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.
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
Loop over successful results with a while
loop.
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()
.
Plus, use a prepared statement for this as it's safer, since you could be leaving yourself open to SQL injection.
You can use a simple foreach
loop to iterate over all the results fetched from the database.
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"];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.