translation mysql_fetch_array to PDO::FETCH_NUM - php

What is the equivalent of these two code in PDO
first:
$row=mysql_fetch_array($query);
second:
while($row=mysql_fetch_array($query)){
$data[]=$row;
}
i used these codes below but they are not exact same i guess, because the rest of the code didn't work.
$row = $query->fetch(PDO::FETCH_NUM);
and
$data[] = $query->fetch(PDO::FETCH_ASSOC);

Here are the correspondences:
mysql_fetch_array = fetch(PDO::FETCH_BOTH) - The rows are arrays with both numeric and named indexes.
mysql_fetch_assoc = fetch(PDO::FETCH_ASSOC) - The rows are arrays with named indexes.
mysql_fetch_row = fetch(PDO::FETCH_NUM) - The rows are arrays with numeric indexes.
mysql_fetch_object = fetch(PDO::FETCH_OBJ) or fetch(PDO::FETCH_CLASS) depending on whether you specify the optional className argument to mysql_fetch_object. The rows are objects, either of the specified class or stdClass.
The while loop is equivalent to:
$data = $query->fetchAll(PDO::FETCH_BOTH)

You should be able to get the data of the query in an array with this:
$data = $query->fetch(PDO::FETCH_BOTH);
If that's not working, your PDO connection is probably not setup right or your query didn't run. You can try troubleshooting the query with something like this:
try {
$query->execute();
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}

Related

Fetch multiple rows in mysql single query in php with different id

I have different id's, i am getting the values of these id from users
$id=array();
$id[0]=$_GET["id0"];
$id[1]=$_GET["id1"];
$id[2]=$_GET["id2"];
now to fetch data from database i am using following query:
for($j=0;$j<count($id);$j++)
{
$res=mysql_query("SELECT * FROM mutable WHERE id='$id[$j]'")
while($row=mysql_fetch_array($res))
{
$row[]=array("email"=>$row[2],"name"=>$row[3],"address"=>$row[5]);
echo JSON_encode($row);
}
}
now i am getting proper result from this query using for loop but the result is not in proper JSON format, is there any way to do it more efficentyly and getting proper result in JSON array and JSON object format
Place json_encode() outside of your loops.
Let's modernize and refine things...
*Unfortunately prepared statements that use an IN clause suffer from convolution. pdo does not suffer in the same fashion.
Code: (untested)
if(isset($_GET['id0'],$_GET['id1'],$_GET['id2'])){
$params=[$_GET['id0'],$_GET['id1'],$_GET['id2']]; // array of ids (validation/filtering can be done here)
$count=count($params); // number of ids
$csph=implode(',',array_fill(0,$count,'?')); // comma-separated placeholders
$query="SELECT * FROM mutable WHERE id IN ($csph)";
$stmt=$mysqli->prepare($query); // for security reasons
array_unshift($params,str_repeat('s',$count)); // prepend the type values string
$ref=[]; // add references
foreach($params as $i=>$v){
$ref[$i]=&$params[$i]; // pass by reference as required/advised by the manual
}
call_user_func_array([$stmt,'bind_param'],$ref);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM))
$rows=["email"=>$row[2],"name"=>$row[3],"address"=>$row[5]];
}
$stmt->close();
echo json_encode($rows);
}
Three things:
Always, always, always used prepared statements and bound parameters when dealing with untrusted (i.e., $_GET) input. Just do it.
As regards your problem with JSON, you only need to run json_encode once:
$results = [];
for($j=0;$j<count($id);$j++) {
...
while($row=mysql_fetch_array($res)) {
results[] = ...
}
}
json_encode( $results );
Use a single SQL statement, since you have a known number of IDs to collect:
$dbh = new PDO($dsn, $user, $password);
$sql = "SELECT * FROM mutable WHERE id IN (?, ?, ?)";
$sth = $dbh->prepare( $sql );
foreach ( $sth->execute( [$_GET['id0'], $_GET['id1'], $_GET['id2']] ) as $row ) {
...
This is more efficient then multiple round trips to the database. For this contrived case it probably doesn't matter, but getting into good habits now will serve you in the long run.
you have used $row wrongly, declare array variable outside of loop like
$json_response = array();
for($j=0;$j<count($id);$j++) {
$res=mysql_query("SELECT * FROM mutable WHERE id='$id[$j]'")
while($row=mysql_fetch_array($res)) {
$json_response[]=array("email"=>$row[2],"name"=>$row[3],"address"=>$row[5]);
echo json_encode($json_response); // not good to echo here
}
}
// echo json_encode($json_response); // ideally echo should be here

Why is my SQL query returning an array?

I've got a table of users each with a unique ID. When I try and fetch their ID for the session it returns an array of two IDs for some reason.
So in the following code, $_SESSION['userid'] becomes an array containing two instances of the same ID.
I can't figure out why though...
$_SESSION['userid'] = getUserID($_POST['username']);
function getUserID($username)
{
include 'db.inc.php';
try {
$sql = "SELECT id FROM user WHERE username = '". $username. "'";
$s = $pdo->prepare($sql);
$s->bindValue(':username', $username);
$s->execute();
}
catch (PDOException $e) {
$error = 'Error getting userid for '.$username . '....error: '.$e;
include $_SERVER['DOCUMENT_ROOT']."/database/includes/pages/error.html.php";
exit();
}
$row = $s->fetch();
return $row;
}
Your problem is in your $s->fetch(). By default PDO fetches an array indexed by both field and number, e.g. $row['id'] and $row[0] Try this:
$row = $s->fetch(PDO::FETCH_ASSOC);
return $row['id'];
See http://php.net/manual/en/pdostatement.fetch.php for more information.
PDOStatement::fetch() defaults to returning PDO::FETCH_BOTH:
returns an array indexed by both column name and 0-indexed column number as returned in your result set
(Taken from http://php.net/manual/en/pdostatement.fetch.php)
You need to do:
$row = $s->fetch(PDO::FETCH_ASSOC);
The problem is that $s->fetch() is returning an object. You need to modify it to return an associative array:
$s->fetch(PDO::FETCH_ASSOC)
You are doing wrong with $result = $sth->fetch(); You have missed PDO::FETCH_ASSOC which returns an array indexed by column name as returned in your result set.
So you must use the code like
$row = $s->fetch(PDO::FETCH_ASSOC);

While loop to display all data after SELECT query

I know this might be a very basic question, but I am new to php and databases, I'm trying to figure out a while condition that will keep while loop running until all (would be also nice to know how to do it for fixed amount) of data is taken form database.
$stmt = $db->prepare("SELECT * FROM icecreams");
$stmt -> execute();
$row = $stmt -> fetchAll(PDO::FETCH_ASSOC);
So now I need to figure out what while condition I need, the logic is
while (there is data to fetch) {
echo "<h1>$row['flavour']</h1>";
echo "...";
}
fetchAll() returns an array containing all of the result set rows, whereas fetch() returns a single row from the result-set.
fetchAll() Usage:
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($array as $row) {
# code...
}
fetch() Usage:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
# code...
}
If you're going to use this for printing HTML, the second option seems nicer. For small recordsets, the performance difference shouldn't really matter, but if you're working with a lot of records, then fetchAll() might be a little slower, as it tries to map the entire data into a single array at once.
$stmt = $db->prepare("SELECT * FROM properties");
$stmt -> execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//$row['column_name']
}
fetchAll does fetch everything as an associative array (as flag FETCH_ASSOC tells). It does it automatically for, you don't have to worry about it.
If you do this then you will see that you have all of your data in an array already:
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>'.print_r($row, true).'</pre>';
So now you can simply loop the items an access the data:
foreach($row as $k=>$v)
{
echo $k.'<br>'; // this will show you what row # you are on, sometimes useful :)
echo $v['title'].'<br>';
// etc....
}

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();
}

