Nested while doesn't work in PHP - php

I have problem with my code.
I use nested while in my code and the nested while doesn't work, only the outer while is work
I don't know where is the bug of my code.
This is the piece of my code :
$database = new mysqli('127.0.0.1', 'user', 'user', 'mini_email');
$query = 'SELECT * FROM mails';
$query2 = 'SELECT * FROM users';
$result_set = $database->query($query);
$result2 = $database->query($query2);
while ($row2 = $result2->fetch_assoc()) {
if ($row2['username'] == $_SESSION['user']) {
$id_email = $row2['id'];
}
}
if (isset($_SESSION['is_logged_in'])) {
echo('<center><font size="10">Mailing List</font></center><br><br>');
echo('<center><table border="3" bgcolor="#f0cdfa">');
echo('<tr>');
echo ('<td>No</td>');
echo ('<td>ID</td>');
echo ('<td>From</td>');
echo('<td>Subject</td>');
echo ('<td>Message</td>');
echo ('<td>Action</td>');
echo ('</tr>');
$i = 1;
while ($row = $result_set->fetch_assoc()) {
if ($row['to_user_id'] == $id_email) {
echo('<tr>');
echo ('<td>' . $i . '</td>');
echo ('<td>' . $row['id'] . '</td>');
while($row2 = $result2->fetch_assoc()){
if($row2['id']== $row['from_user_id']){
echo ('<td>' . $row2['username'] . '</td>');
}
}
echo ('<td>' . $row['subject'] . '</td>');
echo ('<td>' . $row['message'] . '</td>');
echo ('<td>View</td>');
echo ('</tr>');
$i++;
}
}

Your initial
while ($row2 = $result2->fetch_assoc()) {
is looping through all the records to the end of the set,
so looping a second time won't retrieve any further records because you're already at the end of the resultset
Resultset pointers aren't automatically reset when you initiate a new loop, but you can reset them manually using
$result2->data_seek(0);
before each subsequent loop
But iterating the point made in the comments by #Sirko you'd be better using a JOIN to make a single query

If I may help, I think you shouldn't even perform the queries when your if statement with the session returns false.
In the first lines or your script you should define a function with all this code, and write it like this :
function YourFunction()
{
if (isset($_SESSION['is_logged_in'])) {
return false;
}
// Database connection and queries
// your business
}
This will be more clean.
Next, your query doesn't seem to be correct. You get all the mails of your website, and then in a loop you check if the mail user id is the user id you have in session. Imagine the lack of performance if you have 35 000 mails in your database.
Improve your query with a WHERE statement : http://www.w3schools.com/sql/sql_where.asp
then, are you sure that $_SESSION['user'] contains an id ? I think your second if statement never returns true because of that.

Related

using fetch twice in php to get the data

I'm trying to get a data from db, I would to say welcome $row['name'];
then in a loop need to print the items
if I did the below code, I will get all items except the first item, but if I deleted the $row2 with the welcoming name, I will get all items why ?
is there a way to use this $row = $SQL->fetch() for both?
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$row2 = $SQL->fetch();
echo "Welcome " . $row2['name'] . "<br>";
while ($row = $SQL->fetch()) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
}else{
echo "<h1>Not Logged in. Access denied.</h1>";
}
?>
When you run fetch() you are moving forward the pointer in the result set. So your first call to fetch() gets the first row, second gets the second row, etc.
Probably the easiest approach would be to pull all results into an array and then work with that.
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$data = $SQL->fetchAll();
$row2 = $data[0];
echo "Welcome " . $row2['name'] . "<br>";
foreach ($data as $row) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
} else {
echo "<h1>Not Logged in. Access denied.</h1>";
}

MySQL PHP use query result more that once in HTML

I have an query that shows data from db. I use while loop to display data. Problem is that I can call (echo) result only once.
Here is my code:
$ime_ = "SELECT * FROM `users` WHERE '" . ($_COOKIE['username']) . "' = user_username";
$ime_result = $mysqli->query($ime_);
and later in my html I use this result as:
<?php
if ($ime_result->num_rows > 0)
while($row = $ime_result->fetch_assoc()) {
echo "<h2>" . $row["Ime"] . "</h2>";
}
?>
This work ok, but I want to use this result to display many times in my html. And when copy while loop again later in html no result is given.
Store the string with data from while() into a variable, than apply echo to that variable as many times as you like..
$re_out ='';
if($ime_result->num_rows > 0){
while($row = $ime_result->fetch_assoc()) {
$re_out .="<h2>". $row["Ime"] ."</h2>";
}
}
echo $re_out;
//etc..
echo $re_out;
<?php
if ($ime_result->num_rows > 0)
$ime_result->data_seek(0); // seek to row no. 1
while($row = $ime_result->fetch_assoc()) {
echo "<h2>" . $row["Ime"] . "</h2>";
}
?>
Haven't run script. Try if it works.

Why can't I loop over $q->fetch() twice?

