I have imported data into a table and I am now accessing that data with PHP using the code as follows,
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result->close();
$conn->close();
This works!
I am really just curious why adding a second for-loop does not work, unless I declare $result again?
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . 'Flag<br/>';
}
$result->close();
$conn->close();
Doesn't work, although 'Flag' is printed an appropriate number of times.
Whereas if I declare $result again.
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result = $conn->query($query);
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . '<br/>';
}
$result->close();
$conn->close();
The code does work.
I have tried unsetting a few variables with unset($row) etc and I did notice if I remove the line,
$row = $result->fetch_array(MYSQLI_ASSOC);
from the second for loop, it will print the last value in the Number column as many times as the loop will run.
I hope that is understandable. I am wondering what is happening in the code that I need to re-declare $result if I want to run a second for loop against it.
The standard solution I would recommend is to do fetch_all()
Instead of:
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
Do
$rows = $result->fetch_all();
foreach ($rows as $row)
{
...
}
// then you can re-loop same array of $rows
foreach ($rows as $row)
{
...
}
There is an internal pointer when you call fetch_* function.
In your first for loop, you send the pointer to the end of the result set.
So, the next fetch will return nothing.
If you run $result->data_seek(0) you will reset this pointer and can reuse:
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result->data_seek(0); //<---- REPLACE HERE
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . '<br/>';
}
Of course, usually there is no need to loop the same result set twice, you may need to rethink your logic and loop only once.
Related
Actually with my code I print out all results together but the goal is to associate to a variable each row.
$sql = "SELECT modello FROM THING;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["modello"]; //this print all result but want to associate first result to variable $first and second to $second
}
} else {
echo "0 results";
}
Change echo $row["modello"]; to $modellos[] = $row["modello"]; like so in the example below:
$result = $conn->query("SELECT modello FROM THING");
$modellos = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$modellos[] = $row["modello"];
}
} else {
echo "0 results";
}
Now $modellos has the first in $modellos[0] and the second in $modellos[1] and the third in $modellos[2] etc etc to do with as you wish after the while loop. If you really really need them in $first and $second, add after the loop:
$first = $modellos[0];
$second = $modellos[1];
You can use array to store your results.
$result = []
while($row = $result->fetch_assoc()) {
$result[] = $row["modello"];
}
But if you really need to associate each row to a variable, you can use:
$i = 0;
while($row = $result->fetch_assoc()) {
${"result" . $i} = $row["modello"];
$i++;
}
Usually when you do the basic php excercises you just use the following to print data on a blank page:
<?php
include('../includes/dbh.php');
$titulo = mysqli_real_escape_string($conn,$_GET['titulo']);
$sql = "SELECT * FROM proyectos WHERE proyect_name='$titulo'";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if($queryResults > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div>".$row['proyect_name']. "
</div>";
}
}
?>
My question is, if I try to separate and echo out $row proyect_name in another part of the webpage nothing happens. I used both echo and var_dump and yes, the query works but it just doesn't print anything. I am new to this so yes, it may be obvious to you but not to me. I think it may be the while loop, but I do not know how to "blend it in".
<?php
include('../includes/dbh.php');
$titulo = mysqli_real_escape_string($conn,$_GET['titulo']);
$sql = "SELECT * FROM proyectos WHERE proyect_name='$titulo'";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
$data=array();
if($queryResults > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div>".$row['proyect_name']. "
</div>";
$data[] = $row;
}
}
foreach($data as value) {
echo $value;
}
// OR
foreach($data as $key => $value) {
echo $key . " - " . $value;
}
?>
Set variable before loop then add $row data to it then loop it out with a foreach loop Does this work??
Use mysqli_fetch_array() - Example
So in your case it would be
<?php
include('../includes/dbh.php');
$titulo = mysqli_real_escape_string($conn,$_GET['titulo']);
$sql = "SELECT * FROM proyectos WHERE proyect_name='$titulo'";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if($queryResults > 0){
while ($row = $result->fetch_array()){
$rows[] = $row;
}
foreach ($rows as $row) {
echo "<div>".$row['proyect_name']."</div>";
}
}
?>
I am a completely newbie in programming php I would like to make this code below return many arrays(to flash as3), however I only receive one array.Can anyone please pinpoint what is my mistake here? thanks.
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
echo "returnStr=$data_array";
exit();
}
When you write your exit insight your loop you stop executing your program and you get only one record. You should set the echo and exit after your while loop.
$data_array = "";
$i = 0;
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql)) {
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1) {
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
} else {
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
Those two last line of your should be outside of your loop:
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
If you would name the columns that you want in the SELECT then it's much simpler. Make sure to use MYSQLI_ASSOC in the fetch:
$sql = mysqli_query($conn, "SELECT Username, Fb_id, Access_token, Fb_sig, Char_id FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC))
{
$data_array[] = implode('|', $row);
}
echo "returnStr=" . implode('(||)', $data_array);
exit();
I have a table named members with 3 rows. The following code attempts to display all the rows in the members table. It displays the 1'st record 3 times instead of displaying each record once.
<?php
$con = new mysqli("localhost", "root", "jce123", "profile");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
$keysarray = array_keys($array);
$valuearray = array_values($array);
for ($i=0; $i < $num; $i++) {
for($j = 0; $j < count($array); $j++) {
echo "<table>";
echo "<tr><td>".$keysarray[$j].": </td><td>".$valuearray[$j]."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
mysqli_close($con);
?>
I've updated this per suggestions:
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
while ($row = mysqli_fetch_assoc($res)) {
foreach($array as $key => $value){
echo "<table>";
echo "<tr><td>".$key.": </td><td>".$value."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
That's because, your $num = 3, count($array) = 3 and the outer for loop has no bearing on inner for loop.
Where you have $array = mysqli_fetch_assoc($res);, you will only receive one row from your database. You need something like:
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
}
Any basic tutorial will tell you this. Even the PHP docs provide an example.
you can use do something like this..
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
e.g
echo $row['id'];
echo $row['name'];
etc
}
try this... this peace of code is not tested but just to give you an idea...
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
echo "<table>";
echo '<tr><td> id = "'.$row['id'].'":
</td><td> name = "'.$row['name'].'"</td></tr>";
echo "</table>";
}
The query I have below will only show me one result even if there are multiple matching entries (completely or partially matching). How do I fix it so it will return all matching entries:
//$allowed is a variable from database.
$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM
`users` LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name`
LIKE '%$q%' ) LIMIT $startrow, 15";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$num_rows1 = mysql_num_rows($result);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$person = htmlspecialchars($row['full_name']);
}
}
}
print $person;
Because your overwriting $person on each iteration.
Hold it in a $person[] array if your expecting more then one. Then loop through it with a foreach loop when you intend to output.
Not related but your also querying twice, you only need 1 $result = mysql_query($sql);
Update (Simple Outputting Example):
<?php
$person=array();
while($row = mysql_fetch_array($query)){
$person[] = array('full_name'=>$row['full_name'],
'email'=>$row['email'],
'somthing_else1'=>$row['some_other_column']);
}
//Then when you want to output:
foreach($person as $value){
echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>
Or an alternative way to is to build your output within the loop using concatenation.
<?php
$person='';
while($row = mysql_fetch_array($query)){
$person .= '<p>Name:'.$row['full_name'].'</p>';
$person .= '<p>Email:'.$row['email'].'</p>';
}
echo $person;
?>
Or just echo it.
<?php
while($row = mysql_fetch_array($query)){
echo '<p>Name:'.$row['full_name'].'</p>';
echo '<p>Email:'.$row['email'].'</p>';
}
?>