$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).
Related
Is there any way to print the resource_id without mysql_fetch_array.I dont want to loop through result.I want print only the first row at top.I know mysql has been depreciated.This is for old project.
You can make use of arrays in your case
$all_rows = array();
.
. // your query
.
while($dbrow = mysql_fetch_array($query))
{
$all_rows[] = $dbrow;
}
$first_row_array = $all_rows[0]; // first row will be stored here
/*
uncomment the below line if you do not want to use the
first row again while looping through the remaining
rows
*/
/* unset($all_rows[0]); */
foreach($first_row_array as $first_row)
{
// do something with first row data
}
foreach($all_rows as $dbrow)
{
// loop through all the rows returned including the first row
}
A resource in itself is a pretty meaningless type. It only means something to specific functions, like mysql_*. When querying the database, there are certain resources allocated on the MySQL server which hold your requested result; PHP doesn't really have access to those results yet. To give you a handle on those resources on the MySQL server, you get a resource type variable. It's basically just your ticket, saying "if you ever want to access that data waiting for you on the MySQL server, use this number."
So, if you want to output the data from the MySQL server, you will have to fetch it from there, e.g. with mysql_fetch_assoc. That then returns the data to you which you can print.
If you just want the first result, just call that function once.
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.
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);
}
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.
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