How to echo out table rows from the db (php) - php

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'])

Related

mysqli_fetch_array is working only first time [duplicate]

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.....

nested while loop ( inside while loop) works only for once [duplicate]

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.....

Writing the attributes of a database in PHP

I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>

Failed to iterate over selected rows

The code is supposed to get a row at each loop and build td elements for each data piece. However, it only gets some rows while missing others even though all rows were selected:
$query = "select * from category";
$ret = mysql_query($query, $conn);
while ($rows = mysql_fetch_assoc($ret)) {
echo "<tr>";
foreach ($rows as $val) {
echo "<td>{$val}</td>";
}
}
mysql_fetch_assoc returns an associative array. To display each returned row, do something like this (taken directly from the php.net page for mysql_fetch_assoc
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
Try removing the curly braces like this:
echo "<td>$val</td>";
Beside you didn't close the <tr> tag. So you should do this:
$query = "select * from category";
$ret = mysql_query($query, $conn);
while ($rows = mysql_fetch_assoc($ret)) {
echo "<tr>";
foreach ($rows as $val) {
echo "<td>$val</td>";
}
echo"</tr>";
}
Now like Jack Albright said you should consider various columns of your table to display specific data. Upon that the while() is already a look, I think you don't need to add any foreach() inside. SO your final code should look like this:
$query = "select * from category";
$ret = mysql_query($query, $conn);
while ($rows = mysql_fetch_assoc($ret)) {
echo "<tr>";
echo "<td>$rows['columnName']</td>";
echo "</tr>";
}

How can I use mysqli_fetch_array() twice?

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.....

Categories