Displaying all records in a mysql table - php

The code below works fine for printing one record from a database table, but what I really want to be able to do is print all the records in the mysql table in a format similar to my code.
I.E.: Field Name as heading for each column in the html table and the entry below the heading. Hope this is making sense to someone ;)
$raw = mysql_query("SELECT * FROM tbl_gas_meters");
$allresults = mysql_fetch_array($raw);
$field = mysql_query("SELECT * FROM tbl_gas_meters");
$num_fields = mysql_num_fields($raw);
$num_rows = mysql_num_rows($raw);
$i = 1;
print "<table border=1>\n";
while ($i < $num_fields)
{
echo "<tr>";
echo "<b><td>" . mysql_field_name($field, $i) . "</td></b>";
//echo ": ";
echo '<td><font color ="red">' . $allresults[$i] . '</font></td>';
$i++;
echo "</tr>";
//echo "<br>";
}
print "</table>";

Just as an additional piece of information you should probably be using PDO. It has more features and is helpful in learning how to prepare SQL statements. It will also serve you much better if you ever write more complicated code.
http://www.php.net/manual/en/intro.pdo.php
This example uses objects rather then arrays. Doesn't necessarily matter, but it uses less characters so I like it. Difference do present themselves when you get deeper into objects, but not in this example.
//connection information
$user = "your_mysql_user";
$pass = "your_mysql_user_pass";
$dbh = new PDO('mysql:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
//prepare statement to query table
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
//loop over all table rows and fetch them as an object
while($result = $sth->fetch(PDO::FETCH_OBJ))
{
//print out the fruits name in this case.
print $result->name;
print("\n");
print $result->colour;
print("\n");
}
You probably also want to look into prepared statements. This helps against injection. Injection is bad for security reasons. Here is the page for that.
http://www.php.net/manual/en/pdostatement.bindparam.php
You probably should look into sanitizing your user input as well. Just a heads up and unrelated to your current situation.
Also to get all the field names with PDO try this
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
Once you have all the table fields it would be pretty easy using <div> or even a <table> to arrange them as you like using a <th>
Happy learning PHP. It is fun.

Thanks guys, got it.
$table = 'tbl_gas_meters';
$result = MYSQL_QUERY("SELECT * FROM {$table}");
$fields_num = MYSQL_NUM_FIELDS($result);
ECHO "<h1>Table: {$table}</h1>";
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>";
}
ECHO "</tr>\n";
// 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>\n";
}

while ( $row = mysql_fetch_array($field) ) {
echo $row['fieldname'];
//stuff
}

Try this :
$raw = mysql_query("SELECT * FROM tbl_gas_meters");
$allresults = mysql_fetch_array($raw);
$field = mysql_query("SELECT * FROM tbl_gas_meters");
while($row = mysql_fetch_assoc($field)){
echo $row['your field name here'];
}
Please note that, mysql_* functions are deprecated in new php version , so use mysqli or PDO instead.

Thanks! I adapted some of these answers to draw a table from all records from any table, without having to specify the field names. Just paste this into a .php file and change the connection info:
<?php
// Authentication detail for connection
$servername = "localhost";
$username = "xxxxxxxxxx";
$password = "xxxxxxxxxx";
$dbname = "xxxxxxxxxx";
$tablename = "xxxxxxxxxx";
$orderby = "1 DESC LIMIT 500"; // column # to sort & max # of records to display
// Create & check connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); // quit
}
// Run query & verify success
$sql = "SELECT * FROM {$tablename} ORDER BY {$orderby}";
if ($result = $conn->query($sql)) {
$conn->close(); // Close table
$fields_num = $result->field_count;
$count_rows = $result->num_rows;
if ($count_rows == 0) {
die ("No data found in table: [" . $tablename . "]" ); //quit
}
} else {
$conn->close(); // Close table
die ("Error running SQL:<br>" . $sql ); //quit
}
// Start drawing table
echo "<!DOCTYPE html><html><head><title>{$tablename}</title>";
echo "<style> table, th, td { border: 1px solid black; border-collapse: collapse; }</style></head>";
echo "<body><span style='font-size:18px'>Table: <strong>{$tablename}</strong></span><br>";
echo "<span style='font-size:10px'>({$count_rows} records, {$fields_num} fields)</span><br>";
echo "<br><span style='font-size:10px'><table><tr>";
// Print table Field Names
while ($finfo = $result->fetch_field()) {
echo "<td><center><strong>{$finfo->name}</strong></center></td>";
}
echo "</tr>"; // Finished Field Names
/* Loop through records in object array */
while ($row = $result->fetch_row()) {
echo "<tr>"; // start data row
for( $i = 0; $i<$fields_num; $i++ ) {
echo "<td>{$row[$i]}</td>";
}
echo "</tr>"; // end data row
}
echo "</table>"; // End table
$result->close(); // Free result set
?>

