PDO query - loop produces duplicate fields? [duplicate] - php

This question already has answers here:
PDO returning incorrect, but duplicate, data. Key's not in database.
(3 answers)
Closed 3 years ago.
The code below is producing duplicate <td> elements for each field. I am trying to produce a simple HTML table based on the results of a PDO query. Can anyone tell me why each field is being duplicated?
$data = $conn->query('SELECT * FROM students');
// Print results in a HTML table
echo '<table border="1" cellpadding="5">';
foreach($data as $row) {
echo '<tr>';
foreach ($row as $field) {
echo '<td>' . $field . '</td>';
}
echo '</tr>';
}
echo '</table>';
Thanks

It looks like you are using the PDO::FETCH_BOTH style.
This will produce an array where the entries are duplicated, once for the column name keys, and once for the integer keys.
See the following for details:
http://php.net/manual/en/pdostatement.fetch.php

$data = $conn->query('SELECT * FROM students');
echo "<table border="1" cellpadding="5">
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<td>".$info[column1] . "</td> ";
Print "<td>".$info[column2] . " </td></tr>";
}
echo "</table>

Related

php only displaying first result from sql query [duplicate]

This question already has answers here:
How do I iterate over the results in a MySQLi result set?
(2 answers)
Closed 5 months ago.
I'm very new to PHP and I'm trying to get some code that someone else has written to work. As the title says it is only showing the first result when it should be displaying many and I have no idea how to sort it (even though I imagine it's quite simple!). The code is below:
$result = mysqli_query($connection, ("SELECT id FROM details where publicposition like '%$trimvar%' or familyorgname like '%$trimvar%' or commercialorgind like '%$trimvar%' ORDER BY id "));
if (!$result)
{
die('Could not run query');
}
echo "<h1>Your staff conflict search on <font color='#ff0000'>'$trimvar'<font color='#000'> returned <font color='#ff0000'>$rows<font color='#000'> results</h1>";
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
{
echo "<table style='width: 20%; border='0';'>";
echo "<tr>";
echo "<th> Record ID : " . $row['id'] . "</th><br/>";
echo "</tr>";
}
echo "</table>";
Any help on this would be hugely appreciated!
mysqli_result::fetch_array -- mysqli_fetch_array — Fetch the next row
of a result set as an associative, a numeric array, or both
Try using mysqli_fetch_array inside a while loop to fetch one row at a time until the end is reached.
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
echo "<tr>";
echo "<th> Record ID : " . $row['id'] . "</th>";
echo "</tr>";
}

Set fields in Structure HTML with PHP7 [duplicate]

This question already has answers here:
Display query result in a table
(5 answers)
Closed 5 years ago.
I have a problem for setting field in htlm5 with results query.
{
$query = "SELECT nome,cognome FROM utente";
$result = $mysqli->query($query);
while($rows = $result->fetch_all(MYSQLI_ASSOC)){
print_r($rows);
};
}
How can I take this result in this structure?
<tr>
<td>??? field 1</td>
<td>??? field 2</td>
</tr>
Well, $rows is just an array that contains the fields you request in your query, so you can access its fields by using the index.
<?php
$rows = mysqli_query($conn,$query);
mysqli_fetch_all($rows,MYSQLI_ASSOC);
$html_string = "<table> <thead>....whatever optional... </thead> <tbody>";
foreach( $rows as $r){
$html_string .= "<tr> <td>" . $r[0] . "</td><td>" . $r[1] . "</td></tr>";
}
$html_string .= "</tbody></table>";
echo $html_string;
?>
Should be enough for the rows of your table.

get column names from stored procedure for displaying in html table using php

