save values from editable table using php - php

Hi I have a table generated from php, it is editable, I want to save edited values to database. I have no Idea how can I do this as there are many rows(dynamic) on a page.
Here is a screen-shot:-
Please suggest
Edit:-
My code is
echo "<table border='1'>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>";
while($row = $result->fetch_assoc())
{
echo "<tr contenteditable>";
echo "<td>" . $row["Row Number"]. "</td>";
echo "<td>" . $row["Product Id"]. "</td>";
echo "<td>" . $row["Product Name"]. "</td>";
echo "<td>" . $row["Product Catagory"]. "</td>";
echo "<td>" . $row["Retal Price"]. "</td>";
echo "<td>" . $row["Max Price"]. "</td>";
echo "<td>" . $row["Min Price"]."</td>";
echo "<td>" . $row["Initial Stock"]."</td>";
echo "<td>" . $row["Quantity Sold"]. "</td>";
echo "<td>" . $row["Current Stock"]."</td>";
echo "<td>" . $row["Last Order"]."</td>";
echo "<td contenteditable = 'false'><button href = '#'>Update</a></td>";
echo "</tr>";
}

Let me give you with the best way
First your database tables have spaces: correct that e.g.
from $row["Initial Stock"] to $row["Initial_Stock"]
Then i will propose you use ajax instead of wasting time clicking buttons
The HTML Page
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script>
$(function(){
$("#loading").hide();
//acknowledgement message
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('update.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},1000);
}
});
});
});
</script>
<style>
table.zebra-style {
font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
text-align:left;
border:1px solid #ccc;
margin-bottom:25px;
width:100%
}
table.zebra-style th {
color: #444;
font-size: 13px;
font-weight: normal;
padding: 5px 4px;
}
table.zebra-style td {
color: #777;
padding: 4px;
font-size:13px;
}
table.zebra-style tr.odd {
background:#f2f2f2;
}
#status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
#loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
</style>
<div id="status"> </div>
<div id="loading"></div>
<table id="tableID" border="0" class="sortable table zebra-style">
<thead>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>
</thead>
<tbody class="list">
<?php do { ?>
<tr>
<td contenteditable="true" id="Row_Number:<?php echo $row["Row_Number"]; ?>"><?php echo $row["Row_Number"]; ?></td>
<td contenteditable="true" id="Product_Id:<?php echo $row["Product_Id"]; ?>"><?php echo $row["Product_Id"]; ?></td>
<td contenteditable="true" id="Product_Name:<?php echo $row["Product_Name"]; ?>"><?php echo $row["Product_Name"]; ?></td>
<td contenteditable="true" id="Product_Catagory:<?php echo $row["Product Id"]; ?>"><?php echo $row["Product_Catagory"]; ?></td>
<td contenteditable="true" id="Retal_Price:<?php echo $row["Retal_Price"]; ?>"><?php echo $row["Retal_Price"]; ?></td>
<td contenteditable="true" id="Max_Price:<?php echo $row["Max_Price"]; ?>"><?php echo $row["Max_Price"]; ?></td>
<td contenteditable="true" id="Min_Price:<?php echo $row["Min_Price"]; ?>"><?php echo $row["Min_Price"]; ?></td>
<td contenteditable="true" id="Initial_Stock:<?php echo $row["Initial_Stock"]; ?>"><?php echo $row["Initial_Stock"]; ?></td>
<td contenteditable="true" id="Quantity_Sold:<?php echo $row["Quantity_Sold"]; ?>"><?php echo $row["Quantity_Sold"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable = 'false'></td>";
</tr>
<?php } while($row = $result->fetch_assoc()) ?>
</tbody>
</table>
And the update php page
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8',
'username',
'password',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
?>
<?php
if(!empty($_POST))
{
//database settings
foreach($_POST as $field_name => $val)
{
//clean post values
$field_id = strip_tags(trim($field_name));
//from the fieldname:user_id we need to get user_id
$split_data = explode(':', $field_id);
$product_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($product_id) && !empty($field_name) && !empty($val))
{
$affected_rows = $db->exec("UPDATE yourtable SET $field_name = '$val' WHERE product_ID = $product_id");
echo $affected_rows;
echo "Updated";
} else {
echo "Invalid Requests";
}
}
}
else {
echo "Invalid Requests";
}
?>

