I am using the entries from a database to fill a row and a column in a table. But I cannot access the SQL returned data twice using mysqli_fetch_array() twice. I need to loop mysqli result more than once. This doesn't work:
//Copy the result
$db_res = mysqli_query( $db_link, $sql );
$db_res2=$db_res;
//Top row
while ($row = mysqli_fetch_array( $db_res, MYSQL_ASSOC))
{
echo "<td>". $row['Title'] . "</td>";
}
//leftmost column
while ($row = mysqli_fetch_array( $db_res2, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>". $row['Title'] . "</td>";
.....
echo "</tr>";
}
How can I apply mysqli_fetch_array twice on the same result?
You should always separate data manipulations from output.
Select your data first:
$db_res = mysqli_query( $db_link, $sql );
$data = array();
while ($row = mysqli_fetch_assoc($db_res))
{
$data[] = $row;
}
Note that since PHP 5.3 you can use fetch_all() instead of the explicit loop:
$db_res = mysqli_query( $db_link, $sql );
$data = $db_res->fetch_all(MYSQLI_ASSOC);
Then use it as many times as you wish:
//Top row
foreach ($data as $row)
{
echo "<td>". $row['Title'] . "</td>";
}
//leftmost column
foreach ($data as $row)
{
echo "<tr>";
echo "<td>". $row['Title'] . "</td>";
.....
echo "</tr>";
}
Yes. mysqli_fetch_array() moves the pointer forward each time you call it. You need mysqli_data_seek() to set the pointer back to the start and then call mysqli_fetch_array() again.
So before calling the function a second time, do:
mysqli_data_seek($db_res, 0);
You don't need the while loop and you don't need to use mysqli_fetch_array() at all!
You can simply loop on the mysqli_result object itself many times. It implements Traversable interface that allows it to be used in foreach.
//Top row
foreach($db_res as $row) {
echo "<td>". $row['Title'] . "</td>";
}
//leftmost column
foreach($db_res as $row) {
echo "<tr>";
echo "<td>". $row['Title'] . "</td>";
.....
echo "</tr>";
}
However, you should separate your DB logic from your display logic and to achieve this it is best to use fetch_all(MYSQLI_ASSOC) in your DB logic to retrieve all records into an array.
If you fetch all the data into an array, you can loop that array as many times as you want.
$data = $db_res->fetch_all(MYSQLI_ASSOC);
foreach($data as $row) {
// logic here...
}
$squery = mysqli_query($con,"SELECT * FROM table");
while($s = mysqli_fetch_array($query)){
....
}
// add this line
mysqli_data_seek( $query, 0 );
while($r = mysqli_fetch_array($query)){
...
}
try it.....
Related
I am using the entries from a database to fill a row and a column in a table. But I cannot access the SQL returned data twice using mysqli_fetch_array() twice. I need to loop mysqli result more than once. This doesn't work:
//Copy the result
$db_res = mysqli_query( $db_link, $sql );
$db_res2=$db_res;
//Top row
while ($row = mysqli_fetch_array( $db_res, MYSQL_ASSOC))
{
echo "<td>". $row['Title'] . "</td>";
}
//leftmost column
while ($row = mysqli_fetch_array( $db_res2, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>". $row['Title'] . "</td>";
.....
echo "</tr>";
}
How can I apply mysqli_fetch_array twice on the same result?
You should always separate data manipulations from output.
Select your data first:
$db_res = mysqli_query( $db_link, $sql );
$data = array();
while ($row = mysqli_fetch_assoc($db_res))
{
$data[] = $row;
}
Note that since PHP 5.3 you can use fetch_all() instead of the explicit loop:
$db_res = mysqli_query( $db_link, $sql );
$data = $db_res->fetch_all(MYSQLI_ASSOC);
Then use it as many times as you wish:
//Top row
foreach ($data as $row)
{
echo "<td>". $row['Title'] . "</td>";
}
//leftmost column
foreach ($data as $row)
{
echo "<tr>";
echo "<td>". $row['Title'] . "</td>";
.....
echo "</tr>";
}
Yes. mysqli_fetch_array() moves the pointer forward each time you call it. You need mysqli_data_seek() to set the pointer back to the start and then call mysqli_fetch_array() again.
So before calling the function a second time, do:
mysqli_data_seek($db_res, 0);
You don't need the while loop and you don't need to use mysqli_fetch_array() at all!
You can simply loop on the mysqli_result object itself many times. It implements Traversable interface that allows it to be used in foreach.
//Top row
foreach($db_res as $row) {
echo "<td>". $row['Title'] . "</td>";
}
//leftmost column
foreach($db_res as $row) {
echo "<tr>";
echo "<td>". $row['Title'] . "</td>";
.....
echo "</tr>";
}
However, you should separate your DB logic from your display logic and to achieve this it is best to use fetch_all(MYSQLI_ASSOC) in your DB logic to retrieve all records into an array.
If you fetch all the data into an array, you can loop that array as many times as you want.
$data = $db_res->fetch_all(MYSQLI_ASSOC);
foreach($data as $row) {
// logic here...
}
$squery = mysqli_query($con,"SELECT * FROM table");
while($s = mysqli_fetch_array($query)){
....
}
// add this line
mysqli_data_seek( $query, 0 );
while($r = mysqli_fetch_array($query)){
...
}
try it.....
I'm trying to show a full table from SQL in my HTML/PHP webpage. So far I succeeded to fetch the data from the table in my webpage without define each row in HTML. This works, but it shows the data from the table only. I want to see the column names in the first row.
See my code below:
include_once "connection.php";
$sql = "SELECT * FROM `own`";
$result = mysqli_query($conn, $sql);
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
As you are using mysqli_fetch_assoc() - this will return an array with the column names as the key for each value. So this code will display (for the first loop only) the column names as a separate row.
$headerDisplayed = false;
while ($row = mysqli_fetch_assoc($result))
{
if ( $headerDisplayed == false ) {
echo "<tr>";
foreach($row as $columnName => $value) {
echo "<th>" . $columnName . "</th>";
}
echo "</tr>";
$headerDisplayed = true;
}
echo "<tr>";
foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
If you want to be able to give a more meaningful name, you could also use column aliases (for example)..
select `dept_no` as `department number` from `departments`
will show department number as the heading instead of dept_no.
The easiest solution would be to just output the column names first on the first iteration:
while ($row = mysqli_fetch_assoc($result))
{
// If the variable $colNamesPrinted is undefined, print the column names
if (isset($colNamesPrinted) === false) {
echo "<tr>";
foreach($row as $name => $value) {
echo "<th>" . $name . "</th>";
}
echo "</tr>";
// Define the variable so it will be set on the next iteration.
$colNamesPrinted = true;
}
echo "<tr>";
foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
I am trying to create a dynamically made table that will display multiple drop down lists within each row with previously selected values that are stored within a DB.
Currently I am stuck on just displaying the proper values within each <td>.
//$query..
$data = mysqli_query($dbc, $query);
echo"<table>
<tr>
<th>Component</th>
<th>Component Type</th>
<th>Component Thickness</th>
</tr>";
while ($row = mysqli_fetch_array($data)) { //while I have rows..
//add column values to an array
$facSecComponentID[] = $row['facility_section_components_id'];
$facSecComponent[] = $row['roof_component_id'];
$facSecComponentType[] = $row['roof_component_type_id'];
$facSecComponentThickness[] = $row['component_thickness'];
//try to loop through each index of each row and get the DB value..
//eventually use this value to assign a selected index within the drop down list
foreach ($row as $componentIndex => $selectedComponent) {
echo "<tr>";
echo "<td>" . $facSecComponent[$selectedComponent] . "</td>";
echo "<td>" . $facSecComponentType[$selectedComponent] . "</td>";
echo "<td>" . $facSecComponentThickness[$selectedComponent] . "</td>";
echo "</tr>";
}
}
echo "</table>";
I can't get the values I need here to display properly, I have also tried to do something like: "<td>" . $componentIndex[$selectedComponent] . "</td>"; which didn't help.
I keep getting undefined index errors or all fields being a single value.
Let me know if anything is unclear or needs further explanation and I will try to make my question more clear.
Any help would be great,
Thanks
Try:
$facSecComponentID = array();
$facSecComponent = array();
$facSecComponentType = array();
$facSecComponentThickness = array();
while ($row = mysqli_fetch_array($data)) {
$facSecComponentID[] = $row['facility_section_components_id'];
$facSecComponent[] = $row['roof_component_id'];
$facSecComponentType[] = $row['roof_component_type_id'];
$facSecComponentThickness[] = $row['component_thickness'];
}
$numItems = mysqli_num_rows($result);
for($i=0;$i<$numItems;$i++){
echo "<tr>";
echo "<td>{$facSecComponent[$i]}</td>";
echo "<td>{$facSecComponentType[$i]}</td>";
echo "<td>{$facSecComponentThickness[$i]}</td>";
echo "</tr>";
}
It's better if you concatenate a string like
$this->Table ="<table>";
while($MyRow = mysqli_fetch_array($fect)){
$this->Table .="<tr><td>".$MyRow['data']."</td></tr>";
}
$this->Table .="</table>";
return $this->Table ;
I am using the entries from a database to fill a row and a column in a table. But I cannot access the SQL returned data twice using mysqli_fetch_array() twice. I need to loop mysqli result more than once. This doesn't work:
//Copy the result
$db_res = mysqli_query( $db_link, $sql );
$db_res2=$db_res;
//Top row
while ($row = mysqli_fetch_array( $db_res, MYSQL_ASSOC))
{
echo "<td>". $row['Title'] . "</td>";
}
//leftmost column
while ($row = mysqli_fetch_array( $db_res2, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>". $row['Title'] . "</td>";
.....
echo "</tr>";
}
How can I apply mysqli_fetch_array twice on the same result?
You should always separate data manipulations from output.
Select your data first:
$db_res = mysqli_query( $db_link, $sql );
$data = array();
while ($row = mysqli_fetch_assoc($db_res))
{
$data[] = $row;
}
Note that since PHP 5.3 you can use fetch_all() instead of the explicit loop:
$db_res = mysqli_query( $db_link, $sql );
$data = $db_res->fetch_all(MYSQLI_ASSOC);
Then use it as many times as you wish:
//Top row
foreach ($data as $row)
{
echo "<td>". $row['Title'] . "</td>";
}
//leftmost column
foreach ($data as $row)
{
echo "<tr>";
echo "<td>". $row['Title'] . "</td>";
.....
echo "</tr>";
}
Yes. mysqli_fetch_array() moves the pointer forward each time you call it. You need mysqli_data_seek() to set the pointer back to the start and then call mysqli_fetch_array() again.
So before calling the function a second time, do:
mysqli_data_seek($db_res, 0);
You don't need the while loop and you don't need to use mysqli_fetch_array() at all!
You can simply loop on the mysqli_result object itself many times. It implements Traversable interface that allows it to be used in foreach.
//Top row
foreach($db_res as $row) {
echo "<td>". $row['Title'] . "</td>";
}
//leftmost column
foreach($db_res as $row) {
echo "<tr>";
echo "<td>". $row['Title'] . "</td>";
.....
echo "</tr>";
}
However, you should separate your DB logic from your display logic and to achieve this it is best to use fetch_all(MYSQLI_ASSOC) in your DB logic to retrieve all records into an array.
If you fetch all the data into an array, you can loop that array as many times as you want.
$data = $db_res->fetch_all(MYSQLI_ASSOC);
foreach($data as $row) {
// logic here...
}
$squery = mysqli_query($con,"SELECT * FROM table");
while($s = mysqli_fetch_array($query)){
....
}
// add this line
mysqli_data_seek( $query, 0 );
while($r = mysqli_fetch_array($query)){
...
}
try it.....
i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but what I want is all of them, echoed out one after the other. How can I turn a mysql result into something I can use?
I tried:
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
$res = mysql_result($results, 0);
while ($res->fetchInto($row)) {
echo "<form id=\"$row[0]\" name=\"$row[0]\" method=post action=\"\"><td style=\"border-bottom:1px solid black\">$row[0]</td><td style=\"border-bottom:1px solid black\"><input type=hidden name=\"remove\" value=\"$row[0]\"><input type=submit value=Remove></td><tr></form>\n";
}
$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
echo "<tr>";
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.
Wrapped in <table> so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
echo "<tr>";
foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.
Nested loop to display all rows & columns of resulting table:
$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
for( $j = 0; $j<$cols; $j++ ) {
echo mysql_result($result, $i, $j)."<br>";
}
}
Can be made more complex with data decryption/decoding, error checking & html formatting before display.
Tested in MS Edge & G Chrome, PHP 5.6
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach() (because it is "iterable") which eliminates the need to maked iterated _fetch() calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id'])