This While loop is Driving me Crazy - php

I want to simply display something using a while loop with php, but it is not working.
Here is the code -
<?php
mysqli_select_db($connect,"users");
$select_title = "select title, message from messages where user = '$u' LIMIT 4 ";
$querying = mysqli_query($connect,$select_title) or die ('Whops! Something went wrong.');
$line = mysqli_fetch_assoc($querying);
//$title = mysqli_real_escape_string($connect,trim($line['title']));
while(($rows = mysqli_fetch_assoc($querying)))
{
echo $rows['title'];
}
?>
Now I have two titles, but only one is being displayed. Why so?

You have fetched one row here:
$line = mysqli_fetch_assoc($querying);
The cursor will be moved to the next row, hence
while(($rows = mysqli_fetch_assoc($querying)))
{
echo $rows['title'];
}
will display the second row only.
The best solution is simply comment that line:
//$line = mysqli_fetch_assoc($querying);

Delete this line:
$line = mysqli_fetch_assoc($querying);

Comment this line will solve your problem
//$line = mysqli_fetch_assoc($querying);

... because you fetch the first title with the line $line = mysqli_fetch_assoc($querying); but never echo it and then start a loop to go through the rest of the titles.
Delete/uncomment the line and you should be fine.

you already fetch one record with
$line = mysqli_fetch_assoc($querying);
so there is only one left in while

Debug
My MySQL is a bit rusty(Long time ago since I used SQL => Moved to NoSQL camp...), but this is what I would do:
First I would test if query returns correct result using phpmyadmin console or just mysql console from commandline.
But I guess the query is correct because a lot of people are saying that
$line = mysqli_fetch_assoc($querying);
is already fetching a row. But still you could use it for debugging purposes I guess.
PDO
Also I would like to point out you should PDO instead of mysqli(almost deprecated I guess). PDO prepared statements also protect you against SQL-injections and could be faster because it is precompiled.

Every time you call mysqli_fetch_assoc() you "take" one record from the result set. When there are no more records, mysqli_fetch_assoc() returns false. This is, by the way, the reason you can use while loop.
When you called $line = mysqli_fetch_assoc($querying);, you took one record from the result set, leaving only 1 in the result set. So your while loop iterates over this one record only. As everyone else pointed out - you just need to comment that line.
I can also recommend using mysqli_fetch_all() function, this will give you an ordinary array that you can use, well, like a normal array
$results = mysqli_fetch_all($querying, MYSQLI_ASSOC);

Related

PHP While loop Update stopping at first row

