PHP:MYSQL array to JSON stop duplicating? - php

So whenever I download data from my mysql database, and convert to a JSON array via PHP then display it, I get duplicated values.
I do understand why this is so, but is there any way to remove the numeric duplicates?:/
{"id":"1","0":"1","userId":"23","1":"23","message":"HELLO","2":HELLO"},
{"id":"2","0":"2","userId":"53","1":"53","message":"WOW","2":WOW"}

For PDO use PDO::FETCH_ASSOC flag after query execute
$sth = $dbh->prepare("SELECT col FROM table");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
And for mysql_* functions:
$query = "SELECT col FROM table";
$result = mysqli_query($connection, $query);
$output = array();
while($row = mysqli_fetch_assoc($result)){
$output[] = $row;
}
json_encode($output);

As you've asked, to remove it:
Loop through it, if key is numeric delete.
foreach($array as $key=>$var){
if(is_numeric($key)){
delete $array[$key];
}
}

Related

Saving PDO-data in array

i am doing this select:
$result = $dbh->query("SELECT clicks FROM table WHERE click_date = '".$current_date."'");
$result->execute();
$array = array();
while ($user = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($array, $user['clicks'].",");
}
But this returns:
49572940
But it should be:
4,9,5,7,2,9,4,0
Anybody could help me to fix this problem?
Greetings!
Try this way:
<?php
$sql = "SELECT clicks FROM table WHERE click_date = '$current_date'";
foreach ($dbh->query($sql) as $row) {
$array[] = $row['clicks'];
}
//now echo and use implode
echo implode(", ", $array);
?>
because according to PHP Manual - PDO::query:
PDO::query — Executes an SQL statement, returning a result set as a
PDOStatement object
You should use fetchAll to get all the values and also if you want to execute a prepared statement you have to use prepare instead of query.
$sth = $dbh->prepare("SELECT clicks FROM table WHERE click_date = :current_date");
$sth->bindParam(':current_date', $current_date);
$sth->execute();
$result = $sth->fetchAll();
and after if you want a string with values separate by comma you can use implode as #jason suggested.
$str = implode(",", $result );

Mysql fetch all rows and echo as json

I've got a database with 5 columns and multiple rows. I want to fetch the first 3 rows and echo them as an array. So far I can only get the first row (I'm new to PHP and mysql). Here's my PHP so far:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
//==== ECHO AS JSON
echo json_encode($array);
Help would be much appreciated.
You need to loop through the results. mysql_fetch_row gets them one at a time.
http://php.net/manual/en/function.mysql-fetch-row.php
The code would end up like:
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
$jsonData[] = $array;
}
echo json_encode($jsonData);
//json_encode()
PLEASE NOTE
The mysql extension is deprecated in PHP 5.5, as stated in the comments you should use mysqli or PDO. You would just substitute mysqli_fetch_row in the code above.
http://www.php.net/manual/en/mysqli-result.fetch-row.php
I do like this while quering an ODBC database connection with PHP 5.5.7, the results will be in JSON format:
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
Fetching results allowing edit on fields:
while( $row = odbc_fetch_array($result) ) {
$json['field_1'] = $row['field_1'];
$json['field_2'] = $row['field_2'];
$json['field_3'] = $row['field_1'] + $row['field_2'];
array_push($response, $json);
}
Or if i do not want to change anything i could simplify like this:
while ($array = odbc_fetch_array($result)) { $response[] = $array; }
What if i want to return the results in JSON format?, easy:
echo json_encode($response, true);
You can change odbc_fetch_array for mysqli_fetch_array to query a MySql db.
According to the PHP Documentation mysql_fetch_row (besides that it's deprecated and you should use mysqli or PDO)
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
so you need for example a while loop to fetch all rows:
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row;
}
echo json_encode($rows);
I leave it to you how to only fetch 3 rows :)
You need to put this in some kind of a loop, mysql_fetch_row returns results one at a time.
See example:
http://www.php.net/manual/en/mysqli-result.fetch-row.php#example-1794
$result = mysql_query( "SELECT * FROM $tableName ORDER BY id LIMIT 3");
$json = array();
while($array = mysql_fetch_row($result)){
$json[] = $array;
}
echo json_encode($json);

MySQL results issue in php array

Can anybody tell me why not all the results for MySQL aren't ending up in the array?
$result = mysql_query("select * from groups order by id desc");
if ($row = $result->fetch()) {
$groups[] = $row;
}
Use while not if
while ($row = $result->fetch()) {
$groups[] = $row;
}
The code you have there does not iterate over the result set.
Try this instead.
while ($row = $result->fetch()) { 
$groups[] = $row;
}
Because fetch only fetches a row as explained in the php manual:
Fetches the next row from a result set
I'd like to suggest changing your mysql_ code for PDO
$db = new PDO("..."); // Creates the PDO object. Put the right arguments for your connection.
$statement = $db->prepare("SELECT * FROM groups ORDER BY id DESC");
$statement->execute();
while ($groups = $statement->fetch())
{
// Do whatever you want to do
}

return all the row values for a given id

How do I return all the row values for a given id?
require('dbc.php');
mysql_select_db($db);
$result = mysql_query("SELECT * FROM about WHERE id=".$_GET['id']);
$row = mysql_fetch_assoc($result);
echo $row['content']; // return all values instead of just content
You can use mysql_fetch_row and then implode the array:
echo implode(",",mysql_fetch_row($result));
The following will work:
while ($row = mysql_fetch_assoc ($result) ) {
foreach($row as $column => $value){
echo "Row: $column - $value<br />";
}
}
But, I would suggest you move to MySQLi, for security and performance purposes. Once you do, you can use:
$all_rows = mysqli_fetch_all ($result, MYSQLI_ASSOC);
You could loop through this or call implode on it to return the values.

mysql_query row values iteration problem

I have a problem iterating through an sql query:
$result = mysql_query("SELECT * FROM transactions");
while($row = mysql_fetch_array($result)) {
// this returns 3 rows
foreach ($row as $values)
{
//fputcsv($a_csv, $values;
echo $values;
}
}
The script iterates fine but it appears to be going through each row twice. So what I receive in output is the following:
value1value1value2value2value3value3
I'm not sure why this is - could anyone explain please?
Thankyou
mysql_fetch_array fetches both the named & the numerical keys. Use either mysql_fetch_assoc or mysql_fetch_row.
$result = mysql_query("SELECT * FROM transactions");
//return an associative array
while($row = mysql_fetch_assoc($result)) {
// this returns 3 rows
$values = "{$row["name_of_column1"]}, {$row["name_of_column2"]}, {$row["name_of_column3"]}";
//fputcsv($a_csv, $values;
//print the whole row array
print_r($row);
//echo value in format value1, value2, value3
echo $values;
}
You need to access $row like this $row[0] And $row shouldn't be in a foreach() itself unless it too is some kind of array you need to iterate through.
$result = mysql_query("SELECT * FROM transactions");
while($row = mysql_fetch_row($result))
{
echo $row[0];
echo $row[1];
// ... etc.
}

Categories