Adding mysql data as td attribute with php - php

I need this code to give me a little different output.
<?php
$conn=mysqli_connect("localhost","root","","");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function print_tableA ($conn, $id) {
$sql = "SELECT Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8 FROM mytable1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='$id'>";
while($row = $result->fetch_assoc()) {
echo '<tr><td>' . join('</td><td>', $row) . "</td></tr>\n" ;
}
echo "</table>";
}
}
$result = $conn->query("SELECT Date from mytable2");
while ($row = $result->fetch_assoc()) {
print_tableA ($conn, $row['Date']);
}
?>
Currently it prints the output in this format: `
<tr>
<td>2</td>
....
</tr>`
I need it to be printed in this format:
<tr>
<td val="2">2</td>
....
</tr>
so basically the data from the mysql should also be repeated as a td attribute. I hope this is simple, and I'd be grateful if someone can show me the change that I need to make to get this output. Thanks.

Replace while loop with this one:
while($row = $result->fetch_assoc()) {
$data = array_reduce($row, function($carry, $value) {
$carry[] = "<td val='{$value}'>{$value}</td>";
return $carry;
}, []);
echo '<tr>' . implode('', $data) . "</tr>\n" ;
}
will output:
<tr><td val='10'>10</td><td val='11'>11</td></tr>
A sendbox example can be found here.
PHP Manual for array_reduce function.

You need to iterate through the row values and echo the td as you want them:
while($row = $result->fetch_assoc()) {
echo '<tr>';
// Let's iterate through all the columns
foreach ($row as $value) {
echo "<td val='$value'>$value</td>";
}
echo "</tr>\n";
}
Just as a note: val isn't a valid attribute in for a td-element.

Related

how to output mysql table data into an html table without knowing what $row is like phpmyadmin

