Listing the tables content in the database - php

written a script to print the contents of all the tables present in the database...
but unfortunately i am going wrong somewhere. could anyone please tell me where is the mistake?
$sql = "SHOW TABLES FROM $dbName";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
for ($i=1; $i<=5; $i++)
{
while ($row = mysql_fetch_row($result))
{
echo "Table: {$row[0]}\n";
$sql_1 = "SELECT * FROM {$row[0]}";
$result_1 = mysql_query($sql_1);
$row_1 = mysql_fetch_row($result);
echo "$row_1";
}
}
mysql_free_result($result);
?>
thanks..

first of all, u don't need
for ($i=1; $i<=5; $i++)
Also, $row_1 is an array, so to print it use something like
print_r($row_1);
And there might be not the only row in a table, so use construction like
while ($row = mysql_fetch_row($result))
{
echo "Table: {$row[0]}\n";
$sql_1 = "SELECT * FROM {$row[0]}";
$result_1 = mysql_query($sql_1);
while ($row_1 = mysql_fetch_row($result_1/*There was also an error*/))
print_r($row_1); /*Print_r or other function to print an array*/
}

Related

Parsing empty rows from MySQL table and output as html table without empty cells

I have been trying to create a PHP function that can display a MySQL table as a HTML table using PHP. So far I am able to output any table I choice, yet I am encountering a problem when the MySQL table contains empty rows, because empty cells result in the HTML tables. My code is as such:
<?php
function getTABLE(){
$db_host = 'HOST.com';
$db_user = 'USER1';
$db_pwd = 'PASSWORD';
$database = 'testdb';
$table = 'FAQTable';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
//// sending query and only result cell that are not NULL
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h3><center>Table: {$table}</h3>";
echo "<table border='1'><tr>";
//// printing table headers
for($i=0; $i<$fields_num; $i++){
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
//// printing table rows
while($row = mysql_fetch_row($result)){
echo "<tr>";
//// $row is array... foreach( .. ) puts every element
//// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>";
}
print "</TABLE>";
mysql_close();
}
print getTABLE();
?>
My dilemma is in the "printing table rows" section of the code. I am hoping there is a way in the while($row = mysql_fetch_row($result)) to only accept rows that have values in them. Any ideas?
I have already tried using the following lines with no luck:
$result = mysql_query("SELECT * FROM {$table} WHERE * IS NOT NULL");
$result = mysql_query("SELECT COUNT(id) FROM {$table} where answer IS NOT NULL or answer <>'' ");
$result = mysql_query('SELECT COUNT(*) FROM {$table} WHERE answer <> ""');
$result = mysql_query("SELECT * FROM {$table} WHERE CHAR_LENGTH>0");
$result = mysql_query("SELECT * FROM {$table} WHERE val1 is <> '' ");
$result = mysql_query("SELECT * FROM {$table} WHERE col1 is <> '' ");
//// Outputs funky count in a separate table, but not the desired table with no empty cells
$result = mysql_query("SELECT COUNT(answer) FROM {$table} WHERE CHAR_LENGTH(answer)>0");
$result = mysql_query("SELECT COUNT(answer) FROM {$table} WHERE LENGTH(answer)>0");
$reslts = mysql_query("SELECT * FROM {$table}");
while($row = mysql_fetch_row($reslts)){
$empty_count = 0;
$count = count($row);
for($i = 0; $i < $count; $i++)
if($row[$i] === '' || $row[$i] === 'NULL')
$empty_count++;
$result = ($count);
}
So Thanks To Paul Spiegal for helping with this PHP function that can output any MySQL Table into a HTML Table to be displayed on a website... The working function is as follows, just change the values for the variables to access any MySQL data:
function getTABLE(){
$db_host = 'www.host.com';
$db_user = 'user1';
$db_pwd = 'password';
$database = 'testdb';
$table = 'MyTable';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
//// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h3><center>Table: {$table}</h3>";
echo "<table border='1'><tr>";
//// printing table headers
for($i=0; $i<$fields_num; $i++){
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
//// printing table rows
while($row = mysql_fetch_row($result)){
echo "<tr>";
if (strlen(implode('', $row )) == 0) {
continue;
}else {
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>";
}
}
print "</TABLE>";
mysql_close();
}
print getTABLE();
Using implode() function, you can combine all cells into one string. If that string is empty, you skip printing that row.
while($row = mysql_fetch_row($result)){
if (strlen(implode('', $row)) == 0) {
continue; // skip this empty row
} else {
// TODO: print this row
}
}

Need to display a MySQL table on a page using PHP

I'm trying to get a table to display and keep getting an error. Could someone out there with better coding skills help me?
Here is the code:
<?php
// connect to the database
$host = "###";
$username = '###';
$pass = '###';
mysql_connect($host,$username,$pass) or die(mysql_error());
mysql_select_db("Employees") or die(mysql_error());
// select everything from the table
$query = "SELECT * FROM Employees";
$result = mysql_query($query') or die(mysql_error());
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_array($result)))
{
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
mysql_close();
?>
When the page runs it yields the following error:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /home/content/35/4683335/html/crosshill/display.php on line 36
Line 34 is: echo "<td>".$row['employeeid']."</td>";
I suggest that you need check 3 points:
You could use or die(mysql_error()) in dev environment to check if you have an error (with sql functions related).
Connection
mysql_connect($host,$username,$pass) or die(mysql_error());
Select db
mysql_select_db("Employees") or die(mysql_error());
Query (I see that you query are correct, but probably you table name are wrong, remember that names are case sensitive)
$result = mysql_query($query) or die(mysql_error());
I noticed your database is called Employees as well as your table, is this a mistake or are they both the same name?
You also have syntax error here:
$query = "SELECT * FROM Employees";
$result = mysql_query($query') or die(mysql_error());
Remove the ' so it is like this:
$result = mysql_query($query) or die(mysql_error());
Try this:
$query = "SELECT * FROM Employees";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result)< 1){
echo 'no rows founds';
} else {
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_assoc($result)))
{
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
}
echo "</tr>";
echo "</table>";
}
Side note:
As suggested by others you should switch to either mysqli_* or perhaps pdo.

