The mysql_fetch_array() is duplicating every thing [duplicate] - php

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

Related

Remove Indexes from json_encode output [duplicate]

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

Json Encoding Issue in Database Connection [duplicate]

This question already has answers here:
php warning: mysqli_close() expects parameter 1 to be mysqli
(2 answers)
Closed 2 years ago.
I am having a slight problem when I try to connect to a db remotely and I would be really grateful for any tips. Here is the code:
$con=mysqli_connect($port, $username, $password, $database);
$sql = "SELECT name, date FROM `view_tickets`;";
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
mysqli_close($result);
mysqli_close($con);
I want to result in json to be able to run this from a mobile app. At the moment nothing is displaying on the browser (I am running Xampp). I added some prints and can confirm that the connection is successful and the array is being filled properly. I managed to print it out using print_r(array_values($resultArray));
Is something wrong with my json?
I don't know if this helps but noticed that I am getting the following warning;
Warning: mysqli_close() expects parameter 1 to be mysqli, object given in /Applications/XAMPP/xamppfiles/htdocs/www/service.php on line 39
This corresponds to mysqli_close($result);
Any ideas?
Here is optimised version of your code.
Note that tempArray is remove (there is no need of it)..
mysqli_close($result) is replaced with unset($result) because $result is not a connection object. How ever unsetting is not required if this is the end of your code because after the end of the script php will unset all variables by it self..
$con=mysqli_connect($port, $username, $password, $database);
$sql = "SELECT name, date FROM `view_tickets`;";
$resultArray = array();
if ($result = mysqli_query($con, $sql)) {
// Loop through each row in the result set
while($row = $result->fetch_object()){
$resultArray[] = $row;
}
}
unset($result);
mysqli_close($con);
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
The mysqli_close needs to connection given to close, but you're give the function your result from your Query!
Change it to
mysqli_close($con);
Then it should be working, if not just comment
I had an issue with the encoding of the character set. Databases can have different encoding, make sure it is utf8

translation mysql_fetch_array to PDO::FETCH_NUM

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

prepared parameterized query with PDO

New to this new and secure way of handling SQL's in PHP and MySql driven web based application, to secure the code from SQL injections. I am planning to start using mysqli with PDO. Can anyone please outline how should i get started and proceed.
Any reference to any article will also be helpful.
Thanks in advance.
To create the connection
try {
$db = new PDO("mysql:dbname=".DB_NAME.";host=".DB_HOST,DB_USER,DB_PWD);
} catch (PDOException $e) {
die("Database Connection Failed: " . $e->getMessage());
}
Then to prepare a statement
$prep = $db->prepare("SELECT * FROM `users` WHERE userid = ':id'");
As you can see, you label each parameter you'd like by prefixing any string with ':'. Then all you do is pass an array mapping the parameter (:id) to the value when you execute.
if (!$prep->execute(array(":id" => $userinput))) {
$error = $prep->errorInfo();
echo "Error: {$error[2]}"; // element 2 has the string text of the error
} else {
while ($row = $prep->fetch(PDO::FETCH_ASSOC)) { // check the documentation for the other options here
// do stuff, $row is an associative array, the keys are the field names
}
}
Instead of PDO::FETCH_ASSOC with the "fetch" function, there are various other ways to get your data. You can use fetchAll to get an array of ALL the results at once instead of just going row by row. Or you can get the array of information as a 0-indexed array, or you can even fetch the results directly into a class instance (if the field names line up with the properties of the class.)
All the documentation of PDO can be found here: PHP.net PDO Manual

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