MYsql in a HTML table. Delete row - php

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
}

Related

How to use database table header for html <th> table header tag

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>";

Displaying all records in a mysql 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
?>

Displaying Mysql data using PHP gives me a blank page

I am trying to display a table containing data from my db in a php page.
No problems at all.
When I try to use css to make the table better looking the browser gives me simply a blank page.
Here's my code...
If I delete the id=csstest part after opening the table tag everything works, as soon as I add id=csstest I get a blank page...
What am I doing wrong?
<?php
include 'config.php';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to db");
if (!mysql_select_db($database))
die("Can't select db");
// sending query
$result = mysql_query("SELECT data, cur_timestamp FROM {$table}");
if (!$result) {
die("Check your SQL query");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Tabella: {$table}</h1>";
echo "<table id="csstest"><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);
mysql_close($result);
?>
</table>
Change the following statement:
echo "<table id="csstest"><tr>";
to this:
echo "<table id=\"csstest\"><tr>";
you need to add slashes before your double quotes:
echo "<table id=\"csstest\"><tr>";
echo "<table id="csstest"><tr>";
above code generates parse error and your error reporting is off so it just showing blank page
try on of the below method
echo "<table id='csstest'><tr>";
echo '<table id="csstest"><tr>';
echo "<table id=\"csstest\"><tr>";

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>';
}

Updating multiple SQL records using a single submit button

Scenario: I have multiple text boxes in which a user will enter data into some of them / all of them / or none of them.
Goal: I need to be able to UPDATE multiple records based on what is in the text boxes where the users has entered their data.
Problem: The update statement is not working when I try to update each record for each text box.
Below is the code:
$conn = mysql_connect ($localhost, $user, $pass);
mysql_select_db($db_name, $conn) or die (mysql_error());
$myFile = "/var/www/html/JG/LSP/lsp_ref.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
if (isset($_POST['submit'])) {
foreach ($_POST['notes'] as $key=>$value) {
echo $_POST['notes'][$key];
#echo "<br/>";
//echo "$key";
//echo "<br/>";
$query_update = "UPDATE lsp_active SET Notes = ".$_POST['notes'][$key];
$result_update = mysql_query($query_update);
}
#header ('Location:lsp_display.php');
}
$query = "SELECT * FROM lsp_active";
$result = mysql_query($query);
$field_num = mysql_num_fields($result);
echo "<form method='post' action='lsp_display.php'>";
echo "<table border=1>";
$cols = 0;
while ($row = mysql_fetch_assoc($result)) {
if ( $cols == 0) {
$cols = 1;
echo "<tr>";
foreach ($row as $col => $value) {
print "<th>$col</th>";
}
print "<th>Insert Ticket / Notes</th>";
echo "</tr>";
}
echo "<tr>";
foreach ($row as $cell) {
echo "<td>$cell</td>";
}
echo "<td><input type='text' name='notes[]'/></td>";
echo "</tr>\n";
}
echo "<tr><td colspan=8><input type='submit' name='submit' value='Update'/></td></tr>";
echo "</form>";
mysql_free_result($result);
?>
Now when I print out $_POST['notes'][$key] it spits back out what I give it in the text boxes.
However, the update statement that I have for my SQL isn't updating the database with what I put in.
I am not sure what could be wrong with it :(.
Any help is appreciated!
Thank you!
It looks like you probably need to surround your $_POST in single quotes.
Also use a function to clean the $_POST variable.
For example:
function escape($data) {
$magicQuotes = get_magic_quotes_gpc();
if(function_exists('mysql_real_escape_string')) {
if($magicQuotes) {
$data = stripslashes($data);
}
$data = mysql_real_escape_string($data);
}
else {
if(!$magicQuotes) {
$data = addslashes($data);
}
}
return $data;
}
And then your query:
$query_update = "UPDATE lsp_active SET Notes = '" . escape($_POST['notes'][$key]) . "'";
Edit:
You also might want to put a WHERE statement on the end of your UPDATE query, so that you don't update everything in the table.
"UPDATE lsp_active a SET a.Notes = '" . mysql_real_escape_string($_POST['notes'][$key]) ."' WHERE a.Index = '" . ($key + 1). "'"
Index is a keyword thar refers to indexes, not your column. So I defined an alias, and made it explicit that Im referring to the column. Also, the + 1 on the Where $key since Index is not zero-based like PHP arrays.

Categories