Related

PHP and MySQL WP

I am trying to accomplish two things here with this code. I am writing PHP directly into a WP page using the INSERT PHP Plugin.
1) Query the MySQL database and return the results from one column into four columns.
2) Make each result is its own hyperlink that directs the user to a new WP page that runs a new query on that page.
I am able to get the query to show results and even to turn those results into a dynamic hyperlink, however I cannot get the formatting down. Right now it just returns the result into one column. Here is what I have:
[insert_php]
$servername = "localhost";
$username = "login"; //edited for privacy
$password = "password"; //edited for privacy
$database = "database"; //edited for privacy
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//get results from database
$result = mysqli_query($conn,"SELECT mine FROM mines ORDER BY mine");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo "<td><a href='urlhere/$row[$item]'>".$row[$item]. "</a>"."</td>"; //get items using property value
}
echo '</tr>';
}
echo "</table>";
[/insert_php]
Thanks for any help you can offer.
I'd like the results to look like this (each one as a hyperlink):
Image link below
I was able to work this out. Still have not gotten the results to properly hyperlink but the array is filling in over four columns now. Here is my code:
$sql = "SELECT mine FROM mines ORDER by mine";
$result = mysqli_query($conn, $sql);
if ($result) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row['mine'];
}
}
if (is_array($data) && count($data)) { // if array's not empty, create HTML
//create a table & header row
$htmlout="<table><tr>
<th colspan='4'>Mine</th></tr>
<tr>
";
$counter = 1; //keep count of data
foreach ($data as $mines) {
//table cell for datum
$htmlout .= "<td>$mines</td>\n";
//rows of 4
if ($counter % 4 == 0) {
$htmlout .= "</tr>\n<tr>\n";
}
$counter++;
}
}
$htmlout .= "</tr></table>";
echo $htmlout;

want to print the selected column of sql table queried through html form