Only Displaying one row Mysql

I want this data to display all the results, in the query I get 129 results. But when I display it on the page I only get one row. I have used very similar code to get multiple results before, so I know it`s something simple, but I just can't get it. Any thoughts would be greatly appreciated!
<?php
$sql = "SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber";
$sql1 = "select dataplan as currentplan from maindata GROUP BY phonenumber";
$sql2 = "SELECT DISTINCT phonenumber AS value_sum1 FROM maindata";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$result1 = mysql_query($sql2);
if (!$result1) {
echo "Could not successfully run query ($sql1) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result1) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$result2 = mysql_query($sql2);
if (!$result2) {
echo "Could not successfully run query ($sql2) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result2) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)){
echo "<TABLE id='display'>";
echo "<td><b>Data Usage This Period: ". ROUND ($row["value_sum"],2) . "MB</b></td> ";
}
while ($row1 = mysql_fetch_assoc($result1)){
echo "<TABLE id='display'>";
echo "<td><b>Data Plan: ". $row1["currentplan"] . "</b></td> ";
}
while ($row2 = mysql_fetch_assoc($result2)){
echo "<TABLE id='display'>";
echo "<td><b>Phone Number: ". $row2["value_sum1"] . "</b></td> ";
}
?>
Updated based on suggestions - Very helpful thank you, I am very close, all values are correct but I can not get them in the same table, thoughts?
TRY To use ,
Loop in you code eg.
$result1 = mysql_query("SELECT DISTINCT phonenumber AS value_sum1 FROM maindata");
echo '<table>';
echo '<tr>';
echo '<th>id</th>';
echo '</tr>';
while($record = mysql_fetch_assoc($result))
{
echo '<tr>';
foreach ($record as $val)
{
echo '<td>'.$val.'</td>';
}
echo '</tr>';
}
echo '</table>';
Add
"LIMIT 0, 1" at the end of query
or
edit query like "select TOP 1 from....."
Lets make it easy on you ;)
have a look here how to use mysql_fetch_assoc
http://php.net/manual/en/function.mysql-fetch-assoc.php
follow the examples, you will be done in a sec.

PHP Script, Table data populating from form

<html><head></head><body>
<?php
$db_hostname = "mysql";
$db_database = "u1da";
$db_username = "u1da";
$db_password = "1234";
$con = mysql_connect($db_hostname ,$db_username ,$db_password);
if (!$con) die ("Unable to connect to MySQL: ".mysql_error ());
mysql_select_db ( $db_database ) ||
die (" Unable to select database : ". mysql_error());
$query = "select * from students";
$result = mysql_query($query);
$result || die ("Database access failed: ".mysql_error());
$rows = mysql_num_rows($result);
echo "<table border=1>";
echo "<tr><td><p><b>Name</b></p></td></tr>";
for ($j = 0; $j < $rows ; $j ++) {
echo "<tr><td>", mysql_result($result,$j,'name') ,"</td></tr>";
}
echo "</table><br />";
$query2 = "select * from groups";
$result2 = mysql_query($query2);
$result2 || die ("Database access failed: ".mysql_error());
$rows2 = mysql_num_rows($result2);
echo "<table border=1>";
echo "<tr><td><p><b>Tutorial Group</b></p></td><td><p><b>Capacity</b></p></td></tr>";
for ($i = 0; $i < $rows2 ; $i ++) {
echo "<tr><td>", mysql_result($result2,$i,'Tutorial_Group') ,"</td><td>", mysql_result($result2,$i,'Capacity') ,"</td></tr>";
}
echo "</table>";
echo "<form method='post' action='' enctype="multipart/form-data">";
$query3 = "select * from students";
$result3 = mysql_query($query3);
echo "<br /><br /><select name='name'>";
while($name = mysql_fetch_array($result3)) {
echo "<option value='$name[Name]' > $name[Name] </option>"."<BR>";
}
echo "</select><br />";
$query4 = "select Tutorial_Group from groups";
$result4 = mysql_query($query4);
echo "<select name = 'group'>";
while($grp = mysql_fetch_array($result4)){
echo "<option value='$grp[Tutorial_Group]'>$grp[Tutorial_Group]</option>";
}
echo "</select><br />";
echo "Student ID: ";
echo '<input type="text" name="SID"><br />';
echo "Email: ";
echo '<input type="text" name="email"><br />';
echo '<input type="submit" name="submit" value="Submit">';
echo "</form>";
?>
Here is my current script code.
I have to make a query which will get the value from the 2 drop-down menus and 2 text fields and insert them into a table.
Table is called assg and have columns: Name, Student_ID, email, s_group. I have tried some different ways, but it didn't worked out. Please help.
Your first problem is that you are using mysql_fetch_array to get an array of elements into $grp variable but next you try to use it with a associative array to get values like $grp[Tutorial_Group]
Using mysql_fetch_array you can get $grp[0] ... $grp[1] but not $grp[Tutorial_Group]
You need to use mysql_fetch_assoc to get associative arrays like $grp[Tutorial_Group]
Your second problem is using complex php vars incorrectly example
Incorrect:
echo "<option value='$grp[Tutorial_Group]'>$grp[Tutorial_Group]</option>";
Correct:
echo '<option value="'.$grp['Tutorial_Group'].'">'.$grp['Tutorial_Group'].'</option>';
Or
echo "<option value='{$grp['Tutorial_Group']}'>{$grp['Tutorial_Group']}</option>";
Also the code only has the part to view the tables and the form. The insert part of the data is missing in the example. Probably this part has also some errors.
No indentation, html in echos, i don't even understand what you want.
By dropdown you mean select ?
What about $_POST['nameOfTheField'] ?
And why multipart ? There's no files to send here.

how do I traverse rows in a table

I have a table named members with 3 rows. The following code attempts to display all the rows in the members table. It displays the 1'st record 3 times instead of displaying each record once.
<?php
$con = new mysqli("localhost", "root", "jce123", "profile");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
$keysarray = array_keys($array);
$valuearray = array_values($array);
for ($i=0; $i < $num; $i++) {
for($j = 0; $j < count($array); $j++) {
echo "<table>";
echo "<tr><td>".$keysarray[$j].": </td><td>".$valuearray[$j]."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
mysqli_close($con);
?>
I've updated this per suggestions:
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
while ($row = mysqli_fetch_assoc($res)) {
foreach($array as $key => $value){
echo "<table>";
echo "<tr><td>".$key.": </td><td>".$value."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
That's because, your $num = 3, count($array) = 3 and the outer for loop has no bearing on inner for loop.
Where you have $array = mysqli_fetch_assoc($res);, you will only receive one row from your database. You need something like:
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
}
Any basic tutorial will tell you this. Even the PHP docs provide an example.
you can use do something like this..
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
e.g
echo $row['id'];
echo $row['name'];
etc
}
try this... this peace of code is not tested but just to give you an idea...
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
echo "<table>";
echo '<tr><td> id = "'.$row['id'].'":
</td><td> name = "'.$row['name'].'"</td></tr>";
echo "</table>";
}

Categories