Reset row pointer of a mySQL result (PDO) [duplicate] - php

This question already has answers here:
Resetting array pointer in PDO results
(7 answers)
Closed 8 years ago.
I need to loop through the results of a query a few times. After the first loop, I cannot go through the results again as the pointer is at the bottom. How can I make it return to the top? I dont want to run the query again as that is just going to use up more resources and return the same results.
$stmt = $conn->prepare("SELECT * FROM customers");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
//This kind of loop will repeat elsewhere in the code
while($row = $stmt->fetch()){
//Do something here
}

while($row = $stmt->fetch()){
$rows[] = $row; //use $rows later
//Do something here with $row
}

Related

PHP not writing SQL result to JSON file [duplicate]

This question already has answers here:
php JSON_encode not working
(4 answers)
Closed 1 year ago.
What I am trying to achieve is to simply put all the rows of a mysqli result to a JSON file.
My code looks like this:
$sth = mysqli_query($mysqli, "SELECT * FROM table");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print_r($rows);
$mysqli->close();
$fileobj = fopen("takeOutItems.json", 'w');
fwrite($fileobj,json_encode($rows));
fclose($fileobj);
printing the $rows arrays shows data correctly.
fwrite, however, does not change anything in takeOutItems.json.
What am I doing wrong?
The issue was that some data elements were not displayed correctly. Adding $mysqli->set_charset("utf8"); resolved the issue.

Remind first row after getting all data - PHP PDO [duplicate]

This question already has an answer here:
Reset cursor position in PDO
(1 answer)
Closed 4 years ago.
I am using php PDO for server connection. just like that
$stmt = $pdo->prepare('call naviSql( ?, ?, ? )');
$stmt->execute( array( $someone, $on_navi, $on_date ) );
while( $row = $stmt->fetch( ) ) {
echo '';
}
now after echoing out all the data, how i can remind first row values once again?
Use fetchAll instead and store all your results in a variable. The first row can then be accessed by its index, i.e.:
// Store all fetched rows in a variable
$results = $stmt->fetchAll();
// Iterate through all your results
foreach($results as $row) {
echo '';
}
// Re-access the first row
$firstRow = $results[0];
print_r($firstRow);

The mysql_fetch_array() is duplicating every thing [duplicate]

This question already has answers here:
remove duplicating fields in php-mysql result rows
(2 answers)
Closed 8 years ago.
Hey guys (and girls) I'm having a problem with arrays, this code below looks like duplicating each column inside a array! :/
<?php
//quantidade_de_registro
include("mysqlconfig.inc");
$query = "SELECT * FROM contas ";
$res = mysql_query($query);
while($row = mysql_fetch_array($res)){
$arr[] = $row;
}
echo json_encode($arr);
mysql_close($con);
?>
It will returns something like this:
[{"0":"5","ID":"5","1":"Zenny","Login":"Zenny","2":"Zeny","Nome":"Zeny","3":"daniel_queiroz789#hotmail.com","Email":"daniel_queiroz789#hotmail.com","4":"23021994","Senha":"23021994"}]
Each Column appears twice, But I need each column appears just once, a friend mine said that I need to re-parse the array and put it into the array, I don't know what it means or how I can do that :/
Please help :)
you can modify your script by adding a second parameter to the fetch
mysql_fetch_array($res,MYSQL_ASSOC)
However I will second that you should use PDO or mysqli instead
Use mysql_fetch_assoc
No, don't do that. Instead use PDO or mysqli and their respective fetch methods.
mysql_fetch_array fetches both numeric and associative arrays simultaneously.
mysql_fetch_array() as it's second paramter by default at "MYSQL_BOTH" meaning it return an array with both numerical and associative key.
To have only one of those, you can specify it in the call
mysql_fetch_array($res, MYSQL_ASSOC); // for assosiative
// OR
mysql_fetch_array($resm MYSQL_NUM); // for numeric
For more information you can take a look at the PHP documentation : http://php.net/manual/en/function.mysql-fetch-array.php
Try using PDO. The PDOStatement class fetch methods allow you to set the format of the returned data.
Here is some code for retrieving your data in an associative array:
try {
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$sth = $dbh->prepare("SELECT * FROM contas");
if($sth->execute()) {
$contacts = $sth->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($contacts);
} else {
throw new PDOException(print_r($sth->errorInfo(), true));
}
} catch(PDOException $e) {
echo $e->getMessage();
}

Converting mysql_result to mysqli when creating a session [duplicate]

This question already has answers here:
MySQLi equivalent of mysql_result()?
(12 answers)
Closed 10 months ago.
I am trying to convert a mysql script to mysqli and have hit a wall. I am trying to convert a mysql_result to mysqli however am unsure how to do this, below is my code
$_SESSION['num_user'] = mysql_result(mysqli_query($GLOBALS["___mysqli_ston"], "SELECT COUNT(*) FROM `members` WHERE mem_emailactivated = 1"), 0);
As weird as it is, there doesn't seem to be a way to fetch without prepare/execute.
$stmt = mysqli_prepare($GLOBALS['___mysqli_ston'], "SELECT COUNT(*) AS count ...");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $count);
mysqli_stmt_fetch($stmt);
$_SESSION['num_user'] = $count;
You are mixing things up here. You wouldn't use mysql_result to get the result from a query using mysqli. you would instead use mysqli to iterate through the returned array and then store this array in the $_SESSION.
$result = $mysqli->query("call getUsers()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$user_arr[] = $row;
}
$result->close();
}
$_SESSION['num_user'] = $user_arr;

How do I reset a PHP pointer for a MySQL resource? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to reset mysql pointer back to the first row in PHP?
I have 2 while loops in my PHP script that processes a list of data from a database.
$results = mysql_query("SELECT * FROM myTable");
while ($result = mysql_fetch_object($results)) {
// do stuff
}
reset($results);
while ($result = mysql_fetch_object($results)) {
// do some more stuff
}
However, the reset() function is not resetting my pointer within the MySQL resource. In fact, it generates an error:
"Warning: reset() [function.reset]: Passed variable is not an array or
object in /home/cs179_team13/public_html/timeTests/results.php on
line 133."
Why? How do I reset a PHP pointer for a MySQL resource?
You can use the function mysql_data_seek.
bool mysql_data_seek ( resource $result , int $row_number )
More information can be a found at http://www.php.net/manual/en/function.mysql-data-seek.php.
Pass the resultset returned along with 0
mysql_data_seek($resultset, 0) ;//reset result set
You don't need such an ugly way.
Just get yourself an array.
$data = sql_to_arr("SELECT * FROM myTable");
foreach ($data as $row) {
// do stuff
}
foreach ($data as $row) {
// do stuff
}
foreach ($data as $row) {
// do stuff
}
this is way more convenient way to deal with data

Categories