Ok so I'm trying to make a localhost site that has the same base functions as Phpmyadmin, and everything is working other than displaying a table's data.
here's an example of what I'm trying to accomplish:
though I'm not sure how to accomplish this. Here is some code to show you what I have now
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$columquery = "SHOW COLUMNS FROM " . $table;
$columresult = mysql_query($columquery);
while ($row3 = mysql_fetch_array($columresult)) {
echo "<th>" . $row3['Field'] . "</th>";
}
?>
<?php
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($result2)) {
foreach($row2 as $var) {
echo "<tr><td>" . $var . "</td></tr>";
}
}
?>
</table>
</div>
Yes yes, I know it's horrible.
The other answers use the mysqli API while you're using the older, no longer supported mysql API. I really recommend upgrading to either mysqli or PDO, but if you want to stay with mysql you can use the following solution:
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$shouldOutputHeaders = true;
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2)) {
if ($shouldOutputHeaders) {
echo "<tr>";
foreach (array_keys($row2) as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
$shouldOutputHeaders = false;
}
echo "<tr>";
foreach ($row2 as $var) {
echo "<td>" . $var . "</td>";
}
echo "</tr>";
}
?>
</table>
</div>
If i understood you well, You need mysqli_fetch_row.
$q= "SELECT * FROM table";
$result = $mysqli->query($q)
while ($row = $result->fetch_row()) {
print ("$row[0], $row[1]);
}
I think you are looking for something very ugly like the following. I found it in the garbage. I am not responsable for any use of it:
<?php
$db=Db::getConnection(); // singleton
$this->var['result']=$db->query($_POST['query']);
if (isset($this->var['result'])) {
echo '<table cellpadding="5" cellspacing="2" border="1"><tbody>';
$titles=array_keys(#$this->var['result'][0]);
echo '<tr>';
foreach($titles as $title)
echo '<th>'.$title.'</th>';
echo '</tr>';
foreach($this->var['result'] as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
}
?>
Db is an standard singleton that contains a mysqli private object.
query() contains something like
$sql = $this->mysqli->query($query);
$this->lastInsertId = $this->mysqli->insert_id;
$errno = $this->mysqli->connect_errno;
if ($errno === 0) {
if ($this->mysqli->field_count > 0) {
while ($row = $sql->fetch_assoc()) $response[] = $row;
return $response;
}else{
return true;
}
}
to create the "array of arrays" response. Suitable for the output you are looking for.
I've added some escaping and only queried the database when needed:
// Print table tags
echo "<table>";
// Print out records
$q = mysql_query("SELECT * FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print out columns
$columns = array_keys($res[0]);
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$columns).'</th></tr>';
// Print out table data
echo'<tr><td>'.implode('</td><td>', array_map('htmlspecialchars',$res).'</td></tr>';
} else {
// IFF there is no data, print out columns
$q = mysql_query("SHOW COLUMNS FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print columns
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$res).'</th></tr>';
}
}
echo '</table>';
Hope this helps,

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>

Displaying all tables in a database

How do I display out all the information in a database (All tables and records) using PHP? I read displaying tables as HTML table but how do I do it for all the tables?
I tried the example here:
http://davidwalsh.name/html-mysql-php
But it shows the table names, how do I also display all the values?
Okay got it .. try this
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "username", "password", "DB");
$result = $mysqli->query("SHOW TABLES");
while ($row = $result->fetch_row()) {
$table = $row[0];
echo '<h3>', $table, '</h3>';
$result1 = $mysqli->query("SELECT * FROM `$table`");
echo '<table cellpadding="0" cellspacing="0" class="db-table">';
$column = $mysqli->query("SHOW COLUMNS FROM `$table`");
echo '<tr>';
while ($row3 = $column->fetch_row()) {
echo '<th>' . $row3[0] . '</th>';
}
echo '</tr>';
while ($row2 = $result1->fetch_row()) {
echo '<tr>';
foreach ($row2 as $key => $value) {
echo '<td>', $value, '</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
$mysqli->close();
you can use the recursive function to display the tree Structure of your database.
Here is the a sample code from http://webcodingeasy.com/PHP/Simple-recursive-function-to-print-out-database-tree-structure
<?php
function print_menu($id = 0)
{
// get all records from database whose parent is $id
$result = $query->select_result("*", "table", "where parent = '".$id."'");
//check if there are any results
if($result != 0)
{
echo "<ul> n";
while($row = $query->fetch($result))
{
//print result and call function to check if it has children
echo "<li>".$row['name']."</li> n";
print_menu($row['ID']);
}
echo "</ul> n";
}
}
print_menu();
?>
If you want to pull all tables with the values in mysql, you can use the following code:
<?php
mysql_connect ("localhost", "DB_USER", "DB_PASSWORD"); //your mysql connection
mysql_select_db('DB_NAME') or die( "Unable to select database"); //your db name
$tables = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema='DB_NAME'"); //pull tables from theh databsase
while ($table= mysql_fetch_row($tables)) {
$rsFields = mysql_query("SHOW COLUMNS FROM ".$table[0]);
while ($field = mysql_fetch_assoc($rsFields)) {
echo $table[0].".".$field["Field"].", "; //prints out all columns
}
echo $table[0];
$query = "SELECT * FROM ".$table[0]; //prints out tables name
$result = mysql_query($query);
PullValues($result); //call function to get all values
}
//function to pull all values from tables
function PullValues($result)
{
if($result == 0)
{
echo "<b>Error ".mysql_errno().": ".mysql_error()."</b>";
}
elseif (#mysql_num_rows($result) == 0)
{
echo("<b>Query completed. No results returned.</b><br>");
}
else
{
echo "<table border='1'>
<thead>
<tr><th>[Num]</th>";
for($i = 0;$i < mysql_num_fields($result);$i++)
{
echo "<th>" . $i . " - " . mysql_field_name($result, $i) . "</th>";
}
echo " </tr>
</thead>
<tbody>";
for ($i = 0; $i < mysql_num_rows($result); $i++)
{
echo "<tr><td>[$i]</td>";
$row = mysql_fetch_row($result);
for($j = 0;$j < mysql_num_fields($result);$j++)
{
echo("<td>" . $row[$j] . "</td>");
}
echo "</tr>";
}
echo "</tbody>
</table>";
} //end else
}
?>
I am using this and works fine in mysql, for mysqli you need to tweak it a very little.

How to increase mysql_fetch_array pointer?

while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
$row = mysql_fetch_array($result, MYSQL_ASSOC) //it's not increase ?
}
i want increase two time in each loop?
for
<table>
<td>**1 times**</td><td>**1 times**</td>
</table>
I think the documentation is very clear. http://hu.php.net/manual/en/function.mysql-fetch-array.php or http://hu.php.net/manual/en/function.mysql-fetch-assoc.php.
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
You don't need that.
If you want to print your data formatted in 2 columns, select it all into array and then use that array for the formatted output.
one of possible solutions
<?php
//collect data into array
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
//and here goes template part
?>
<html>
<? $data = array_chunk($data, 2) ?>
<table>
<? foreach ($data as $chunk): ?>
<tr>
<? foreach ($chunk as $row): ?>
<td><?=$row['name']?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
it WILL increase the pointer by 1 step...
therefore:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// logic here
}
will perform the loop and logic
Why not do something like this:
$max_row = 100;//mysql_num_rows($result);
for($idx = 0; $idx < $max_row; $idx+=2){
if (!mysql_data_seek($result, $i)) {
echo "Cannot seek to row $i: " . mysql_error() . "\n";
continue;
}
if (!($row = mysql_fetch_assoc($result))) {
continue;
}
//do what you want to do here...
}
if you have 10 records, it will echo row 0, 2, 4, 6, 8.
<?php
$counter=0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if ($counter % 2)
{
echo '<table><tr>'; // start table
}
echo '<td>' . $row['foo'] . '</td>'; // echo result
if (!$counter % 2)
{
echo "</tr></table>"; // end table
}
$counter++;
}
?>
Maybe you want mysql_data_seek?

How to echo out table rows from the db (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'])

Categories