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.
Related
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,
I'm trying to make a code that permits the user to show any table in my database in a php page.
I tried with that code:
<?php
include('connection_db.php');
$table = $_POST['table'];
$sql1 = "SELECT * FROM $table";
$sql2 = "SELECT count(*)
FROM information_schema.columns
WHERE table_name = '$table'";
$sql3 = "SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'$table'";
$result = mysql_query($sql1);
$column = mysql_query($sql2);
$ncolumn= mysql_query($sql3);
echo "<table width='100%' border='1'>";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
for ($i = 0; $i <= $column; $i++) {
echo "<td>". $row['$ncolumn'] ."</td>";
}
echo "</tr>";
echo "<br/>";
}
echo "</table>";
?>
It should show the entire table with his records, but it shows only a lot of empty lines
$table = $_POST['table'];
$mysqli = new mysqli(_DB_SERVER_,_DB_USER_,_DB_PASSWD_,_DB_NAME_);
$mysqli->set_charset("utf8");
if (mysqli_connect_errno()) {
$Message = "Connect failed: %s\n" . $mysqli->connect_error;
exit();
}
if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
if($result->num_rows == 1) {
$Tableexists = "yes";
} else {
$Tableexists = "no";
}
} else {
$Tableexists = 0;
}
echo $Tableexists;
I've been having issues displaying items that i saved from my database in an array. My table has two columns for 'name' and 'details'. I successfully retrieved them using mySQLi and stored in an array but instead of displaying all the columns at once, I want to place them at different places on my webpage. eg
<p>$Name1: $Details1</p>. then on another section of the same page
<p>$Name2: $Details2</p>. This is my code:
<?php
include ("config/database.php");
$mysqli = new mysqli($host, $user, $passwd, $database);
if ($mysqli-> connect_errno){
printf("Connect failed: %s\n",$mysqli-> connect_error);
exit();
}
$query = "SELECT name, details FROM recent_properties LIMIT 3";
if($result = $mysqli->query($query)){
printf("%s: %s<br>", $row["name"], $row["details"]);
$result->free();
}
$mysqli->close();
?>
Did you try like this.Make use of loop. To display all the records.
$query = "SELECT name, details FROM recent_properties LIMIT 3";
$result = $mysqli->query($query);
if($result->num_rows()>0)
{
while($row = $result->fetch_assoc())
{
printf("%s: %s<br>", $row["name"], $row["details"]);
}
}
$mysqli->close();
$query = "SELECT name, details FROM recent_properties";
$result = $mysqli->query($query);
if($result->num_rows()>0)
{
$html = "<table>";
$html .= '<tr><th>Name</th><th>Details</th></tr>';
while ($row = $result->fetch_assoc()) {
$html .= '<tr>';
$html .= '<td>' . $row["name"] . '<td>';
$html .= '<td>' . $row["details"] . '<td>';
$html .= '</tr>';
}
$html .= "</table>";
echo $html;
}
$mysqli->close();
this is the simplest way to create HTML content from data
in your case you can do some thing like this
if ($result->num_rows() > 0) {
$dataArray = [];
while ($row = $result->fetch_assoc()) {
$dataArray[$row["name"]] = $row["details"];
}
}
and then use the array in your HTML
<body>
<p><?php echo 'a: ' . $arrayData['a'] ?></p>
<p><?php echo 'b: ' . $arrayData['b'] ?></p>
<p><?php echo 'c: ' . $arrayData['c'] ?></p>
</body>
You need to loop through your $result and fetch an associative array:
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["name"], $row["details"]);
}
EDIT:
while ($row = $result->fetch_assoc()) {
echo '<p>'.$Name1.': '.$Details1.'</p>';
// Whatever else in this section
// You can even break out of PHP and then
// get back into PHP again if you have a lot of HTML.
}
I am trying to print the value from database. the database contains the image URL.
I am retrieving the image url through php and printing it.
I have written this code to do so.
code:
<?php
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT name,thumbnail,link FROM courses';
mysql_select_db($dbname);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
echo "<td><a href='".$row['link']."' title='Click to see schedule'><img src='".$row['thumbnail']."'></a></td>";
echo "</tr>";
}
mysql_close($conn);
?>
This code is retriving image URL and displaying images on table. But I want 3 images per row, now it is printing only 1 image per row.
How can i do this?
You need to change your code to only open and close the row every third image. Try this:
$i = 0;
while($row = mysql_fetch_assoc($retval))
{
if($i == 0) {
echo "<tr>";
}
echo "<td><a href='".$row['link']."' title='Click to see schedule'><img src='".$row['thumbnail']."'></a></td>";
if(++$i == 3) {
echo "</tr>";
$i = 0;
}
}
// To close any open rows at the end
if($i % 3 > 0) {
echo "</tr>";
}
$cc = 0;
//initially open table row
echo "<tr>";
while($row = mysql_fetch_assoc($retval))
{
$cc++;
echo sprintf(
'<td><img src="%s"></td>',
$row['link'],
$row['thumbnail']
);
//close tablerow and open new one every 3 rows
if($cc % 3 == 0){
echo "</tr><tr>";
}
}
//close last table row
echo "</tr>";
this code prints data in 3 columns in a row. Please try
$cols=3; $col=0;
$vars = "<table>";
$vars .= "<tr>";
while($row = mysql_fetch_assoc($retval)){
$col++;
$vars .= "<td>".$row['link']."</td>";
if($col==$cols){
$col=0;
$vars .= "</tr><tr>";
}
}
$vars = "</tr>";
$vars .= "</table>";
Hope this helps.
Is this OK ?
$i = 0;
while ($row = mysql_fetch_array($result))
{
$resultset[] = $row;
$columns[] = mysql_fetch_field($result, $i);
}
Then when trying to print
<tr><th><?php echo $columns[0] ?></th><th><?php echo $columns[1] ?></th></tr>
I got an error
Catchable fatal error: Object of class stdClass could not be converted to string
Try the mysql_fetch_field function.
For example:
<?php
$dbLink = mysql_connect('localhost', 'usr', 'pwd');
mysql_select_db('test', $dbLink);
$sql = "SELECT * FROM cartable";
$result = mysql_query($sql) or die(mysql_error());
// Print the column names as the headers of a table
echo "<table><tr>";
for($i = 0; $i < mysql_num_fields($result); $i++) {
$field_info = mysql_fetch_field($result, $i);
echo "<th>{$field_info->name}</th>";
}
// Print the data
while($row = mysql_fetch_row($result)) {
echo "<tr>";
foreach($row as $_column) {
echo "<td>{$_column}</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Use mysql_fetch_assoc to get only an associative array and retrieve the column names with the first iteration:
$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
}
$resultset[] = $row;
}
Now you can print the head of your table with the first iteration as well:
echo '<table>';
$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
echo '<tr><th>'.implode('</th><th>', $columns).'</th></tr>';
}
$resultset[] = $row;
echo '<tr><td>'.implode('</td><td>', $rows).'</td></tr>';
}
echo '</table>';
You want to look at
mysql_fetch_assoc
Which gives each row as an associative key => value pair where the key is the column name.
Documentation here
Here is a more modern solution with ...i:
$db_link = #mysqli_connect($server, $user, $pass, $db) or die("Connection failed");
$spalten = ['pc_name', 'pc_type', 'pc_snr', 'pc_bj', 'mo_port_1', 'mo_snr_1', 'mo_bj_1', 'mo_port_2', 'mo_snr_2', 'mo_bj_2'];
$abfrage = "SELECT " . implode(',', $spalten) . " FROM hardware order by pc_name";
$liste = mysqli_query($db_link, $abfrage);
$spalten = mysqli_num_fields($liste);
while ($werte[] = mysqli_fetch_array($liste, MYSQLI_ASSOC)) {}
<table class="display" id="table" style="width:100%">
<thead>
<tr>
<?php
for ($i = 0; $i < $spalten; $i++) {
$feldname[$i] = mysqli_fetch_field_direct($liste, $i)->name;
echo '<th>' . ucfirst($feldname[$i]) . '</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < mysqli_num_rows($liste); $i++) {
?>
<tr>
<?php for ($j = 0; $j < $spalten; $j++) {
?>
<td><?php
echo $werte[$i][$feldname[$j]];
?>
</td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
Though it's deprecated and no longer in PHP 7 you can avoid having to use an object by using the function mysql_field_name instead which returns a string.