Assume I'm in need to loop twice with the result I got form PDO prepared statement.
First loop works fine, the next one does not work
The value of var_dump(q->fetch()) is empty array. Any ideas?
<?php
$q = $dbconnection->prepare("SELECT * from users WHERE role=?");
$q->execute(array('$id')); //Boolean true or false
// first loop
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
echo "<br/>" . $row['user_id'] . "--". $row['fname']. "</br>";
}
// second loop this loop will NOT echo any thing ?!
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
echo "<br/>" . $row['user_id'] . "--". $row['fname']. "</br>";
}
When you loop the row, you empty out the result set. If you want to loop over multiple times, you can use fetchAll(), store that in a variable and loop that where you need using a foreach loop.
$q = $dbconnection->prepare("SELECT * from users WHERE role=?");
$q->execute(array($id)); //Boolean true or false
$res = $q->fetchAll();
foreach ($res as $row) {
echo "<br/>" . $row['user_id'] . "--". $row['fname']. "</br>";
}
foreach ($res as $row) {
echo "<br/>" . $row['user_id'] . "--". $row['fname']. "</br>";
}
Alternatively, you can execute the query again, but if you do that, you make a double query to the database. So you query twice for the same data, which isn't very efficient.
Also you had execute(array('$id')), which would be the exact string $id, and not the variable representation. See the PHP manual on strings. So it should be execute(array($id)) instead.
PHP.net on PDOStatement::fetchAll()
Your are fecth a row time by time if you need two iteration you should perform a copy eg storing rows
while ($row = $q->fetch(PDO::FETCH_ASSOC)){
echo "<br/>" . $row['user_id'] . "--". $row['fname']. "</br>";
$my_rows[] = $row;
}
// second loop this loop will NOT echo any thing ?!
foreach($my_rows as $key=>$value){
echo "<br/>" . $value['user_id'] . "--". $value['fname']. "</br>";
}

passing variable to another page for sql query

I am trying to pass a variable from a page to another page so that i can display more information on the other page by getting the idea. I am not really sure what is going wrong and because I use bluemix it doesn`t display an error it just gives me the page 500 error. Here is my code:
<?php
$strsql = "select id, name, problem, urgency, technology from idea WHERE status='saved'";
if ($result = $mysqli->query($strsql)) {
// printf("<br>Select returned %d rows.\n", $result->num_rows);
} else {
//Could be many reasons, but most likely the table isn't created yet. init.php will create the table.
echo "<b>Can't query the database, did you <a href = init.php>Create the table</a> yet?</b>";
}
?>
<?php
echo "<tr>\n";
while ($property = mysqli_fetch_field($result)) {
echo '<th>' . $property->name . "</th>\n"; //the headings
}
echo "</tr>\n";
while ( $row = mysqli_fetch_row ( $result ) ) {
$idea_id= $row['id'];
echo "<tr>\n";
for($i = 0; $i < mysqli_num_fields ( $result ); $i ++) {
echo '<td>' . "$row[$i]" . '</td>';
}
echo "</tr>\n";
}
$result->close();
mysqli_close();
?>
There's a small bug in your code. Your echo <a href ="... line should be like this,
echo '<td>' . $row[$i] . '</td>';

While inside while and 2 result

<?php
$con=mysqli_connect("","","","");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM itiraf");
$result2 = mysqli_query($con,"SELECT oy FROM users WHERE username='". $Account->session('display_name') ."'");
if(mysqli_num_rows($result)=="0"){echo "Henüz itiraf yapılmamış";}
else{
echo "<table border='1' class='imagetable'>
<tr>
<th>NO:</th>
<th>İsim</th>
<th>İtiraf</th>
<th>Oy</th>
<th>Oy Kullan</th>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><b>" . $row['id'] . "</b></td>";
echo "<td><b>" . $row['username'] . "</b></td>";
echo "<td><b>" . $row['itiraf'] . "</b><br></td>";
echo "<td><b>" . $row['oy'] . "</b><br></th>";
while($row2 = mysqli_fetch_array($result2)){
if ($row2['oy'] ==10) { echo "<td>Oy kullandınız</td>";}
else{echo "<td><a href='oy.php?id={$row[id]}'><img src='assets/images/up.png'/></a></td>";}}
echo "</tr>";
echo "</form>";}
echo "</table>"; }
mysqli_close($con);?>
first while is working. also Second while is working but not so well. just one time i can see the thumbs up image. i added all code in here about table. any idea?
In pseudo code, it appends :
{ //first iteration of while($row = mysqli_fetch_array($result))
...
{ //first iteration of while($row2 = mysqli_fetch_array($result2))
}
{ //Second iteration of while($row2 = mysqli_fetch_array($result2))
}
...
{ //last iteration of while($row2 = mysqli_fetch_array($result2))
}
// know, $result2 is empty
}
{//Second iteration of while($row = mysqli_fetch_array($result))
...
//Here, $result2 is empty, so the second while loop doesn't work
}
if you want to reuse $result2, you can store it in an array before, and then use this array in the while loop
Your second while loop iterates over the query result stored in $result2.
So, the first time the second while loop is executed fully, cursor moves to the end of the table and does not come back to the first position.
One solution would be to store all the values of the second query(whose result is in $result2) in another array, and then use that array in the second while loop.
Another solution would be to move the second query itself inside the first while loop, but that would mean that the query will be executed everytime.

Categories