Can't make PDO rewind work with PDO::FETCH_ORI_ABS - php

I need to scan several times the variable and using mysql_data_seek I had no problems. Now that I'm trying PDO I can't make it work.
I use it like this:
while($rowAssistant = $rowSetAssistantsProject->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0)){
but it doesn't go inside the while (I guess because it is on the end of $rowSetAssistantsProject)

There is no mysql_data_seek in PDO and the current mysql-php connections do not support cursors. What you should do instead is pull all your data into an array and iterate over that.
$rows = $rowSetAssistantsProject->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
// Process rows
}
// Where you would have reset mysql_data_seek back to 0 if it existed
foreach($rows as $row) {
// More row processing
}
Once your data is in array form you can place a cursor on the array using the reset function like this post does. But the code above is what I have had to do since I moved to PDO. Hope that helps.

Related

Use your fetch data from Mysql and reuse [duplicate]

$data=$stmt->fetchAll(); //Dumping the data shows the result. It is also setting the cursor at the end
while($data=$stmt->fetch())
{
//Does not enters loop
//If fetchAll() removes it work as usual
}
I know It dont need to fetch data twice. But my main question is How to reset cursor position in PDO?
AFAIK there is no possibility to reset cursor position with PDO - that might something to do with compatibility with some databases, that don't support resetting internal cursors.
If you want to iterate twice over the results, fetch it to the array and iterate over this array:
<?php
$results = $stmt->fetchAll();
foreach($results as $row) {
// first
}
foreach($results as $row) {
// second
}
Edit Some databases support scrollable cursors. To use that, add PDO::CURSOR_SCROLL flag to prepare method (see examples at PDOFetch documentation page). But that only adds possibility to move forward or backward, not rewind completely. Also, not all databases support that type of cursor (e.g. MySQL doesn't).

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'");

Trouble retrieving data using PDO syntax, PHP

I'm brand new to the PDO syntax and I'm liking the learning curve! I'm refactoring code - migrating over from archaic mysqli_* methods.
Predictably, I've run into some snags, being a novice. One of the big ones is (forgive if this is a dumb question) retrieving data from the DB and echoing it out on the page. Here is what I have so far:
$getURLid = $_GET['id'];
$idQuery = $connection->prepare("SELECT * FROM pages WHERE page_id = :getURLid");
$idQuery->execute(array(':getURLid' => $getURLid));
$idRetrieved = $idQuery->fetchAll(); // This is the part I'm unclear on.
When I echo $idRetrieved['value'] to the page, nothing shows up. I'm missing something or misunderstanding how it works. Maybe fetchAll isn't what I should be using.
If it is, is a loop necessary to retrieve all rows? I was under the impression that fetchAll would loop through them automatically based on what I've read.
Thanks for the help.
Read the doco for PDOStatement::fetchAll closely. It returns an array of row data.
The type of data representing each row depends on your fetch mode which by default is PDO::FETCH_BOTH. This would mean each row is an array with both numeric and associative keys. If you're only going to access the data associatively, I'd recommend using PDO::FETCH_ASSOC, eg
$idRetrieved = $idQuery->fetchAll(PDO::FETCH_ASSOC);
You would then either need to loop or access each row via its index, eg
foreach ($idRetrieved as $row) {
echo $row['value'];
}
// or
echo $idRetrieved[0]['value']; // assuming there's at least one row.

Basic Understanding Needed: PHP MySQLi Row Navigation

I'm using PHP and MySQLi and following a tutorial-type example and have some basic behavioral questions. A php code sample follows (hm, hope I format it correctly, 1st post here):
<?php
$db = new mysqli('hostLiteral', 'userLiteral', 'passwordLiteral', 'people');
$results = $db->query("SELECT * FROM people")
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
?>
I used a DBMS many, many years ago and perhaps it's that behavior that's keeping me from understanding this.
My perception is that when the 'SELECT * FROM people' is executed, MySQL would scan the entire database, get all the pertinent data, and end up 'pointing' at the last record in the database. So when the 'while' loop begins, I would think that's where it's starting, it would only get the last record or row and be done.
But even if it did somehow start at the top of the database at the first row, how does it know to move through the database unless 'fetch_object()' is somehow telling it to move to the next row?
I'm certain I'm missing basic SQL behavior here. But I've not found a good explanation to dispel these concepts that were placed in my head years back.
Thanks for any aid in understanding!
The query leaves the cursor pointing at the first row of your result set rather than the last. Since the general use case is to move forward through the rows, it would make little sense to leave the cursor at the last row.
In addition, fetch_object does exactly what you surmise. It gets the current row and advances the cursor to the next row. It's interesting that the documentation doesn't state that explicitly (like it does with fetch_row, but the example given makes it clear enough that that's what it does:
/* fetch associative array */
while ($obj = mysqli_fetch_object($result)) {
printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
}

Mysqli_fetch_assoc($result), pointer moves to the next record. Is there any way to reset the pointer to the start of the query result?

Have a look at this code
Suppose you are looping through a set of mysql query results in php
while($temp = mysqli_fetch_assoc($result))
{
echo $temp['id']; // ID Column
}
When you do $temp=mysqli_fetch_assoc($result), basically the pointer moves to the next record. Is there any way to reset the pointer to the start of the query? As after the end of this loop mysqli_fetch_assoc($result) will only return empty rows, making it unusable again. So what's the possible solution?
So I was stuck with this problem at work today, and the only solution I initially found was to re-query, or use temporary copy of mysql result in a variable. Neither of which were appealing.
There is a much simpler solution to this which is mysql_data_seek.
Basic syntax is mysqli_data_seek(data,row)
So in this case you just do
mysqli_data_seek($result,0)
$row=mysqli_fetch_assoc($result);// Will now return the first row.
In a similar way you could loop through it again too.
It works similarly with mysql_data_seek. Hope it was helpful.
Quit that thing of printing data directly out of database loop. Learn to separate your business logic from presentation.
Get yourself a database wrapper, to get rid of all these ugly numerous mysqli_fetch_assoc from your code.
Store query result in array.
Use this array as many times as you wish.
Like this
$data = $db->getAll("SELECT * FROM table");
foreach ($data as $row) // 1st iteration
foreach ($data as $row) // 2nd iteration
foreach ($data as $row) // and so on

Categories