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>';
}
Related
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";
I'm new to PHP. I use the code (below) to print a MySQL table as an HTML table.
However my code prints the table headers from the database.
How can I print HTML table header in hard coded format using the <th>header</th> tags and print the all rows from the table?
Thanks!
<?php
$db_host = 'localhost';
$db_user = 'my user';
$db_pwd = 'my pwd';
$database = 'my db';
$table = 'subcontractor';
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 class='table table-bordered table-striped mb-none' id='datatable-tabletools' data-swf-path='assets/vendor/jquery-datatables/extras/TableTools/swf/copy_csv_xls_pdf.swf' >";
// printing table headers
echo "<thead>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<th>{$field->name}</th>";
}
echo "</thead>";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tbody>";
echo "<tr>";
echo "</thead>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>";
echo "</tbody>";
}
mysql_free_result($result);
?>
Thank you works perfect. Is there a way to make PHP skip a column from the table on the DB? Thanks –
Yes, just change the Query
$result = mysql_query("SELECT * FROM {$table}");
for example by
$result = mysql_query("SELECT `name`,`email`,`address` FROM {$table}");
You can change the headers by removing these lines of code.
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<th>{$field->name}</th>";
}
Replace the above lines for example by:
echo "<thead>";
echo "<th>My Header 1</th>";
echo "<th>My Header 2</th>";
echo "</thead>";
Back with another quick question. I have this code below which echo's out product names from a database. What I want to do is make the echoed out product names a link to another page called product.php, each link needs to have a unique ID, for example
Product Name
How would I go about doing this? Many thanks. I will point out that I am very new to PHP.
<?php
//create an ADO connection and open the database
$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\WebData\Northwind.mdb");
//execute an SQL statement and return a recordset
$rs = $conn->execute("SELECT product_name FROM Products");
$num_columns = $rs->Fields->Count();
echo "<table border='1'>";
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";
//close the recordset and the database connection
$rs->close();
$rs = null;
$conn->close();
$conn = null;
?>
Assuming your Products table has a unique ID field called "id", change your select to:
$rs = $conn->execute("SELECT id, product_name FROM Products");
And when you want to create a link, use that field and pass it into the URL. So you'd have product.php?id=<?= $thatIdField; ?>.
Example code:
echo "<table border='1'>";
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";
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
?>
I'm using PHP to display what is in my MYsql database in a table. I would like to add a delete button buy I don't know how. I would like the delete button right after the last column. Here is my code.
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';
$database = 'coins_gage';
$table = 'coins';
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 "<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";
}
mysql_free_result($result);
?>
You have to do several things here to make the interface user friendly and perform your task. If I summarize the steps you have to do is like this.
1) Make sure you keep your table inside a form with POST method. And add following kind of hidden elements just before close the FORM tag.
<input type="hidden" name="hidDelete" id="hidDelete" value="" />
2) Add a column header to the table by modifying this section.
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "<td>Delete</td>";
echo "</tr>\n";
3) Add the delete button to all the rows.
foreach($row as $cell)
echo "<td>$cell</td>";
echo "<td><input type=\"button\" value=\"Delete\" onclick=\"deleteThis({$field->id})\" /></td>"
echo "</tr>\n";
4) The create a javascript function to make the delete request. Before you post data you have to set a hidden value. If you use javascript library like jquery this will be much easier. Since I don't know which library you are using I will explain in pure javascript.
<script type="text/javascript">
function deleteThis(id)
{
document.getElementById("hidDelete").value = id;
document.yourFormName.submit();
}
</script>
5) Once you get the post request to your page, Make the deletion before you do select queries.
if(isset($_POST["hidDelete"]) $_POST["hidDelete"] != "")
{
$rowID = $_POST["hidDelete"];
// Write your delete queries
}