PHP PDO Looping through SQL results shows only the last one - php

Dears,
I am trying to fetch all SQL results into an assoc array and then to json but i don't know why i am only getting the last sql row.
<?php
require_once "Xsecure/access.php";
$Arry = array();
$json = array();
$access = new DatabaseAccess();
$sql = $access->Connect();
$stmt = $sql->prepare("select mid from players");
$stmt->execute();
$rowCount = $stmt->rowCount();
$Arry = $result;
while ($result = $stmt->fetchAll(PDO::FETCH_ASSOC) ){
$Arry = $result;
}
// for array data access
foreach($Arry as $row){
$json["mid"] = $row["mid"];
};
// 3. Disconnect db connection
$sql = $access->Disconnect();
// 4. Return json output
echo json_encode($json, JSON_UNESCAPED_SLASHES);
?>
The result output is :
{
"mid": "10"
}
It should mid from 1 to 10 not only the last row. How can i achieve that? what am i missing?
Note: Later on, i want to add extra keys value pairs to the array that are not derived from mySql database so i have to use assoc array.
Thanks in advance,

...
$stmt->execute();
$rowCount = $stmt->rowCount();
$Arry = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($Arry as $row){
$json[]["mid"] = $row["mid"];
};
...
or even just
...
$stmt->execute();
$rowCount = $stmt->rowCount();
$json = $stmt->fetchAll(PDO::FETCH_ASSOC);
...

Related

PHP:MYSQL array to JSON stop duplicating?

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];
}
}

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
}

How to fetch 2 times in MYSQL PDO without FETCHALL

I have this sample query:
$STH = $DBH->query("SELECT id FROM table");
I want to get the first row and then loop and display all rows. So I use the following to get the first row:
$STH->setFetchMode(PDO::FETCH_ASSOC);
$first_row = $STH->fetch();
$first_row = $first_row['id'];
I use while loop to display all rows again:
while ($list = $STH->fetch()) {
$id = $list['id'];
echo $id;
}
Now the while skips the first row and I want it to be displayed. Is there an equivalent to mysql_data_seek to reset the pointer again to the first row? I know fetchall can be used but it's bad on memory and wasteful. I could also run the query and limit to 1 but this is not recommended as I have a query that joins multiple tables and would be very slow. Is there any other solution?
Thanks
I take that back looks like you can use the cursor orientation contants to select the result... sample code coming... I havent tried this so you may need to play a bit. This is also based on the assumption that a PDO::FETCH_ORI_FIRST acts like a data_seek and leaves the cursor on the first position as opposed to returning it to whatever it was before.
$stmt = $pdo->prepare('SELECT id FROM table', array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$first = $pdo->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_FIRST);
$first_row = $first['id'];
// other stuff
// first iteration we rewind to the first record;
$cursor = PDO::FETCH_ORI_FIRST;
while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC, $cursor))) {
$id = $row['id'];
// successive iterations we hit the "next" record
$cursor = PDO::FETCH_ORI_NEXT;
echo $id;
}
I dont think you can rewind a statement... Assuming these blocks arent seprated by a bunch of intermediary logic id just do it in the loop.
$STH->setFetchMode(PDO::FETCH_COLUMN); // no need to pull an array
$count = 0;
while ($id = $STH->fetch()) {
if($count === 0) {
$first_row = $id;
}
echo $id;
$count++;
}
Could you just use a do...while loop instead?
$STH->setFetchMode(PDO::FETCH_ASSOC);
$list = $STH->fetch();
$first_id = $list['id'];
do {
$id = $list['id'];
echo $id;
} while ($list = $STH->fetch());
You can fetch all the result, and then just act on it as an array. So, for instance, you could shift the first result off the front, and then loop over any additional rows:
<?php
$sql = "YOUR QUERY";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// get first row
$firstRow = array_shift($rows);
// loop over remaining rows
foreach ($rows as $row) {
// do something
}

How can I rewind a pdo result?

I know this question has been asked before, but I tried eveything and can't find how it works.
I have a prepared query, and I need to use it twice with two while() loops like this:
$query = $pdo->prepare('SELECT ...');
$query->execute();
while( $results = $query->fetch() ){
// instructions
}
// rewind
while( $results = $query->fetch() ){
// instructions
}
Thanks
To expand on above answer, you could use:
$results = $query->fetchAll();
$results now being an array containing the result set, so:
foreach ($results as $row) ...
Alternatively with MySQL, you can use buffered queries:
$stmt = $db->prepare('SELECT ...', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
The fetchAll() method will be database vendor independent, but will have higher memory requirements.
Could be as simple as getting all the results on the 1st iteration and loop on the 2nd:
$res = array();
while( $results = $query->fetch() ){
$res[] = $results;
// instructions
}
foreach($res as $results){
// instructions
}

Categories