To save the whole table, you could leave the row-level update buttons out, and have a single save button:
<button id="save">Save</button>
<div id="msg"></div>
The msg area is to display feed-back from the server when the save-operation is performed.
Then you would add this JavaScript to handle the click of the save button:
$('#save').click(function() {
var data = [];
$('td').each(function() {
var row = this.parentElement.rowIndex - 1; // excluding heading
while (row >= data.length) {
data.push([]);
}
data[row].push($(this).text());
});
$.post('savetable.php', {table: data}, function (msg) {
$('#msg').text(msg);
});
});
This will transform the HTML table contents, without header row, to a JavaScript matrix, which then is sent to savetable.php for processing.
In PHP you would then use $_POST['table'] to access that array. When you implement this, first debug, and do a var_dump($_POST['table']) to make sure the data was transferred correctly, and it has the array structure you expect.
Then loop over that array to insert the rows into your database. You can use mysqli or PDO for this.
The PHP script savetable.php should only echo one message: a confirmation ("the table was saved successfully") or an error message ("a problem occurred. Your data was not saved.").
It should not reproduce the HTML of the table, since that is already displayed in the browser. Whatever PHP prints will be used by the JavaScript code to be displayed below the save button.
Here is how savetable.php could look like. But please debug carefully, I did not test this code. And before it works, you first need to set up your database model of course:
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4',
'username', 'password');
// Configure that all database errors result in an exception:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// Make a transaction: this allows to rollback any of the changes
// if anything goes wrong before the end of it.
$db->beginTransaction();
// First delete all rows.
$db->exec("DELETE FROM mytable");
// Prepare a statement that will be executed for each row.
// Needs to be extended for all columns:
$stmt = $db->prepare("INSERT INTO mytable (sl_num, product_id, product_name)
VALUES (?, ?, ?)");
foreach ($_POST('table'] as $row) {
$stmt->execute($row); // the columns are passed to the prepared statement.
}
// All went well: commit the changes.
$db->commit();
echo "Table saved successfully";
} catch(PDOException $e) {
// Something went wrong: roll back any changes made
$db->rollback();
echo "An error occurred: " . $e->getMessage();
}

What you can do is ajax call to a php with the id of the row you want to save and the new data. Then use PDO to connect to the database and update the information. After that is done, use javascript to edit the table itself.
So what you need to do is look up how to use ajax calls and use PDO. I suggest when you echo the table itself
<button href = '#' onclick="updateRow('. $row['Row Number'] .')">Update</a></td> where Row Number is the ID in the database and updateRow() is the javascript function you will create to get the new information and send it via ajax. Don't use mysql_*, because it is not supported in php 7 and it will die soon. Look up PDO instead.

Related

How can I edit the rows of data in a table using data from a database?

