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
Related
It's possible to display records from database two different ways at the same time using PDO? What I mean is I want to echo records as object and array at the same time.
I tried using $db_conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_BOTH); but it's not working. I get this error which I know what it means : Notice: Trying to get property of non-object
Also i set as this with the same result:
$db_conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db_conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
And when I try to fetch data from the database I use:
$db_conn = new PDO('mysql:host=localhost;dbname=test;charset=utf8', $db_user, $db_pass, array(
PDO::ATTR_PERSISTENT => true
));
$sql = $db_conn->prepare('SELECT * FROM table_name');
$sql->execute();
$all_data = $sql->fetchAll();
foreach($all_data as $row){
echo $row->col1;
echo $row['col1'];
}
You can define a class that implements the ArrayAccess interface, so the properties can be accessed using array syntax. Then you can do:
$db_conn->setFetchMode(PDO::FETCH_CLASS, 'YourClass');
The documentation link above has an example of a simple class definition.
I've been at this for some time. Using PDO's documentation and based on older stackoverflow posts I feel I am doing this correct, however I can not figure out where my data is in the array returned by fetchAll. Any help would be appreciated.
In my DatabaseHandler class:
public function getStateList(){
$root = "root";
$rootpasswd = "password";
$host = "localhost";
try{
$dbh = new PDO("mysql:host=$host;dbname=TESTDATA;", $root, $rootpasswd);
$stmt = $dbh->prepare("SELECT id FROM state");
if(!$stmt->execute()){
//error
}
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}catch(PDOExeption $e){
//catch exception
}
}
Now when calling this method it returns an array of 52 id's which is what it's supposed to do however I can not get to this data. Why? Here is the code that calls the method.
<?php
require("./Database/DatabaseHandler.php");
$dbh = new DatabaseHandler();
$stateCodes = $dbh->getStateList();
$max = sizeof($stateCodes);
error_log("Arraysize=".$max."\n", 3, "/testlog/data.dat");
error_log("Position 0: ".$stateCodes[0]."\n", 3, "/testlog/data.dat");
error_log("Position[0][0]: ".$stateCodes[0][0]."\n", 3, "/testlog/data.dat");
error_log("Position[0][0][0]: ".$stateCodes[0][0][0]."\n", 3, "/testlog/data.dat");
?>
The first errorlog records 52.
The second returns the word Array which makes me think it's a 2 dim array.
The Third nothing.
The Fourth Nothing.
I know I am using fetchAll wrong somehow but I can't figure out where or how. Thank you in advance.
You have used PDO::FETCH_ASSOC that will be an associative array.
But since you are fetching all, the array is 2 dimensional.
$stateCodes[0]['id'];
Alternatively you can loop this way:
foreach($stateCodes as $code){
error_log("Code Id =" . $code['id']);
}
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();
}
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();
}
I'm strugging to get to grips with this mysqli style of queries. Can someone help me with this code please?
The intention is to put the results from the query (or which there are three in the database) into an array so that I can display them in a table, for example.
Here is my code...
$get_orders_stmt = $db->prepare(
"select cap_transaction_id, company_id, company_transaction_id, cap_points, transaction2login
from transactions
where transaction2login = ?");
$get_orders_stmt->bind_param("s", $_SESSION['username']);
$get_orders_stmt->execute();
while($row = $get_orders_stmt->fetch()) {
$results[] = $row;
print_r($results);
I was hoping to put $row as the returned records into the array, results but I fear I have got this totally wrong! My print_r() gives me this...
Array ( [0] => 1 ) Array ( [0] => 1 [1] => 1 ) Array ( [0] => 1 [1] => 1 [2] => 1 )
Any thoughts or pointer please?
UPDATE!
Turns out the my machine isn't up to spec with the best answer on here. I need MYSQLIND for get_results(); I'm moving to something more compatible.
You should check the documentation. mysqli_stmt::fetch returns a boolean. You need to bind your result to variables with mysqli_stmt::bind_result.
With mysqli it is always a pain.
So, if you're going to use raw API calls in your code, change API then:
$sql = "select cap_transaction_id, company_id, company_transaction_id,
cap_points, transaction2login
from transactions where transaction2login = ?"
$stmt = $db->prepare($sql);
$stmt->execute(array($_SESSION['username']));
$results = $stmt->fetchAll();
print_r($results);
fetch() is not the right function. You should
...
$get_orders_stmt->execute();
$res = $get_orders_stmt->get_result();
while($row = $res->fetch_assoc())
$results[] = $row;
See documentation to choose between fetch_assoc (returning field associative array), fetch_row (returning non-associative array, indexable by column number) and fetch_array(merge between row and assoc)