Check if PDO Query has Fetched all Rows Matching Where Conditions - php

I'm a novice PHP programmer in need of help. Is there a way to check if there are no remaining records within a PDO while loop? Within the while loop I'm adding up one of the fields and have an if statement to check if the total has eclipsed a variable.
Within the if statement I do all the data manipulations. My problem is if there aren't enough records to eclipse the variable I never get to the data manipulations.
Code:
$stmt = $db->query("SELECT * FROM table WHERE ... ");
while ($rows = $stmt->fetch(PDO::FETCH_ASSOC)) {
$add_column = $rows['number'];
$total_column = $total_column + $add_column;
//Other Stuff
if ($total_column > $variable_balance) {// Would like to also check here if there are no remaining records to fetch.
//Do Stuff
exit;
}
}

You can make sure that you fetch all records by using $stmt->fetchAll(PDO::FETCH_ASSOC) instead of $stmt->fetch(PDO::FETCH_ASSOC)
If you want to use fetchAll you can use a for-loop
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
foreach($rows as $row) {
$add_column = $row['number'];
//other stuff
}
}
This will automatically perform the actions for all records.

Related

Selecting multiple rows in a table

I need to select multiple comments (if there are any) based on the photo_id. As I understand it you can use the WHERE clause but I'm not exactly sure how to select multiple ones and store them in some kind of array?
e.g.
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
$row = $result->fetch_assoc(); // but there's more than 1 row
If for example $photo1id == 21, how do I get all the comments (2 in this case)? Some kind of while loop?
At the end of the PHP file I have this:
echo json_encode(array('photo1id'=>$photo1id));
I need to store each row in that array somehow because I need to retrieve the data in another PHP file using $.getJSON. Or perhaps there is a better solution to this.
Loop through it and generate an array -
while($row = $result->fetch_assoc()) {
$comments[] = $row;
}
After that you can send the array as json.
echo json_encode($comments);
Is there is more rows, you need to use a loop.
while ($row = $result->fetch_assoc()) {
// your code here
}
Try the code below:
//Run query
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
//While there is a result, fetch it
while($row = $result->fetch_assoc()) {
//Do what you need to do with the comment
}
If you don't want to print the code straight away you can just create an array:
$x=0;
while($row = $result->fetch_assoc()) {
$comment[$x]=$row['comment'];
$x++;
}

how to check, if there are still rows left from fetch_assoc loop?

I loop trough the rows with this code:
while ($row = $result->fetch_assoc()) {
//...
}
But how is it possible before the mysqli_fetch_assoc to check if there will be a next record, or not? I mean, like: $result->hasNext()
Check the total number of returned rows using $mysqli->num_rows, then compare it to a counter in your loop that you increment with each loop iteration.
$row_cnt = $result->num_rows;
$loop_ct = 0;
while($row = $result->fetch_assoc()) {
if(++$loop_ct < $row_cnt) {
//do something
}
}
I prefer working efficiently and don't write extra code if it isn't needed. The following will work just fine:
$cnt = $result->num_rows;
while($row = $result->fetch_assoc()){
//....
$cnt--;
if($cnt == x){ //Where x is the number you want
//....
}
}
You're doing a while loop until you don't have any rows left, so the question is do you really need a test or do you just run the code you want at the end of your loop? If you need to test inside whether there will be a next row, you could do this:
$row = $result->fetch_assoc();
while (1) {
...
if (!$row = $result->fetch_assoc()) {
// No next row
break;
}
}
Which is pretty similar to what you're doing now.
Consider the code you posted
while ($row = $result->fetch_assoc()) {
//...
}
It is already doing that. check out the docs for mysqli_result::fetch_assoc, the while loop will break if $result->fetch_assoc() returns NULL. You don't need to manually check anything.
Either you can go with #McWayWeb or you can try this function mysqli_next_result().
Read it's manual here:- http://php.net/manual/en/mysqli.next-result.php

Mysqli prepared statement: store rows in an array and loop through this array later

I use a prepared statement to select rows in a database. Subsequently I would like to echo the individual rows using a while loop. This worked fine, until I tried using a new query within the execution of the while loop (this was necessary because I extract the userID, which I need to transform into a username. I did this by performing a query on the users table, but when I try this, my code doesn't run). I thought I might fix this by storing all the rows in an array, and later in my code loop through this array. However, I can't seem to figure out how to loop through all indices of this array and extract all fields of the row in each instance of the loop.
Thanks a lot! Here is my code:
$results = array();
$stmt = $db->prepare("SELECT admissionID,userID,description,link,postingdate,compensation FROM replies WHERE projectID=?");
$stmt->bind_param('i',$projectID);
$stmt->execute();
$stmt->bind_result($admissionID,$userID,$description,$link,$postingdate,$compensation);
while($row = $stmt->fetch()){
$results[] = $row;
}
foreach($results as $result) {
echo $result['admissionID'];
}
This is how you need to do it
ids=array();
while($row = $stmt->fetch()){
ids[]= $row['userID'];
}
ids is an array and will have all the ids that you need.
But I would say "Dont do it like that", just use a table join to get the username for example may be your case would be like
SELECT replies.admissionID,users.name,replies.userID,replies.description,
replies.link,replies.postingdate,replies.compensation FROM replies, users
WHERE
users.name=replies.userID
and replies.projectID=?

How can I get and display all values of a certain field in a sql table?

I have a table wherein I need to get all the data in one column/field, but I can't seem to make it work with the code I have below:
$con=mysqli_connect("localhost","root","","database");
$result = mysqli_query($con,"select * from client");
$row = mysqli_fetch_array($result111);
echo $row['name'];
With the code above, it only prints one statement, which happens to be the first value in the table. I have 11 more data in the table and they are not printed with this.
You need to loop through the recordsets .. (A while loop will do) Something like this will help
$con=mysqli_connect("localhost","root","","database");
$result = mysqli_query($con,"select * from client");
while($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
The mysqli_fetch_array() function will return the next element from the array, and it will return false when you have ran out of records. This is how you can use while loops to loop through the data, like so:
while ($record = mysqli_fetch_array($result)) {
// do something with the data...
echo $record['column_name'];
}

Looping Through SQL Results in PHP - Not getting Entire Array

I'm probably missing something easy, but I seem to be blocked here... I have a MySQL database with two tables and each table has several rows. So the goal is to query the database and display the results in a table, so I start like so:
$query = "SELECT name, email, phone FROM users";
Then I have this PHP code:
$result = mysql_query($query);
Then, I use this to get array:
$row = mysql_fetch_array($result);
At this point, I thought I could simply loop through the $row array and display results in a table. I already have a function to do the looping and displaying of the table, but unfortunately the array seems to be incomplete before it even gets to the function.
To troubleshoot this I use this:
for ($i = 0; $i < count($row); $i++) {
echo $row[$i] . " ";
}
At this point, I only get the first row in the database, and there are 3 others that aren't displaying. Any assistance is much appreciated.
You need to use the following because if you call mysql_fetch_array outside of the loop, you're only returning an array of all the elements in the first row. By setting row to a new row returned by mysql_fetch_array each time the loop goes through, you will iterate through each row instead of whats actually inside the row.
while($row = mysql_fetch_array($result))
{
// This will loop through each row, now use your loop here
}
But the good way is to iterate through each row, as you have only three columns
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['email']." ";
}
One common way to loop through results is something like this:
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
// do stuff with $row
}
Check out the examples and comments on PHP.net. You can find everything you need to know there.

Categories