PHP while looping endlessly instead of iterating through MySQL table rows - php

I can't figure out why this keeps breaking my page. Could someone take a look? Thanks!
while ($row = mysql_fetch_array(mysql_query("SELECT * FROM `mytable` WHERE `col1` = 0"))) {
echo $row['id'];
}
I've seen this type of while loop show up pretty regularly in google searches and just browsing through stackoverflow. I don't know why it isn't working for me.
How would I achieve the desired result? (Echo the id of each row where col1 = 0)

Obviously it is because you create new MySQL resource with every iteration and then use it's first row.
Use something like
$res = mysql_query("...");
while ($row = mysql_fetch_array($res)) {
echo $row['id']'
}
By the way, you do know that mysql is deprecated, do you not?

$result = mysql_query("SELECT * FROM `mytable` WHERE `col1` = 0");
while ($row = mysql_fetch_array($result)) {
echo $row['id'];
}

Related

SQL SELECT * returns only one row

I'm designing a website and I wrote some webpage that display the list of users.
I used to do a
$query = SELECT * FROM `table_users` WHERE `id`='.$id.'
and then increment the ID with a "while" so I can grab all the users. But it's too slow now, and it glitches when there is a gap between IDs.
So I tried something like
$query = SELECT `name` FROM `tbl_user`ORDER BY `id`
and displaying the userlist with a
while ($i < sizeof(mysql_fetch_array(mysql_query($query)))){
<code to display an user>
$i++
}
But the mysql_fetch_array only returnes one user, the first one (the one with the littliest ID). I want it to return all users in an array. How do I do ?
Try This
$query = "SELECT `name` FROM `tbl_user` ORDER BY `id`";
$user_query = mysql_query($query);
$i=1;
while ($row = mysql_fetch_array($user_query)){
echo $i." : ".$row['name']."<br>";
$i++;
}
Try it like this:
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//$row is the row which was just gathered
}
And please, use PDO or MySQLi instead of deprecated mysql.

array in foreach loop

I'm taking data from mysql database table. The table have ID and "POST" columns. I've ordered posts by id's from bottom so i always have the newest post on the first place. But when i want to echo specific post (eg. with id 5) i can't echo it with $col = mysqli_fetch_array($result); echo $col;. I've tried with foreach loop but it echo's all posts. So I thought if i could put them into array with foreach loop it would do the job.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
}
I've tried a lot of things and spent a lot of time on research but still don't have idea how to do it.
Thanks for your ideas and help.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
if($col['id'] == 5) {
print_r($col);
}
}
mysqli_fetch_array fetchs a result row as an associative, a numeric array, or both.
You need to specify the name of the column you want to print out.
Because you may have more than one row in your result set, you should use a loop (while) like so:
while ($row = mysqli_fetch_array($result)) {
echo $row['POST']; // 'POST' here is the name of the column you want to print out
}
Hope this helps!
UPDATED:
If you want to get a specific post, you have to change your SQL to something like this:
$sql = "SELECT * FROM `post` WHERE `id` = $wanted_post_id";

searching a table in a database with result from another table

hi i am trying to write a php to grab a specific category of post in a wordpress database, this is what i got so far:
$q = "select * from table1 where column like 'condition'";
$r = mysql_query($q);
$id = array();
if($r){
while ($row = mysql_fetch_array($r)) {
$link = $row["object_id"];
$id[] = array(
"postid"=>$link,
);
}
}
else{
echo mysql_error();
}
now i am trying to use the result i got from pervious code to search another table to get something else. i am new to php so i am hoping to get some help
thanks in advance

Query goes in endless loop

The following goes into an endless loop, meaning it just constantly shows the same record over and over and over again.
<?php
while ($rowr = mysql_fetch_assoc(mysql_query("SELECT * FROM table1")) {
while($rowu = mysql_fetch_assoc(mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'"))){
while($rowc = mysql_fetch_assoc(mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'"))){
?>
<tr><td><?php echo $rowc['post']; ?></td><td><?php echo $rowu['username']; ?></td><td><font color="#FF0000">X</font></td></tr>
<?php
};
};
};
?>
Why does that happen and how can I fix it?
You are putting the mysql query in the while statement so every time it gets there it does the same query and shows the same first record, you are never advancing to the next record in the result set.
Personally I would combine all queries into one, but to show how you can solve your problem (the same applies to all loops):
$results = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
while ($rowc = mysql_fetch_assoc($results))
{
// do stuff
}
Simply because the query gets executed again every time the loop condition is checked. That means you'll always get the same result unless something changes in the database in the meantime.
You need something like this:
<?php
$res1 = mysql_query("SELECT * FROM table1");
while ($rowr = mysql_fetch_assoc($res1)) {
$res2 = mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'");
while($rowu = mysql_fetch_assoc($res2)){
$res3 = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
while($rowc = mysql_fetch_assoc($res3)){
?>
<tr><td><?php echo $rowc['post']; ?></td><td><?php echo $rowu['username']; ?></td><td><font color="#FF0000">X</font></td></tr>
<?php
}
}
}
?>
That's just to illustrate why it doesn't work. As others already noted, combining your queries into one using JOIN would be advisable.
Btw, you don't need a ; after a {} block.
Use joins and you can do it in one query.
Mysql Join
Join Tutorial
You're re-executing the queries on each loop iteration, restarting the results from scratch.
You want something like this instead:
$resultR = mysql_query("... table1");
while($rowR = mysql_fetch_assoc($resultR)) {
$resultU = mysql_query("... table2");
while($rowU = mysql_fetch_assoc($resultU)) {
etc...
}
}
Of course, this is a highly inefficient construct. You end up running count($rowR) * count($rowU) * count($rowC) queries. Why not reformulate it as a join?

Question if my code is a low resources one

Hi please tell me if this is a low resources piece of code, and if it is not how shall I change it ? Thank you!
$query = 'SELECT MAX(ID) as maxidpost
FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$postid = $row['maxidpost']+1;
echo "p=$postid";
The improvement is debatable, but:
$query = 'SELECT MAX(ID) +1 as maxidpost
FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo "p = ". $row["maxidpost"];
You can do math in SQL statements, saving you from having to do the operation in PHP.
It'd be nice to know what you're using this for - if it's the next id to be inserted, using AUTO_INCREMENT would be safer. SELECT statements are generally given higher priority over INSERT/UPDATE/DELETE, and thus can read before an insert from another source -- which would risk duplicates.
Because you are returning one row, you should do something like:
$query = 'SELECT MAX(ID) as maxidpost FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
$postid = $row['maxidpost']+1;
echo "p=$postid";
Otherwise seems about as good as you could do.
You can recalculate the post code after each post. Start with zero. Select it from the database, use that id, add one, save back to database.
Or you could use auto increment (if that is possible).

Categories