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
}
Related
I believe I am using the PDO fetch functions completely wrong. Here is what I am trying to do:
Query a row, get the results, use a helper function to process the results into an array.
Query
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$qr = $q->fetchAll(PDO::FETCH_ASSOC);
if ($qr->rowCount() > 0){
foreach($qr as $row){
$names[$row['id']] = buildArray($row);
}
return $names;
}
}
My custom array building function
function buildArray($row){
$usernames = array();
if(isset($row['id'])) $usernames['id'] = $row['id'];
if(isset($row['name'])) $usernames['name'] = $row['name'];
}
I'm actually getting exactly what I want from this, but when I echo inbetween I see that things are looping 3 times instead of once. I think I am misusing fetchAll.
Any help appreciated
If you're going to build a new array, there's not much point in having fetchAll() build an array. Write your own fetch() loop:
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$names = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$names[$row['id']] = $row;
}
return $names;
}
There's also no need for buildArray(), since $row is already the associative array you want.
Is it possible to extract a value from mysqli_result without fetching a row i.e. without modifying the result set as I need it in full later in my code?
You can also point the iterator back to the beginning. ie..
$result = $mysqli->query($query);
while($row = $result->fetch_assoc())
{
//do stuff with the result
}
//back to the start
mysqli_data_seek($result,0);
now the pointer is returned to the beginning. mysqli_data_seek
You can get all and store in an array…
$results = [];
$sql = mysqli_query($con,"SELECT * FROM WHATEVER");
while ($row = mysqli_fetch_array($sql)) {
array_push($results, $row);
}
//Now $results is fully populated
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);
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
}
I'm having trouble getting my data from fetchAll to print selectively.
In normal mysql I do it this way:
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)){
$id = $row['id'];
$n = $row['n'];
$k = $row['k'];
}
In PDO, I'm having trouble. I bound the params, then I'm saving the fetched data into $rs like above, with the purpose of looping through it the same way..
$sth->execute();
$rs = $query->fetchAll();
Now comes the trouble part. What do I do PDO-wise to get something matching the while loop above?! I know I can use print_r() or dump_var, but that's not what I want. I need to do what I used to be able to do with regular mysql, like grabbing $id, $n, $k individually as needed. Is it possible?
Thanks in advance..
It should be
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['n'];
$k = $row['k'];
}
If you insist on fetchAll, then
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
$id = $row['id'];
$n = $row['n'];
$k = $row['k'];
}
PDO::FETCH_ASSOC fetches only column names and omits the numeric index.