I am trying to display html table from a stored procedure using PDO.Resultset contains lot of columns and rows which needs to be exported to an excel.
But I need to get the column names to be on the first row, how can be possible on the below code? Any help ?
$q= $db->prepare( "CALL spalldetails" );
$q->execute();
while ($arrValues = $q->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
foreach ($arrValues as $key=>$value)
{
$column_names[]=$key;
?>
<td><?=$value?></td>
<?
}
echo "</tr>";
}
The below code displays the column name, but I want it to be the top row of the table.
echo "<tr>";
foreach ($column_names as $name)
{ ?>
<td>
<?=$name?>
</td>
<?
}
echo "</tr>";
?>
The question has nothing to do with stored procedures, as it's applicable to any data returned from database.
the most convenient way would be to fetch the data first, get the column names from the first row and then print the data.
besides, use of prepare execute is not justified for this query
$data = $db->query( "CALL spalldetails" )->fetchAll(PDO::FETCH_ASSOC);
$column_names = array_keys($data[0]);
here you have your column names before output which you can make using foreach() instead of while()
I would suggest instead of printing the output immediately while processing the through the for loop, you rather create a string to output later. This can be accomplished simply like this: (mind you the below is untested air code, but to show you an example of what I mean)
$q= $db->prepare( "CALL spalldetails" );
$q->execute();
while ($arrValues = $q->fetch(PDO::FETCH_ASSOC))
{
$tablestring .= "<tr>";
foreach ($arrValues as $key=>$value){
$column_names[]=$key;
$tablestring .= "<td>".$value."</td>";
}
$tablestring .= "</tr>";
}
$headstring .= "<tr>";
foreach ($column_names as $name)
{ $headstring .= "<td>".$name."</td>";
}
$headstring .= "</tr>";
echo "<table>".$headstring.$tablestring."</table>";

Can I display query results without naming columns?

Is there a php or html code to dynamically generate a table.
query :
"SELECT * FROM table1;
Can I display this grid of info without any specifics.
IF there are 4 rows and 4 columns I want the table to be that size; if 5x5 than that.
It seems like this should be possible, but all code I can find wants me to specify names or columns.
Yes. There are a couple different ways to do this, but for illustration I will assume that the result of your query is stored in a variable called $results, which is simply a multidimensional array that you can loop through using a double foreach to dynamically produce your table.
echo '<table>';
foreach ($results as $row) {
echo '<tr>';
foreach ($row as $col) {
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';
OR if you don't have a $results array and are instead getting query results and building the table at the same time, something like this might be more appropriate for your needs:
echo '<table>';
while ($row = mysqli_fetch_array($query)) {
echo '<tr>';
foreach ($row as $col) {
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';
echo'<table>';
while($row = mysql_fetch_array($result))
{
echo'<tr>';
echo '<td>'.$row[colname].'</td>';
echo '</tr>';
}
echo'</table>';

Selecting table data with PDO statements [duplicate]

This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
I have a php script that selects data via mysql_, however recently I have been reading that PDO is the way to go and that mysql_ is becoming depreciated. Now I am converting that script to PDO.
My question is though, I am not using $_POST to select. I just want to select the entire table with all of its data so I enter this query :
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query->fetchall(); // or you can just $result = $query as hakre proposed!
so then like I did with my old depreciated mysql_ version of the script I used the echo to echo a table with the data in it.
echo
"<table border='2'>
<tr>
<th>ID</th>
<th>A Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Why</th>
<th>Comments</th>
<th>Signintime</th>
</tr>"
;
foreach($result as $row)
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" .$row['anum'] . " </td>";
echo "<td>" . $row['first'] . "</td>";
echo "<td>" . $row['last'] . "</td>";
echo "<td>" . $row['why'] . "</td>";
echo "<td>" . $row['comments'] . "</td>";
echo "<td>" . $row['signintime'] . "</td>";
echo "<td> <input type=\"button\" value=\"Start Session\"onClick=\accept.php?id=" . $row['id'] . "&start=true></td>";
}
echo "</tr>";
echo "</table>";
now using this, I can not get a single output to my table.
My question is am I missing something from my select statements? Or am I not fetching any rows? Also I the connection settings set in another script called connect.php that is required by init.php (at the top of all of my pages)
Edit : 1
Edited the code so it now works, also adding a picture to show others how it should look! Hopefully some one can put this to some sort of use!
You are doing too much actually:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $dbh->query($query);
The problematic line is:
$result = $dbh->query($query);
Check with http://php.net/pdo.query, the parameter is a string, actually the SQL string you already use above, not the result value of a PDO::prepare() call.
For your simple query you can just do:
$result = $dbh->query("SELECT * FROM students");
Or if you like to prepare:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query;
The later is some boilerplate if you want to insert variables into the query, that's why you prepare it.
The next problem is with the foreach line:
foreach($result as $row);
You are terminating the loop immediately because of the semicolon ; at the end. Remove that semicolon so that the following angle-bracketed code-block becomes the body of the foreach-loop.
Your code is wrong:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $dbh->query($query);
After executing a prepared statement, you can just call fetchAll() on it:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query->fetchAll();
The rest of your code will work fine once you remove the semicolon after the foreach.

Categories