I made a while loop that will tell if there are items in the transaction history and will put it back in the inventory as the transaction ends but the problem is. It fetches an error called
Uncaught Error: Call to a member function fetch_assoc() on bool in
So I tried the query's one by one and it works.
I tried to experiment and comment the other query and adding a counter++; to tell if the loop works. The problem I found is that after the first if else the counter only add's 1 Where as if I only try this it loops 4 which is right
Query I tried to check the number of loops
$counter=0;
$sql="SELECT * FROM brb_backtransaction WHERE trans_uk='$curr_trans' ";
if($rs=$con->query($sql)){
while ($row=$rs->fetch_assoc()){
$counter++
}
}
It echoes 1234 so it's correct but when the first if else happen it only echo'es 1
$counter =0;
$sql="SELECT * FROM brb_backtransaction WHERE trans_uk='$curr_trans' ";
if($rs=$con->query($sql)){
while ($row=$rs->fetch_assoc()){
$item = $row['trans_item'];
$quan = $row['trans_quantity'];
$sqlsitem="SELECT itmQuantity FROM brb_inventory WHERE itmName='$item'";
if($rs=$con->query($sqlsitem)){
$quanrow = $rs->fetch_assoc();
$currquan = $quanrow['itmQuantity'];
$counter++;
}
I remove other query's as I think this is the problem I ran a total of 3 queries in the while loop.
For your while loop to work it needs access to your original data stream as stored in the $rs variable.
However, further down in your code you are replacing the contents of the $rs variable with a totally new data stream. Therefore, the while loop no longer has access to the original data stream as it is basically throw away.
To solve this, change the second instance to another variable name such as $rs2. That way you have two completely different variables for two different data streams.
With that said, your code is also open to injection attacks. I would recommend looking into PDO and prepared statements.
Also, Tangentially Perpendicular is correct in using SQL JOINS

PHP while() fails to stop looping

I was getting a problem because using while() function but I'm solving it for five or six hours today. I'm asking here because I don't understand how it could be.
Here is my code
$sql = mysql_query("SELECT saldo from stock where id >= '$id' and idItem = '$idItem';")
if I try :
$row = mysql_fetch_array($sql);
while($row)
{ // my code is here
}
then, while() fails to stop looping. but if I try like this:
while($row = mysql_fetch_array($sql))
{//my code is here
}
by that code, I'm getting the correct result.
I feel this is little strength because I think the first and the second code have same function.
thanks for you comments or answers!
mysql_fetch_array() fetches one row at once when you use in while it fetch next row every time. It returns true if there is any next row to fetch and false if there is not.
For preventing infinite loop, Use this is correct syntax for fetching:
while($row = mysql_fetch_array($sql))
{
//your code
}
Note: The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead,
use the MySQLi or PDO_MySQL extensions
$row is not affected by the loop, so of course it keeps looping. You probably want something like this:
while($row = mysql_fetch_array($sql))
{ // processing code goes here
}
In your first snippet, the loop condition is always true because the value of $row never changes and you're ending up in an infinite loop.
In the second snippet, $row is re-assigned upon each loop iteration and once it's null (usually at the end of the recordset in the case of mysql_fetch_array) the loop terminates.
Because first code uses same $row every time, the loop never stops and it doesn't even fetch the result per each iteration.
But the second code fetches result every time, the loop works as you expected.
The reason the second one eventually stops, is because every call to mysql_fetch_array() will call the next row from your database query. Once all the rows have been called, it will start returning false and this is what ends the loop.
It can be a little confusing because you're not seeing any counter, but the counter is really hidden inside the mysql_fetch_array() function, and will eventually terminate.
But if you put that call outside the while loop, it's only called once and you keep iterating the same row.
$row = mysql_fetch_array($sql);
while($row)
{ // my code is here
}
mysql_fetch_array fetches 1 and only 1 row from your table into $row, so if you have one row matching your query you dont need a while
if the resulting query has more than 1 row you need to make a while to the mysql_fetch_array like this:
while($row=myql_fetch_array($sql){}
now you can get all the rows from your table
The value of $row is not changed in the first case. You would need to update it again within the loop with another assignment, so your 2nd statement is better, as it does it all in one go :)
For -
$row = mysql_fetch_array($sql);
while($row)
{ // my code is here
}
$row is always true as it contains the values so the loop will be executed infinitely. And
while($row = mysql_fetch_array($sql))
{//my code is here
}
$row is ture untill the mysql_fetch_arrya has values.
mysql is deprecated. Try to use mysqli or PDO instead.
Try this code:
You have a semicolon inside your query.. your semicolon must be at the end of the mysql_query() function. That may be the cause of your infinite looping in while loop.
$sql = mysql_query("SELECT saldo FROM stock WHERE id >= '$id' AND idItem = '$idItem'");

php mysql result coming back wrong, every time from php, but is fine in sql pro and phpmyadmin

The following statement is returning a 1 in php. I've serialized and output the result and every other credential, and it is doing this on three seperate queries. When I run the query in sqlpro or phpmyadmin I get the result as 8. Please tell me someone has a bright idea.
$numRFPsSwitch = 0;
$bquery = " SELECT COUNT(rp.id) AS 'NumRFPs'
FROM rfp_proposal rp
WHERE rp.vendor_id = 1 AND rp.id IN(13,15,16,23,24,26,4,9) ";
$bresult = mysql_query($bquery, $connection);
$XMLFormatedString .= 'NumRFPs="';
while ($brow = mysql_fetch_object($bresult)){
$XMLFormatedString .= $brow->NumRFPs;
$numRFPsSwitch = 1;
}
What's returning 1? $numRFPsSwitch which is set to 1? :) $XMLFormatedString should have the correct value, your example works fine for me.
The result will always be a single row. So the loop should be replaced with an if.
Concerning the problem: Did you check your $connection?
Perhaps you could do a SELECT * (to return all rows involved), and then do a mysql_num_rows(...) on the result to find out the row count. If this returns the same result, then at least you can be sure it's not the query or concatenation that's at fault.
$query = "SELECT ...";
echo mysql_num_rows(mysql_query($query, $connection));
Are you sure you use the right login credentials in mysql_connect() and mysql_selectdb()?
Also: If you dó use the right credentials, are you sure you have the right permissions to select/update/delete etc.

only retrieving 1 row of data from MYSQL database

I am trying to input multiple pieces of data through a form and all the data will be separated by (,). I plan to use this data to find the corresponding id for further processing through an sql query.
Below is the code I use.
$key_code = explode(",", $keyword);
//$key_count = count($key_code);
$list = "'". implode("','", $key_code) ."'";
//$row_count = '';
$sql4= "SELECT key_id FROM keyword WHERE key_code IN (".$list.")";
if(!$result4 = mysql_query($sql4, $connect)) {
mysql_close($connect);
$error = true;
}else{
//$i = 0;
while($row = mysql_fetch_array($result4)) {
$keyword_id[] = $row['key_id'];
//$i++;
}
//return $keyword_id;
}
The problem i see is that keyword_id[0] is the only element that contains any data (the data is accurate). Even if I input multiple values through the aforementioned form.
I thought it might be an error in the sql but I echo'ed it and it looks like:
SELECT key_id FROM keyword WHERE key_code IN ('WED','WATER','WASTE')
The values in the brackets are exactly what I inputted.
I even tried to figure out how many rows are being returned by the query and it shows only 1. I assume something is wrong with my query but I cannot figure where.
Any help will be greatly appreciated.
Edit: Alright Solved the problem. Thanks to suggestions made I copied and pasted the $sql_query I had echo'ed on the website into mysql console; which resulted in only 1 row being retrieved. After taking a closer look I realized that there was a whitespace between ' and the second word. I believe the problem starts when I input the key_code as:
WED, WATER, WASTE
Instead inputting it as
WED,WATER,WASTE
fixes the problem. I think I should make it so that it works both ways though.
Anyway, thank you for the help.
I am pretty sure that the query is ok. How many rows do you get with just
SELECT key_id FROM keyword
I think that there is just one line that matches your WHERE.
Check the query directly in the database(with phpmyadmin, or in the mysql console), however this query seems to be working as you may assumed. If it returns only 1 row when you use it directly in the db, then maybe there is only one row in your table wich matches this query.

Is it possible to check if pdostatement::fetch() has results without iterating through a row?

I have a page which needs to check for results, and the way I came up with to do it is successful, but iterates through the first row of results. Is there a way I can check without iterating, or to go back to that first row without executing the query again?
I was doing this:
$q = pdo::prepare($SQL);
$q->execute(array(':foo'=> foo, 'bar'=>bar);
if(!q->fetch){
//no results;
}else{
//results;
};
It does pretty much exactly what I hoped, with the unfortunate side affect of skipping the first row of results.
I've resorted to running $q->execute() a second time. Is there a way to avoid doing this?
Just put the result of fetch into a variable:
if($row = $q->fetch()) {
// $row contains first fetched row
echo $row['coloumn_name'];
}
else
// no results
If you want to be lazy, you could always do something like:
$totalRows = count($resultSet->fetchAll());
However, this is less than efficient for large result sets.
Otherwise, see the manual page about rowCount() (particularly example #2) for what appears to be the standard workaround. There are some interesting user-supplied comments on that page as well.
May be you'll find SELECT FOUND_ROWS() usefull for this. See example at php.net site http://www.php.net/manual/en/ref.pdo-mysql.php#77984
rowCount() is known to work with mysql, so if portability is not a concern, use that.
otherwise, you can try to change the program logic, e.g.
$stmt->execute();
$count = 0;
foreach($stmt as $record) {
// output...
$count++;
}
if(!$count)
echo "no results!";

Categories