简体   繁体   English

将SQL中的行插入PHP中的数组

[英]Insert rows from SQL to array in PHP

Can anyone tell me why row[0] has data, but row[1] to row[3] are undefined (empty)? 谁能告诉我为什么row[0]有数据,但是row[1]row[3] undefined (空)?

I have 4 rows in my database having bookid = '35' . 我的数据库中有4行具有bookid = '35'

<?php
$mysqli = new mysqli('localhost', 'root', '', 'assignment3');
$query = "select image from images where BookId='35'";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_NUM);
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
?>

You need to use fetch_array every time you want to extend to the next row. 每次要扩展到下一行时,都需要使用fetch_array Using the numeric indices ( 0, 1, 2 ... n ) only retrieve the columns by number in the row. 使用数字索引( 0, 1, 2 ... n )仅按行中的数字检索列。

Try this: 尝试这个:

$row = $result->fetch_array(MYSQLI_NUM);
print_r($row); // row 1
$row = $result->fetch_array(MYSQLI_NUM);
print_r($row); // row 2
$row = $result->fetch_array(MYSQLI_NUM);
print_r($row); // row 3
$row = $result->fetch_array(MYSQLI_NUM);
print_r($row); // row 4

If this makes sense to you, you can even abstract this into a for loop: 如果这对您有意义,您甚至可以将其抽象为for循环:

for ($i = 0; $i < 4; $i++) {
    $row = $result->fetch_array(MYSQLI_NUM);
    print_r($row);
}

It is much convenient to use mysqli_fetch_all() , since it returns all the rows as an array in a single step. 使用mysqli_fetch_all()非常方便,因为它可以在单个步骤中将所有行作为数组返回。 But it may consume much memory in case of large result-set. 但是,如果结果集很大,可能会占用大量内存。

Eg. 例如。

<?php
$mysqli = new mysqli('localhost', 'root', '', 'assignment3');
$query = "select image from images where BookId='35'";
$result = $mysqli->query($query);
//MYSQLI_NUM for numerical array,
//This will return both associative and numerical, if not specify any parameters.
$row = $result->mysqli_fetch_all(MYSQLI_NUM);
//this will print all rows
print_r($row);

//now it is valid to call
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
?>
select image from images where BookId='35'

This only returns one column so this is why $row[0] works and $row[1] 这仅返回一列,因此这就是$ row [0]和$ row [1]起作用的原因

You need this: 你需要这个:

SELECT * FROM images WHERE BookId = '35'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM