简体   繁体   English

有没有办法在 MySQLi 中获取多行

[英]Is there a way to get multiple rows in MySQLi

I am currently working on a project where I am required to make a list of entries from a SQL table where the id in the column is the same.我目前正在做一个项目,我需要从 SQL 表中创建一个条目列表,其中列中的 id 是相同的。

Here is the table:这是表:

+------+------+
|name  |id    |
+------+------+
|Ex1   |1     |
+------+------+
|Ex2   |1     |
+------+------+
|Ex3   |2     |
+------+------+


I have tried the code below:我试过下面的代码:

$id = '1';
$query2 = "SELECT * FROM entries WHERE id = '$id'";
$data2=mysqli_query($link,$query2);
$row2=mysqli_fetch_array($data2);
$name = $row2["name"];

however that code only returns Ex2 and I would like it to return all the names with the id I specify in $id然而,该代码只返回 Ex2,我希望它返回所有带有我在 $id 中指定的 id 的名称

Loop over successful results with a while loop.遍历成功的结果与while循环。

while($row2=mysqli_fetch_array($data2)){
// echo $name = is valid syntax.
    echo $name = $row2["name"] . "<br>" . "\n";
// The \n used will show clean HTML in source.
}

Side note: You might have to use mysqli_fetch_assoc() instead of mysqli_fetch_array() .旁注:您可能必须使用mysqli_fetch_assoc()而不是mysqli_fetch_array()

Plus, use a prepared statement for this as it's safer, since you could be leaving yourself open to SQL injection.另外,为此使用准备好的语句,因为它更安全,因为您可能会对 SQL 注入持开放态度。

You can use a simple foreach loop to iterate over all the results fetched from the database.您可以使用一个简单的foreach循环来迭代从数据库中获取的所有结果。

Besides, you should use prepared statements with parameter binding.此外,您应该使用带有参数绑定的准备好的语句。

The correct code would look something like this:正确的代码如下所示:

$id = '1';
$stmt = $link->prepare("SELECT * FROM entries WHERE id = ?");
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();

foreach ($result as $row2) {
    $name = $row2["name"];
    // do something with the name
    echo $name.PHP_EOL;
}

Or if you want you can collect all results in an array.或者,如果您愿意,您可以将所有结果收集在一个数组中。

$allNames = [];
foreach ($result as $row2) {
    $allNames[] = $row2["name"];
}

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

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