This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Output (echo/print) everything from a PHP Array
I have done a query from a database and the result is stored in a variable which is believe is an array. The output is only one row and column so i use:
echo result[0];
to output the result.
However i get an error saying:
Notice: Array to string conversion in "C:/apache/htdocs...."
array
I tried to dump the variable using
var_dump result[0];
I then get this
array(1) { [0]=> array(1) { ["var_datain"]=> string(4) "hai!" } }
So.... how do i get it to echo out the value hai! from that array?
In case it matters, here is my query
$db = new PDO(DSN, DBUSER, DBPASS);
$stmt = $db->prepare("CALL test(?)");
$parameter = 'hai!';
$stmt->bindValue(1, $parameter, PDO::PARAM_STR);
$rs = $stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
It's a multidimensional array.
echo $result[0]['var_datain'];
It depends of the way you did your query (show us more code to explain you better) but it looks that in your case each line returned by your query is another array containing the columns that you selected. Even if you select only one col and only one row, it's still returned as a multidimensional array.
Got it?
Related
This question already has answers here:
sql PDO fetchall duplicate object keys?
(2 answers)
Closed 2 years ago.
I've been searching this site and beating my brains out over trying to print_r a json_encode result without including the indexes. Nothing I've found has helped.
Here's the PHP/MySQL function to get data from the database:
public function listGuestsAll() {
if(is_null($this->pdo)) {
$this->msg = 'Connection Failed!';
return [];
} else {
$pdo = $this->pdo;
$stmt = $pdo->prepare('SELECT user_id, name_first, name_last, email_address, user_role FROM guestList');
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
}
...and here's the print_r code:
print_r(json_encode($user->listGuestsAll()));
...and here's the output:
[
{
"user_id":"1",
"0":"1",
"name_first":"John",
"1":"John",
"name_last":"Doe",
"2":"Doe",
"email_address":"john#doe.com",
"3":"john#doe.com",
"user_role":"1",
"4":"1"
},
{
"user_id":"2",
"0":"2",
"name_first":"Jane",
"1":"Jane",
"name_last":"Doe",
"2":"Doe",
"email_address":"jane#doe.com",
"3":"jane#doe.com",
"user_role":"1",
"4":"1"
}]
How do I get it to output without the repeating field indexed as 0:1, 1:John, 2:Doe, 3:john#doe, 4:1, etc?
Thanks in advance!
You're using this to fetch the rows:
$result = $stmt->fetchAll();
The documentation says that the default fetch mode is PDO::FETCH_BOTH which means the result is returned with both column names as keys and numeric keys.
You can specify a fetch mode. To fetch the row only indexed by numeric keys, use:
$result = $stmt->fetchAll(PDO::FETCH_NUM);
To fetch the row only indexed by column names, use:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
You can also change the default globally so it affects all your fetches when you don't specify a fetch mode:
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_NUM);
You should read:
https://www.php.net/manual/en/pdostatement.fetch.php
https://www.php.net/manual/en/pdostatement.fetchall.php
https://www.php.net/manual/en/pdo.setattribute.php
This question already has answers here:
Single Value Mysqli [duplicate]
(8 answers)
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 2 years ago.
I am having trouble extracting information from a table I have created in MYSQL. I am trying to extract the last entry id number of an individual and want to store it into a variable called $person_id.
So far, I have the following:
$res = mysql_query("SELECT max(person_id) FROM Persons;");
$person_id= mysql_query($res,$conn);
echo $person_id;
Nothing shows up when I try to print the variable name person_id.
The connection to the database works fine since I am able to insert data from a form I created. Any advice?
mysql_query was deprecated in PHP 5.5.
It will return a resource on success, or FALSE on error.
So, instead of echo, you could first try a var_dump($person_id).
Source : https://www.php.net/manual/en/function.mysql-query.php
First, avoid using mysql this extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. Now back to your question, you are printing out the wrong value, your query using mysqli should look like this
$res = "SELECT max(person_id) FROM Persons;";
$person = mysqli_query($conn, $res);
echo $person;
this will return nothing because the result is an array(mysqli object) it cannot be converted to string just like that but, using print_r we can print out the value of person as follows
print_r($persons);
you should get something like this
mysqli_result Object ( [current_field] => 0 [field_count] => count [lengths] => [num_rows] => rows [type] => 0 )
the count and rows represents, depending on the results the number of fields and rows used in the query.
To print out the $person variable correctly, as in your query above it should be
$res = "SELECT max(person_id) FROM Persons;";
$result = mysqli_query($conn, $res);
//fetch the database values as an asscoiative array
while($row = mysqli_fetch_assoc($result))
{
$person_id = $row['person_id'];
}
echo $person_id;
this should print the value you wanted
You must have got some error because you are missing something here.
Thats how it should work for you.
$res = "SELECT max(person_id) FROM Persons";
$result = mysql_query($res,$conn);
list($person_id) = mysql_fetch_row($result);
echo $person_id;
This question already has answers here:
mysqli bind_param() expected to be a reference, value given
(3 answers)
Closed 11 months ago.
I have been trying to bind an array with a prepared statement for days, I have managed to create the number of ?,? and the i,i these are represented in my code as $params and $type. The problem comes when using call_user_func_array with my code since I haven't managed to make it work, I have tried multiple answers from this site but I haven't got it working.
The full query code is:
$params = implode(',', array_fill(0, count($greaterThan), '?'));
$stmt11 = $mysqli->prepare("SELECT nombre FROM usuarios WHERE id IN (".$params.")");
$type = implode('', array_fill(0, count($greaterThan), 'i'));
$param = implode(",", $greaterThan);
call_user_func_array(array($stmt11, "bind_param"), array_merge(array($type), $greaterThan));
print_r(error_get_last());
$stmt11->execute();
$stmt11->store_result();
$stmt11->bind_result($nombresmayores);
$arraynombresmayores = array();
$stmt11->store_result();
while($stmt11->fetch()){
$arraynombresmayores[] = $nombresmayores;
}
Where $param are the values separated by comas (just in case you need it). The array I'm trying to bind is $greaterThan, the query works perfectly because I have made some debugging. The error the program outputs is:
Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given
Finally, the content of the array is:
array(2) {
[0]=>
int(2)
[1]=>
int(4)
}
if your php version is not outdated you can make it much simper
$params = implode(',', array_fill(0, count($greaterThan), '?'));
$stmt = $mysqli->prepare("SELECT nombre FROM usuarios WHERE id IN ($params)");
$types = str_repeat('i',count($greaterThan));
$stmt->bind_param($types, ...$greaterThan);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($nombresmayores);
$arraynombresmayores = array();
$stmt->store_result();
while($stmt->fetch()){
$arraynombresmayores[] = $nombresmayores;
}
but better yet use PDO:
$params = implode(',', array_fill(0, count($greaterThan), '?'));
$stmt = $pdo->prepare("SELECT nombre FROM usuarios WHERE id IN ($params)");
$stmt->execute($greaterThan);
$arraynombresmayores = $stmt->fetchAll(PDO::FETCH_COLUMN);
just compare this neat code with that awful mess you have now.
I have method i use in an class i made to work mysqli in a fashinable way. The key reside in the foreach loop: Basicaly you create a copy of your array with another one by reference and then bind the referenced array. Hope this helps.
UPDATED :
in your case you need to create an array with your string $type and the array of greateThan. From the temp to the bind array, make sure the keys stay the sames and don't unset your data before having called the bond_param
$type = implode('', array_fill(0, count($greaterThan), 'i'));
//$param = implode(",", $greaterThan); //Not needed
//merge the 'type' as an array and the variables to pass
$temp_params= array_merge([$type],$greaterThan);
//Create a referenced array but dont'reference the 'type' argument
foreach($temp_params as $k=>$v){
if($k===0){
$bind_params[$k]=$temp_params[$k];
}else{
$bind_params[$k]=&$temp_params[$k];
}
}
//use the referenced array
call_user_func_array(array($stmt11, "bind_param"), array_merge(array($type), $bind_params));
Just try to assign that expression to a variable, and bind a variable. Expressions cannot be used as references, so you have to pass a variable.
This question already has answers here:
How to fetch all in assoc array from a prepared statement?
(4 answers)
Closed 2 years ago.
I want to put the result of a mysqli prepared statement into an array and return the array for use in another page.
The code is presented below.
function getPermission($mysqli , $email) {
if ($stmt = $mysqli->prepare("SELECT m.email , g.permission
FROM members m
INNER JOIN members_groups q ON m.member_id = q.member_id
INNER JOIN groups g on q.group_id = g.group_id
WHERE email = ?"))
{
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_email, $user_perms);
while ($stmt->fetch()) {
echo ' ID: '.$user_email; //prints the results.
}
}
}
I want to place the query results into an array and return the array.
Note: Am using a wamp server with php and mysql in windows 7. I tried to use the $stmt->getresults method, but it returns nothing.
You could try to store it in an array, one by one, in your loop:
$results = array();
while ($stmt->fetch()) {
$results[] = array(
"email" => $user_email,
"perms" => $user_perms
);
}
return $results;
If you need this array in another file, where you include this function, this will work, but if you need it in another request, PHP will have to run this code again to have the array filled.
If you need this array during the session, then consider putting the result in a session variable:
$_SESSION['myarray'] = $results;
Then in the function, first check if the above session variable is set, and if so, immediately return that value. Only when it is not yet set, you perform the rest of the function.
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();
}