php - fetch_array gets only one row
问题描述
Howdee, I'm trying to send two MySQL queries, each for a different table, to connect the results afterwards into a single array for further processing. Here's my code:
function list_invoice($invoice_id){
global $conn;
$query_getinvoice = "SELECT * FROM invoices WHERE id = ".$invoice_id;
$query_getlines = "SELECT * FROM invoice_lines WHERE invoice_id = ".$invoice_id;
$result = $conn->query($query_getinvoice);
$result2 = $conn->query($query_getlines);
$invdata = $result->fetch_array(MYSQLI_ASSOC);
$invdata2 = $result2->fetch_array(MYSQLI_ASSOC);
$the_data = array_merge($invdata,$invdata2);
}
My problem with the code above is that in invoice_lines table there are actually three rows with the same invoice_id, but the print_f($the_data) or even print_f($result2) returns only one row. Why's that?
解决方案
This is what fetch_array
is supposed to do. It fetches one row from the data.
To go through all rows you would have to do something like this:
while ($invdata = $result->fetch_array(MYSQLI_ASSOC) and $invdata2 = $result2->fetch_array(MYSQLI_ASSOC)) {
$the_data = array_merge($invdata,$invdata2);
// Do something with this row of data
}
It's also important to note that the way you create the queries right now could lead to SQL Injection if $invoice_id
is user input. An attacker could insert a quote '
to close the string and execute malicious SQL commands. To prevent this you need to use prepared statements to ensure that user input doesn't get interpreted as code. Here's a post explaining how to do that with mysqli: How can I prevent SQL injection in PHP?
As @El_Vajna pointed out this will stop looping when any of the two results end. To make it go further even if only one result has data you can change the and
inside the if
statement to an or
. Then only one needs to contain more rows
推荐阅读
- arrays - Laravel Vue SPA:如何将由 axios 检索到的数组 prop 传递给子组件?
- leaflet - Leafletjs折线不显示弹出窗口
- r - 相关对图:组和密度散点图的不同点颜色
- javascript - 为什么我的脚本不能使用 django 在 html 中运行
- python - 如果 Python 中的循环停止工作,使用 jupyter?
- python - Microbit 不接收从计算机发送的串行数据
- javascript - 打字稿对象解构被 ESLint no-unused-vars 规则捕获
- javascript - 当两个索引存在并排序时返回布尔值的函数?
- c++ - 仅按地址删除节点,但也会删除其他值以及如何防止内存泄漏
- css - 职位:绝对;左属性无法正常工作