i want to print only selected columns from mysql table on website which are query through html form.
$column[] store the columns which user want to see on the web.
So how to select the particular columns from a mysql table.
inside the php file
<?php
# $db = new mysqli('localhost', 'user', 'passwd', 'myDatabase');
$column = $_POST['columns']; // column passed through html
$query = "select * from primers" ;
$result = $db->query($query);
$num_results = $result->num_rows;
for($i=0; $i<$fields_num; $i++)
{
$field = mysqli_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
?>
now in place of * i want to select the column name which are specified in $column array.
Help me.Thank you
Try something like this:
$query = "select " . (empty($column) ? '*' : implode(', ', $column)) . " from primers";

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 help displaying mysql database contents to webpage

I need help displaying data from mysql to a webpage, I am coding in php.
My database consists of products which are cars(same type e.g Chevy), right now I have 2 rows (I can add more if I want to), each cars contains the image path, and description.
I can show one row (car) but I am unable to show all rows. I know I have to go through a loop to get all the data from the cars database but I am not sure how to implement it.
This is what I have so far. Assuming I already connected to my database
note: the image path I would like to show the picture in my website.
This is how i would like it to display in my webpage:
$query = "SELECT * FROM cars where cars.carType = 'Chevy' AND \
cars.active = 1";
$numberOfFieds = mysqli_num_fields($result);
$numberOfRows = mysqli_num_rows($result);
/* Gets the contents */
$row = mysqli_fetch_row($result);
$rows = mysqli_fetch_assoc($result);
$fieldcarssontable = array_keys($row);
echo "<table>";
while($row = mysqli_fetch_assoc($result)){
echo "<th>" . $fieldcarssontable[imgPath] . "</th>";
echo "<th>" . $fieldcarssontable[description] . "</th>";
}
echo "</tr>";
echo "</table>";
Just add a while loop. mysqli_fetch_assoc returns a row and moves the internal pointer to the next row until all rows are fetched, then it returns false and the while loop will stop
Pseudo syntax to understand while
while ( this is true ) {
execute this
}
So on your case you can say
while ( $row = mysqli_fetch_assoc( $result ) ) {
// process/output $row
}
mysqli_fetch_assoc and mysqli_fetch_row literally do the same, assoc gives you the array with your result field names as index so this is simpler to access ( $row['name'] rather than $row[0] when using fetch_row )
Have fun! :)
EDIT
// connect to your database server
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
// an error occured
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
// build your query
$query = "SELECT
* # select actual fields instead of *
FROM
cars
WHERE
cars.carType = 'Chevy'
AND
cars.active = 1";
// execute query
$result = mysqli_query($link, $query );
if ( !$result ) {
die( 'no result' );
}
// number of fields
$numberOfFields = mysqli_num_fields($result);
// the field names
$fieldNames = mysqli_fetch_fields($result);
// number of result rows
$numberOfRows = mysqli_num_rows($result);
// watch the content of fieldName and compare it with the table header in the output
print_r( $fieldName );
echo "<table>\n";
// table header, not neccessary to put this into a loop if the query isn't dynamic
// so you actually know your field names - you can echo the header without any variable.
// for the sake of learning about loops I added this
foreach( $fieldNames as $index => $fieldName ) {
echo "\t<th>field #" $index . ", name:" . $fieldName . "</th>\n";
}
// now it's time to walk through your result rows, since we only need to check for "true" a while loop does best
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo "\t<tr><td>" . $row['imgPath'] . "</td><td>" . $row['description'] . "</td></tr>\n";
}
echo "</table>\n";
// remove the result from memory
mysqli_free_result( $result );
mysqli_close( $link );
You misspelled $numberOfFields in your loop, which means you're using a different variable for your loop control. Your loop won't work.
I recommend turning on the error reporting so PHP can catch this stuff for you.
Use this... just while loop
<?php
// Array
while($result = mysql_fetch_assoc($result)) {
//show you fields
echo $result["FieldName"];
}
?>
Or use this proper
<?php
// Edit it as per your query
$query = "SELECT * FROM cars";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while($row = $result->fetch_assoc()) {
//show you fields
echo $row["Name"];
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>

Displaying mysql table with php

I'm having trouble displaying my mysql table using php code. All it displays is the column names not the values associated with them. I know my username password and db are all correct but like I said the table is not displaying the values I added. Any help would be much appreciated This is my mysql code:
CREATE TABLE Guitars
(
Brand varchar(20) NOT NULL,
Model varchar(20) NOT NULL,
PRIMARY KEY(Brand)
);
insert into Guitars values('Ibanez','RG');
insert into Guitars values('Ibanez','S');
insert into Guitars values('Gibson','Les Paul');
insert into Guitars values('Gibson','Explorer');
And this is my php code:
<?php
$db_host = '*****';
$db_user = '*****';
$db_pwd = '*****';
$database = '*****';
$table = 'Guitars';
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 "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// 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>\n";
}
mysql_free_result($result);
?>
Try this:
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
echo "<td>$row[0]</td>";
echo "<td>$row[1]</td>";
echo "</tr>\n";
}
Update:
Note: You can't make brand as primary key since you gonna add same brand name for different models.
I don't see why you are using the fetch_field call. I'm assuming that you know ahead of time what the actual names of each field in your table is prior to calling it's data? I think for simplicity sake (less loops and nested loops) you should write the name of the fields manually, then loop through the data entering the values.
$feedback .= "<table border='1'><tr>";
$feedback .= "<th>Brand</th><th>Model</th></tr>";
while ($row = mysql_fetch_array($result)) {
$feedback .= "<tr><td>" . $row['Brand'] . "</td>";
$feedback .= "<td>" . $row['Model'] . "</td></tr>";
}
$feedback .= "</table>";
echo $feedback;
By the time you're done displaying the header, the query result's internal pointer will have reached the last row, so your mysql_fetch_row() calls fail because there are no more rows to fetch. Call mysql_data_seek(0); before printing the table rows, to move the internal pointer back to the first row.
You can also try for fetching data
while ($fielddata = mysql_fetch_array($result))
{
echo '<tr>';
for ($i = 0; $i<$fields_num; $i++) // $fields_num already exists in your code
{
$field = mysql_fetch_field($result, $i);
echo '<td>' . $fielddata[$field->name] . '</td>';
}
echo '</tr>';
}

Categories