I want to output all records in my database. So far so good, but when I loop through it, php gives me an error " Array to string conversion ".
I added an index to the array but then it does just output obviously the first or secound ( etc. ) column.
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result[0] as $value)
{
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
So, with the index, it does work. But I need all records, not just one.
I appreciate every comment and help!
I would start with a nested loop. I also wonder if you want a table for every value
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result as $row){ //Go through every row in the result
echo('<table>');
foreach ($row as $value){ //Go through every value in the row
echo "<tr><td>'$value'</td></tr>";
}
echo('</table>');
}
}
This will print every row as a new table, but you can search out the variation you want.
A nested foreach loop should work.
foreach ($result as $values)
{
foreach ($values as $value) {
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
An alternative to nested loops, if you know the number of fields and said number is constant for each execution; A state that's found in most situations; You can use vsprintf () to print out the rows.
Quick example:
$result = {{'John', 'Doe'}, {'Sarah', 'Jane'}};
$output = '<table>';
foreach ($result as $row) {
$output .= vsprintf ("<tr><td>%s</td><td>%s</td></tr>\n", $row);
}
echo $output."</table>";
Cuts down a bit on the code, and quite a bit on the code complexity. The template for the rows themselves can also be extracted to a variable (or template view), outside of the loop, to make the code even cleaner.
Related
Can anyone tell me how to store an array of associative arrays? I thought this code would work, but it's not. I tried researching it but couldn't find an answer.
foreach($rows as $row) {
// Some SQL...
if ($stmt->execute()) {
while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['NestedResults'][] = $row2;
}
}
}
foreach ($rows as $row) {
foreach ($row['NestedResults'] as $results) {
echo $results['Item'] . '<br>';
}
}
PS: I know I shouldn't loop SQL statements like that, but it's a special case.
In your first foreach loop, you need to pass the $row variable by reference, otherwise you are just modifying a copy of the element from $rows stored in $row:
foreach($rows as &$row)
do you think it is workable to put the second loop inside the first one as below?
$row['NestedResults'][] = $row2;
foreach ($row['NestedResults'] as $results) {
echo $results['Item'] . '<br>';
}
not 100% sure...
I am querying like this, in snippet below 1st loop takes column names and second loops push values in another array(i know this may not be an optimal way but this is what came in my mind and is solving my task). The problem is
$results = '';
$dataArray = array();
$columns_array = array();
$dataArray = array();
$results = mysqli_query($mysqli, ("SELECT
DISTINCT states_drg.`Provider State`,
SUM(states_drg.`Total Discharges`) AS discharges
FROM states_drg
GROUP BY states_drg.`Provider State`")
);
$columns_names = mysqli_fetch_assoc($results);
foreach ($columns_names as $key => $value) {
array_push($columns_array, $key);
}
array_push($dataArray, $columns_array);
foreach ($results as $result) {
array_push($dataArray, mysqli_fetch_row($results));
}
print_r($dataArray);
echo json_encode($dataArray, JSON_NUMERIC_CHECK);
exit;
);
Query runs absolutely fine in query browser, but when I take dump of print_r($dataArray); I get only 26 records where as I have around 51 records in total if I run the Query in Query Browser.
You're using mysqli totally wrong.
foreach($results as $result)
is NOT how you fetch data from a query result. You should have
while($row = mysqli_fetch_assoc($result)) {
$dataArray[] = $row;
}
And not to mention the multiple syntax errors in your pasted code...
I'm trying to nest foreach loops with PDO statements (this previously worked for me in mysql,btw). The first example works and the second one doesn't. However I'd prefer not to run a SQL query every time (isn't that the point of PDO?) and would prefer to use something more like example 2. However, it doesn't 'nest' the loop inside the other, it seems, rather it runs the first then the next.
Example 1)
foreach($db->query('SELECT country FROM db GROUP BY `country`') as $row1) {
echo $row1['country']."<br/>";
foreach($db->query('SELECT * FROM db') as $row2) {
if ($row1['country']==$row2['country']){
echo $row2['name']."<br/>";
}
}
}
Example 2)
$cntry = $db->query('SELECT country FROM db GROUP BY `country` ');
$rslts = $db->query('SELECT * FROM db');
foreach ($cntry as $row1) {
echo "<div id='".$row1['country']."'>".$row1['country']."<br/>";
foreach($rslts as $row2) {
if ($row1['country']==$row2['country']){
echo $row2['name']."<br/>";
}
};
echo "</div>";
}
(isn't that the point of PDO?)
No. The point of PDO is to send your query to database server and to return the results back. But PDO cannot reduce the number of queries executed.
So, here goes the proper solution:
$stmt = $db->query('SELECT country, name FROM db ORDER BY country, name');
$data = $stm->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
foreach ($data as $country => $row)
{
echo $country."<br/>\n";
foreach ($row as $name)
{
echo $name."<br/>\n";
}
}
As a matter of fact, fetchAll() is just a syntax sugar for the code like this:
$data = array();
while ($row = $stmt->fetch())
{
$data[] = $row;
}
it just creates a regular PHP array out of query result. And of course you can loop over this array as many times as you wish. Means you an always replace fetchAll() with manual looping over results, and of course you may group the results whatever way you wish.
While using foreach on $stmt is just a syntax sugar again, intended to confuse PHP users. Because $stmt is not an array but a way more complex structure.
not sure, but as I remember it would be like this
$cntry = $db->query('SELECT country FROM db GROUP BY `country` ')->fetchAll (PDO::FETCH_COLUMN);
$rslts = $db->query('SELECT * FROM db')->fetchAll(PDO::FETCH_COLUMN);
foreach ($cntry as $row1) {
echo $row1['country']."<br/>";
foreach($rslts as $row2) {
if ($row1['country']==$row2['country']){
echo $row2['name']."<br/>";
}
}
}
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 have the below code. It is only returning the first charater of a string.
$conn = Mage::getSingleton('core/resource')->getConnection('connection_write');
$str = 'something to search for';
$fields = 'content_field1, content_field2, content_field3, content_field4';
$idFields = 'id_field1, id_field2, id_field3, id_field4';
$tables = 'table1, table2, table3, table4';
$table = explode(', ', $tables);
$field = explode(', ', $fields);
$rowId = explode(', ', $idFields);
$i=1;
while ($i<4) {
$f = $field[$i];
$id = $rowId[$i];
$sql = $conn->select()->from($table[$i], array($f, $id))->where($f . " LIKE ?", '%' . $str . '%');
$result = $conn->fetchRow($sql);
foreach ($result as $row) {
var_dump($row[$id]);
}
$i++;
}
However, if I use var_dump($row); the entire string from both the id fields and the content fields are outputted.
Can anyone explain to me what I am doing wrong?
Thanks in advance.
However, if I use var_dump($row); the entire string from both the id fields and the content fields are outputted.
well, why do you use var_dump($row[$id]); which exactly equals to "take $id'th char from $row string" then?
foreach ($result as $row) {
$result is a list of rows you selected from the table. Each $row is a string.
$row[$id] simply selects the $id'th character from this row string.
I believe the problem has to do with the fact that $result is an array (possibly an associative array) of strings. (I'm not familiar with Mage, but I'm assuming that fetchRow() returns only a single row and not all of your rows.)
Therefore, what's happening is you've probably got something like this:
$result = array("tom","dick","harry");
When you run foreach($result as $row), $row looks like "tom", "dick", and "harry" on each iteration.
Because $row is a string, calling $row[$id] makes PHP attempt to get get a single character from the $row string. Because it's expecting $id to be an integer in this case, it's probably interpreting "id_field1" as 0, which will end up returning the first character of your string.
I'm not exactly sure what you're trying to get back, but most likely this can be solved by changing your foreach section to be something like...
foreach ($result as $resultColumn) {
var_dump($resultColumn);
}
->fetch() is not needed when fetching data by using foreach statement like in your code (Please see examples below). If you use ->fetch() unnecessarily, this situation often occurs (I experienced this too..)
foreach statement and while statement have the following relationship. Please consider rewriting the code, referring to this:
<?php
$stmt = $pdo->query('SELECT * FROM Entry');
while ($row = $stmt->fetch()) {
echo $row['title'], $row['content'];
}
//this while statement above is equivalent to the foreach statement below
foreach ($stmt as $row) {
//->fetch() is not needed for foreach statement!
echo $row['title'], $row['content'];
}