How can I format and style the rows of data in this table where it's displaying my data?
<table class="table">
<tr bgcolor=" #b366ff">
<th>Game</th>
<th>Date</th>
<th>Score</th>
<th>Venue</th>
</tr>
<?php
$sql = "SELECT * FROM game WHERE username = '{$users}' AND savename = '{$saves}';";
$result = mysqli_query($connection, $sql);
?>
<?php
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['team']."</td>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['score']."</td>";
echo "<td>".$row['venue']."</td>";
echo "</tr>";
}
?>
using a CSS class?
<style>
.tr1{background-color:#333;}
.td1{background-color:#999;}
</style>
echo "<tr class="tr1">";
echo "<td class="td1">".$row['team']."</td>";
You can do same as you do in normal HTML, you can use
.table tr{
background-color: grey;
}
Also you can use nth child selecter to style the elements.

Building an edit/update database form - adding column

I am working on an update database record form. The data is fetched from db table and populated into an html table on the webpage. I am stuck now how to add another column (5th) in the table that will contains 'edit' href link for updating database script.
Like:
|Col1|Col2|Col3|Col4|Edit|
| -- | -- | -- | -- |href|
I know this is very basic question, but so far I am not able to solve it.
It will be very helpful if someone can help me to work it.
Here is my code:
<div id="update" class="col mb-4">
<?php
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid grey;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
echo "<table class='table-bordered'>";
echo "<thead class='table-dark'>";
echo "<tr><th>Col1</th><th>Col2<th>Col3</th><th>xCol4</th></tr>";
echo "</thead>";
echo "<tbody>";
try {
$stmt = $conn->prepare("SELECT Col1, Col2, Col3, Col14 FROM table");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// $conn = null;
echo "</tbody>";
echo "</table>";
?>
</div>
Your code is very overcomplicated, which is what's making it hard to modify.
It seems like you just want to do a simple table with data from a database. You could basically just do:
<div id="update" class="col mb-4">
<table class='table-bordered'>
<thead class='table-dark'>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $conn->prepare("SELECT Col1, Col2, Col3, Col14 FROM table");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $row) {
?>
<tr>
<td style='width:150px;border:1px solid grey;'><?= $row['Col1'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col2'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col3'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col4'] ?></td>
<td style='width:150px;border:1px solid grey;'>Edit</td>
</tr>
<?php
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</tbody>
</table>
</div>
I would also recommending moving the database query away from the view into a class or something. Then the view would be much cleaner (no try/catch etc). Then all the PHP in the view would be something like:
<?php foreach ($myClass->getTheData() as $row) : ?>
<tr>
<td style='width:150px;border:1px solid grey;'><?= $row['Col1'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col2'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col3'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col4'] ?></td>
<td style='width:150px;border:1px solid grey;'>Edit</td>
</tr>
<?php endforeach ?>
Now it would be much easier to change the HTML.

Dynamic PHP Table Filter and Sort

I've written a bit of CSS and PHP to query a MySQL table. I also have a filter in the form of a drop down box which allows the user to choose a 'family', whether it be "capacitor", "resistor", or "ferrite bead" (I've included pictures below of what this looks like).
My question is this: how can I create a sorting system for the elements once they have been filtered by family? That is, if I wanted to query the table from MySQL corresponding to ASC values of "voltage" for example, how would I go about this? I need to retain the filter when the sorting method is selected. I have included my code so far below the images. Thanks for the help!
(Below: 1, full table is loaded : 2, only family entries that match "capacitor" are loaded)
CODE: (File name, index.php)
<html>
<form action="index.php" method="post">
<select name="family">
<option value="" selected="selected">Any family</option>
<option value="capacitor">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
<input name="search" type="submit" value="Search"/>
</form>
<head>
<meta charset = "UTF-8">
<title>test.php</title>
<style>
table {
border-collapse: collapse;
width: 50%;
}
th, td {
input: "text";
text-align: left;
padding: 8px;
}
th {
background-color: SkyBlue;
}
tr:nth-child(odd) {background-color: #f2f2f2;}
tr:hover {background-color: AliceBlue;}
</style>
</head>
<body>
<p>
<?php
$family = "";
if(isset($_POST['family'])) {
$family = $_POST['family'];
}
try {
$con= new PDO('mysql:host=localhost;dbname=mysql', "root", "kelly188");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(!empty($family)) {
$query = 'SELECT * FROM testv2 WHERE family = "'.$family.'"';
}
else {
$query = "SELECT * FROM testv2";
}
//first pass just gets the column names
print "<table>";
$result = $con->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
}
// end foreach
print " </tr>";
//second query gets the data
$data = $con->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} //end field loop
print " </tr>";
} //end record loop
print "</table>";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
?>
</p>
</body>
</html>
Datatables https://datatables.net/ is really cool too. The normal functioning is using JavaScript, but you can configure it to use server resources and process the date on server and just display the results. Once you get the hang of it it's pretty easy.
Each time you either order or filter the data, datatable sends an array with all the info necessary so you just scan the array and generate your queries accordingly.
You can add a sorting dropdown list in your form and use it in your query. This way you can let the user choose a sorting method and handle it server-side.
<form action="index.php" method="post">
<select name="family">
<option value="" selected="selected">Any family</option>
<option value="capacitor">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
<select name="sort">
<option value="" selected="selected">Any Order</option>
<option value="ASC">Ascending</option>
<option value="DESC">Descending</option>
</select>
<input name="search" type="submit" value="Search"/>
</form>
In PHP:
<?php
$family = "";
$sort = "";
if(isset($_POST['family'])) {
$family = $_POST['family'];
}
In your if Statement:
if(!empty($family)) {
$query = 'SELECT * FROM testv2 WHERE family = "'.$family.'" ORDER BY "'.$sort'"';
}
else {
$query = "SELECT * FROM testv2";
}
If you don't want to use a dedicated table sorting library, you should be able to do this yourself. Here is a solution that pulls all data from a provided array of data which you should be able to provide easily using PHP.
// Initially populate the table
populateTable(data);
// Listen for a click on a sort button
$('.sort').on('click', function() {
// Get the key based on the value of the button
var key = $(this).html();
// Sort the data and update our data
data = sortBy(data, key);
// Fill the table with our data
populateTable(data);
});
// Modified from: https://www.sitepoint.com/sort-array-index/
function sortBy(inputData, key) {
// Sort our data based on the given key
inputData.sort(function(a, b) {
var aVal = a[key],
bVal = b[key];
if (aVal == bVal) return 0;
return aVal > bVal ? 1 : -1;
});
return inputData;
}
// Modified from: https://stackoverflow.com/questions/5361810/fast-way-to-dynamically-fill-table-with-data-from-json-in-javascript
function populateTable(inputData) {
var keys = new Array(),
i = -1;
// Create an array of keys
$.each(inputData[0], function(key, value) {
keys[++i] = key;
});
var r = new Array(),
j = -1;
// Populate the table headers
r[++j] = '<tr>';
$.each(keys, function(key, value) {
r[++j] = '<th>' + keys[key] + '</th>';
});
r[++j] = '</tr>';
for (var index = 0, size = inputData.length; index < size; index++) {
// Populate the table values
r[++j] = '<tr>';
$.each(keys, function(key, value) {
r[++j] = '<td>' + inputData[index][value] + '</td>';
});
r[++j] = '</tr>';
}
// Join everything together
$('#data-table').html(r.join(''));
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
text-align: left;
padding: 8px;
}
th {
background-color: skyblue;
}
tr:nth-child(odd) {
background-color: #f2f2f2;
}
tr:hover {
background-color: aliceblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// Set our data
var data = [{
ID: 1,
Family: 'resistor',
Capacitance: 7,
Voltage: 6,
Price: 25.6
},
{
ID: 2,
Family: 'capacitor',
Capacitance: 10,
Voltage: 10,
Price: 100.2
},
{
ID: 3,
Family: 'ferrite bead',
Capacitance: 1,
Voltage: 5,
Price: 35.6
},
{
ID: 4,
Family: 'resistor',
Capacitance: 1,
Voltage: 4,
Price: 35.6
},
{
ID: 5,
Family: 'capacitor',
Capacitance: 9,
Voltage: 4,
Price: 25.6
}
];
</script>
<table id="data-table"></table>
<p>Sort by:</p>
<button class="sort">ID</button>
<button class="sort">Family</button>
<button class="sort">Capacitance</button>
<button class="sort">Voltage</button>
<button class="sort">Price</button>
You could keep the $_POST['family'] in a hidden field (maybe $_POST['hidden_family']). When you do your next level search you can check for it and append that to your search each time if it is not blank.
Here's how you numerically sort your table :
1) give the intended table an ID (in my code case it's main-table)
2) Call the sorting function everytime you click on the table headers (including the column number, first one is 0, everytime you add more columns increase the number inside the function name by one, in this case sortTable(0),sortTable(1),....
The final result will be something like this (test this example, it works):
<table id="main-table">
<tr>
<th style="cursor:pointer" onclick="sortTable(0)">colomn 0</th>
<th style="cursor:pointer" onclick="sortTable(1)">colomn 1</th>
<th style="cursor:pointer" onclick="sortTable(2)">colomn 2</th>
<th style="cursor:pointer" onclick="sortTable(3)">colomn 3</th>
<th style="cursor:pointer" onclick="sortTable(4)">colomn 4</th>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
</table>
<script>
function sortTable(column) {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("main-table");
switching = true;
while (switching) {
switching = false;
rows = table.getElementsByTagName("TR");
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[column];
y = rows[i + 1].getElementsByTagName("TD")[column];
if (Number(x.innerHTML) > Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
</script>
And here's what you need to do to generate the number of the column :
$counter = 0;
foreach ($row as $field => $value){
print " <th onclick='sortTable($counter)'>$field</th>";
$counter = $counter+1;
}

Insert mysql table into a div

I have a problem in inserting table from my database to div.
html code:
<div class="content">
<?php
$query = "SELECT name, surname FROM players";
$response = #mysqli_query($dbc, $query);
if($response) {
echo' <table align="left"
cellspacing="5" cellpadding="8" >
<tr><td align="left"><b>First Name</b></td>
<td align="left"><b>Last Name</b></td></tr>';
while($row = mysqli_fetch_array($response)) {
echo '<tr><td align="left">' .
$row['imie'] . '</td><td align="left">' .
$row['nazwisko'] . '</td><td align="left">';
echo '</tr>';
}
echo '</table>';
} else {
echo "Couldn't issue database query";
echo mysqli_error($dbc);
}
mysqli_close($dbc);
?>
</div>
css code:
.content {
width: 1000px;
margin-left: auto;
margin-right: auto;
background-color: #ffffff;
color: #000000;
border-bottom: 14px solid #333333;}
Is there a way to insert this table to this div? Because when I'm loading this, the table is under my div'content'. The table should be in blank field 'a'.
Screenshot
Correctly indenting your code would have allowed you o spot the error relatively easily - there is an open td element. Either remove the last td from the echo statement in the loop or add additional td pair to first row in table so that they balance ( unless you use colspan attributes )
<style>
.content table tr td{ align:left;padding:5px;color:black;background:white; }
</style>
<div class='content'>
<?php
$sql = 'select `name`, `surname` from `players`';
$response = mysqli_query( $dbc, $sql );
if( $response ) {
echo "
<table align='left' cellspacing='5' cellpadding='8' >
<tr>
<td><b>First Name</b></td>
<td><b>Last Name</b></td>
</tr>";
while( $row = mysqli_fetch_array( $response ) ) {
echo "
<tr>
<td>{$row['imie']}</td>
<td>{$row['nazwisko']}</td>
</tr>";
}
echo "
</table>";
} else {
printf( 'Couldn\'t issue database query: %s', mysqli_error( $dbc ) );
}
mysqli_close( $dbc );
?>
</div>
There is an open <td> tag in your code you should close it before closing the <tr>

MYSQL Select query for displaying data on a table is not working

I want to display the data loaded from database after it is inserted using the function add_data() but it's not displaying the data on the table.
if(isset($_POST['btn_add_details'])) {
add_data();
include("db_PSIS.php");
$sql2="SELECT * FROM sample_barcode WHERE IDRec='".$row['IDRec']."'";
$result2=mysql_query($sql2);
if(!$result2) {
echo "<h1>Could not process query this time. Please try again later!</h1>";
}
else {
while($row2=mysql_fetch_array($result2)) {
echo "<form name='form2' method='POST'>";
echo "<table class='output' border=2 align=center>";
echo "<tr class='thcolor'>";
echo "<th>Parent</th>";
echo "<th>LOT Traveller No.</th>";
echo "<th>Datecode</th>";
echo "</tr>";
echo "<tr>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['Datecode']."</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
echo "<br><h1>Data successfully loaded!</h1>";
}
mysql_close($link);
}
?>
Here's the function for adding data on the database:
function add_data() {
include("db_PSIS.php");
$sql="INSERT INTO sample_barcode (LotTraveller, ShipmentLotNumber) VALUES ('".$_POST['traveller']."', '".$_POST['datecode']."')";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
mysql_close($link);
}
Here's the code for database connection:
<?php
$username="****";
$password="****";
$database="****";
$hostname="****";
$link=#mysql_connect($hostname,$username,$password)
or die ("...cannot connect database, using $username for $hostname");
mysql_query("set names 'utf8'"); //指定数据库字符集
mysql_select_db($database,$link);
?>
Here's the form input:
<table width="500" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<tr>
<th align="right">Parent Traveller: </th>
<td><input type="text" name="traveller" size="20" value="<?php if(empty($_POST['traveller'])) {echo ''; } else { echo $row2['LotTraveller']; } ?>"/></td>
</tr>
<tr>
<th align="right">Date Code: </th>
<td><input type="text" name="datecode" size="20" value="<?php if(empty($_POST['traveller'])) {echo ''; } else { echo $row2['ShipmentLotNumber']; } ?>" /></td>
</tr>
<tr>
<th align="right">Traveller 1: </th>
<td><input type="text" name="traveller1" size="20" /></td>
</tr>
<tr>
<th align="right">Date Code: </th>
<td><input type="text" name="datecode1" size="20" /></td>
</tr>
<tr>
<th align="right">Traveller 2: </th>
<td><input type="text" name="traveller2" size="20" /></td>
</tr>
<tr>
<th align="right">Date Code: </th>
<td><input type="text" name="datecode2" size="20" /></td>
</tr>
<tr>
<th align="right"> </th>
<td><input type="hidden" name="id" size="20" value="<?php if(empty($_POST['traveller'])) {echo ''; } else {echo $row2['IDRec'];} ?>"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btn_add_details" id="btn_add_details" onClick="return check_submit();" value="Add the Detail(s)" onfocus="setStyle(this.id)"
style="color: #000000;
padding: 2px 5px;
border: 2px solid;
border-color: #7bf #07c #07c #4AA02C;
background-color: #09f;
font-family: Georgia, ..., serif;
font-size: 18px;
display: block;
height: 30px;
width: 200px;" /> </td>
</tr>
</table>
Since you stated that IDRec is your PK and is set to auto-increment, AND you are pulling records based on a single number... you will never get more than one result in your resultset.
Change this code block...
$sql2="SELECT * FROM sample_barcode WHERE IDRec='".$row['IDRec']."'";
$result2=mysql_query($sql2);
if(!$result2) {
echo "<h1>Could not process query this time. Please try again later!</h1>";
}
else {
while($row2=mysql_fetch_array($result2)) {
echo "<form name='form2' method='POST'>";
echo "<table class='output' border=2 align=center>";
echo "<tr class='thcolor'>";
echo "<th>Parent</th>";
echo "<th>LOT Traveller No.</th>";
echo "<th>Datecode</th>";
echo "</tr>";
echo "<tr>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['Datecode']."</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
echo "<br><h1>Data successfully loaded!</h1>";
}
mysql_close($link);
}
To this...
$sql2="SELECT * FROM sample_barcode WHERE IDRec=".$row['IDRec']."";
$result2=mysql_query($sql2);
$row2=mysql_fetch_assoc($result2); // added this line
if(!$result2) {
echo "<h1>Could not process query this time. Please try again later!</h1>";
}
else {
echo "<form name='form2' method='POST'>";
echo "<table class='output' border=2 align=center>";
echo "<tr class='thcolor'>";
echo "<th>Parent</th>";
echo "<th>LOT Traveller No.</th>";
echo "<th>Datecode</th>";
echo "</tr>";
echo "<tr>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['Datecode']."</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
echo "<br><h1>Data successfully loaded!</h1>";
}
mysql_close($link);
}
In the first line I removed the single quotes around your IDRec - this is an integer so single quotes are not needed.
Removed your while loop - you will only ever get one result so a loop is not needed.
Also, this doesn't appear to actually be a form so you can also remove your <form> </form> tags.
Finally, start learning pdo_mysql. my_sql has been deprecated. Anyone still using this code will wake up one day to find out that their website has magically stopped functioning.
EDIT
In your add_data function, change it to this...
function add_data() {
include("db_PSIS.php");
$sql="INSERT INTO sample_barcode (LotTraveller, ShipmentLotNumber) VALUES ('".$_POST['traveller']."', '".$_POST['datecode']."')";
$result=mysql_query($sql);
$sql="SELECT * FROM sample_barcode ORDER BY IDRec DESC"; // added this line
$result=mysql_query($sql); // added this line
$row=mysql_fetch_assoc($result); // changed this line from array to assoc
mysql_close($link);
}
This will get the result of the data you just entered. I added a query to get the data you need to display.

Categories