PDO showing more results than expected

I have a simple table with one field "id", and when I execute this code...
$dbh = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
$sql = 'SELECT * FROM logolist';
$q = $dbh->query($sql);
while($r = $q->fetch()){ print_r($r); }
... I get this output:
Array
(
[ID] => 2
[0] => 2
)
Array
(
[ID] => 4
[0] => 4
)
As you see, there's a [0] under the field "ID". if I add more field, I keep getting more extra elements inside the array. It's like every field is outputting it's value 2 times.
Why is this?
That is normal for fetch() without any attribute (it's sets FETCH_BOTH by default). It works like old mysql_fetch_array() and 0 is the numerical index.
If you switch to Associative you will get only fields:
while($r = $q->fetch(PDO::FETCH_ASSOC)){
print_r($r);
}
PDOStatement::fetch - for all styles.
I'm encountering this practice of having a loop for fetching MySQL results and I'm wondering why people do it so I'll write up this answer and try to clear up a few things.
1) You do not need a loop to fetch results
2) Reason you get the results duplicated is because you're receiving an associative array and index-based one. That's the default behaviour.
What you can do is this:
$dbh = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
// Tell PDO to throw exceptions in case of a query error
$dbh ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
$result = $dbh->query("SELECT * FROM logolist")->fetchAll(PDO::FETCH_ASSOC);
// Your result is now in $result array which is associative.
// If it's empty - no results were found.
// In case of an error, you'd go to catch block of the code and you'd echo out an error.
}
catch(PDOException $e)
{
echo "Error reported: ". $e->getMessage();
}
You are fetching both numerical and associative.
Check the PDO documentation:
http://php.net/manual/en/pdostatement.fetch.php
(You are using PDO::FETCH_BOTH (default))
while($r = $q->fetch(PDO::FETCH_ASSOC)){ print_r($r); }
PDO::FETCH_ASSOC will only get values with their associative keys, without numerical indexes.
fetch gives numerical and associative array
http://www.php.net/manual/en/pdostatement.fetch.php
you can use FETCH_ASSOC for only getting associative array

Categories