Remove Indexes from json_encode output [duplicate] - php

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

Related

PDO rowCount and fetchColumn both not returning correct result [duplicate]

This question already has answers here:
Row count with PDO
(21 answers)
Closed 6 years ago.
I've tried various things to get this short bit of code to work. What it does is it connects to the database via PDO and then selects all rows that match a post variable. If there is more than 0 rows, update the licensekey rows to be "used" and echo true.
I have tried both rowcount and fetchcolumn and count(*) for sql, and none of shown any differences. In MySQL itself, I have used a valid licensekey and it indeed returns one row.
<?php
if(isset($_POST['licensekey'])) {
try {
$db = new PDO("mysql:host=localhost;dbname=validation", "test", "test");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die($e->getMessage());
}
$search = ("SELECT * FROM validated WHERE activationkey=:lk AND used='0'");
$result = $db->prepare($search);
$result->bindParam(":lk", $_POST['licensekey']);
$result->execute();
if($result->rowCount() > 0) {
$used = ("UPDATE validated SET used='1' WHERE validated.activationkey=:lk");
$result2 = $db->prepare($used);
$result2->bindParam(":lk", $_POST['licensekey']);
$result2->execute();
echo "true";
} else {
echo "false";
}
$db = null;
} else {
exit();
}
?>
Every time it will return false no matter what.
What seems to be the issue here?
Actually you can't see how many records selected in DB with rowCount function. As i read in PHP Documentation many of select queries doesn't return how many rows affected by query with rowCount method. Check it for more information : http://php.net/manual/en/pdostatement.rowcount.php
As doc says you can use fetchColumn method.

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 Return All Rows [duplicate]

This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
So, right now I have a PHP function that utilizes PDO to return the first row of a specific table. That works fine, but I want to return all of the information, while being able to organize it all.
I have the table zip__admins and I'm trying to return the first_name and last_name from the table. With this information, I have a button on the login page asking the user to select their name (each person gets their own button) to sign in. As of now, I'm returning one result, instead of two results. How can I modify the below code to return two results, and input the data into a templating parameter.
final public function fetchAdminInfo() {
global $zip, $db, $tpl;
$query = $db->prepare('SELECT first_name, last_name FROM zip__admins');
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
$tpl->define('admin: first_name', $result['first_name']);
$tpl->define('admin: last_name', $result['last_name']);
}
Here is my table:
![SQL Table][1]
You need to use fetchAll()
$result = $query -> fetchAll();
foreach( $result as $row ) {
echo $row['first_name'];
echo $row['last_name'];
}

Wierd php array? after db query [duplicate]

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?

Why do I get "Resource id #4" when I apply print_r() to an array in PHP? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
Below is the code:
$result=mysql_query("select * from choices where a_id='$taskid'")or die(mysql_error());
print_r($result);
I get "Resource id #4", any idea?
After I added
while($row=mysql_fetch_assoc($result))
{ print_r($row); }
I just got []
What's wrong?
You are trying to print a mysql resource variable instead of the values contained within the resource it references. You must first try to extract the values you have gotten by using a function such as mysql_fetch_assoc().
You might also try mysql_fetch_array() or mysql_fetch_row(), but I find associative arrays quite nice as they allow you to access their values by the field name as in Mike's example.
mysql_query() does not return an array as explained in the manual. Use mysql_fetch_array(), mysql_fetch_assoc(), or mysql_fetch_row() with your $result. See the link above for more info on how to manipulate query results.
$result = mysql_query('SELECT * FROM table');
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
$result is a resource variable returned by mysql_query. More about resource variables: http://php.net/manual/en/language.types.resource.php
You must use other functions such as mysql_fetch_array() or mysql_fetch_assoc() to get the array of the query resultset.
$resultset = array();
$result=mysql_query("select * from choices where a_id='$taskid'") or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$resultset[] = $row; // fetch each row...
}
mysql_free_result($result); // optional though...
print_r($resultset);
See:
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/function.mysql-fetch-assoc.php
http://php.net/manual/en/function.mysql-query.php
Resources are special variable types used by PHP to track external resources like database connections, file handles, sockets, etc.

Categories