I have a form that displays the results from a survey into a webpage. At the moment, when a user clicks on the 'View Here' it takes them to the individual entry for that ID. When it is clicked I would like it to also show additional results (also part of the results from the same database).
Any idea how I do this? Just to clarify, it should not show until the ID is clicked to single out that entry - otherwise it shows them all in full one after the other.
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=***', '***', '***');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
class guestquestionnaireEntry {
public $id, $date_submitted,
$entry;
public function __construct()
{
$this->entry = "
<table border='1' align='center'>
<tr class='tablelist' style='font-size: 8pt;' ><td width='5%' colspan='2'>{$this->ID}</td><td width='40%' colspan='2'><b>Date Received: </b>{$this->date_submitted}</td><td width='45%' colspan='2'>{$this->name}</td><td width='10%'>View here </td></tr>
</table>
";
}
}
SELECT DATE_FORMAT(date_submitted, '%m/%d/%Y') AS date_submitted FROM guestquestionnaire
// Checks if the submitted is a number. If so, isolates the ID and adds "where" clause
$id = (!empty($_GET['ID']) && is_numeric($_GET['ID']))? " where ID = '".$_GET['ID']."'" : "";
// Add the $id to the end of the string
// A single call would be SELECT * FROM guestquestionnaire where ID = '1'
$query = $handler->query("SELECT * FROM guestquestionnaire{$id}");
$query->setFetchMode(PDO::FETCH_CLASS, 'guestquestionnaireEntry');
while($r = $query->fetch()) {
echo $r->entry, '<br>';
}
?>
Additional code that I would like to show once 'View Here' is clicked (so when the individual entry is shown):
class guestquestionnaireEntry {
public $id, $date_submitted, $choice, $expectations, $res, $res_information, $res_staff, $further_comments1,
$entry;
public function __construct()
{
$this->entry = "
<tr style='font-size: 8pt;'><td width='60%'>ID </td><td width='40%' colspan='2'>{$this->date_submitted}</td></tr>
<tr style='text-align: left; font:arial;'><td><h3>Date Submitted: {$this->date_submitted}</h3></td></tr>
<table border='1' align='center'>
<tr style='background: #566890; font-size: 8pt; font-weight: bold; color: #fff;'><td colspan='3'>Prior to Arrival</td></tr>
<tr style='font-size: 8pt;'><td width='60%'>What made you choose us for your recent trip? </td><td width='40%' colspan='2'>{$this->choice}</td></tr>
<tr style='font-size: 8pt;'><td>Did we meet your expectations as advertised? If no, please state why: </td><td width='40%' colspan='2'>{$this->expectations}</td></tr>
<tr style='background: #566890; font-size: 8pt; font-weight: bold; color: #fff;'><td colspan='3'>Making your Reservation</td></tr><BR>
<tr style='font-size: 8pt;'><td>Ease of making your reservation: </td><td width='40%'>$img</td><td width='5%'>{$this->res}</td></tr><BR>
<tr style='font-size: 8pt;'><td>Hotel information offered: </td><td width='40%'>$img2</td><td width='5%'>{$this->res_information}</td></tr><BR>
<tr style='font-size: 8pt;'><td>Warmth and friendliness of staff: </td><td width='40%'>$img3</td><td width='5%'>{$this->res_staff}</td></tr><BR>
<tr style='font-size: 8pt;'><td colspan='3'>Further Comments: </BR></BR>{$this->further_comments1}</td></tr>
<BR>
</table>
<BR>
<p>Back to List</p>
";
See if this works. I have not tested it, so make sure you save a copy of whatever you have so far. It requires database credentials to be filled out:
Classes:
<?php
interface Database
{
public static function SetConnection($host,$username,$password,$database);
}
interface Questionnaire
{
public function Display();
public function DisplaySingle();
}
class MySQLConn implements Database
{
protected static $host;
protected static $username;
protected static $password;
protected static $database;
public static $connect;
private function __construct()
{
}
public static function SetConnection($host = "***",$username = "***",$password = "***",$database = "***")
{
self::$host = $host;
self::$username = $username;
self::$password = $password;
self::$database = $database;
self::$connect = (!isset(self::$connect))? self::Initialize() : self::$connect;
}
private static function Initialize($use = 'PDO')
{
if($use == 'PDO') {
try {
$con = new PDO('mysql:host='.self::$host.';dbname='.self::$database, self::$username, self::$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $con;
}
catch (PDOException $e) {
die($e->getMessage());
}
}
else
return new mysqli(self::$host, self::$username, self::$password, self::$database);
}
}
class guestquestionnaireEntry implements Questionnaire
{
public $id,
$date_submitted,
$choice,
$expectations,
$res,
$res_information,
$res_staff,
$further_comments1,
$entry;
public function __construct()
{
if(empty($_GET['focus']))
$this->entry = $this->DisplaySingle();
else
$this->entry = $this->Display();
}
public function DisplaySingle()
{
ob_start(); ?>
<table border='1' align='center'>
<tr class='tablelist' style='font-size: 8pt;' >
<td width='5%' colspan='2'><?php echo $this->ID; ?></td>
<td width='40%' colspan='2'><b>Date Received: </b><?php echo $this->date_submitted; ?></td>
<td width='45%' colspan='2'><?php echo $this->name; ?></td>
<td width='10%'>View here</td>
</tr>
</table>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
public function Display()
{
ob_start(); ?>
<tr style='font-size: 8pt;'>
<td width='60%'>ID</td>
<td width='40%' colspan='2'><?php echo $this->date_submitted; ?></td>
</tr>
<tr style='text-align: left; font:arial;'>
<td><h3>Date Submitted: <?php echo $this->date_submitted; ?></h3></td>
</tr>
<table border='1' align='center'>
<tr style='background: #566890; font-size: 8pt; font-weight: bold; color: #fff;'>
<td colspan='3'>Prior to Arrival</td>
</tr>
<tr style='font-size: 8pt;'>
<td width='60%'>What made you choose us for your recent trip? </td>
<td width='40%' colspan='2'><?php echo $this->choice; ?></td>
</tr>
<tr style='font-size: 8pt;'>
<td>Did we meet your expectations as advertised? If no, please state why: </td>
<td width='40%' colspan='2'><?php echo $this->expectations; ?></td>
</tr>
<tr style='background: #566890; font-size: 8pt; font-weight: bold; color: #fff;'>
<td colspan='3'>Making your Reservation</td>
</tr>
<BR>
<tr style='font-size: 8pt;'>
<td>Ease of making your reservation: </td>
<td width='40%'>$img</td>
<td width='5%'><?php echo $this->res; ?></td>
</tr>
<BR>
<tr style='font-size: 8pt;'>
<td>Hotel information offered: </td>
<td width='40%'><?php echo $img2; ?></td>
<td width='5%'><?php echo $this->res_information; ?></td>
</tr>
<BR>
<tr style='font-size: 8pt;'>
<td>Warmth and friendliness of staff: </td>
<td width='40%'><?php echo $img3; ?></td>
<td width='5%'><?php echo $this->res_staff; ?></td>
</tr>
<BR>
<tr style='font-size: 8pt;'>
<td colspan='3'>Further Comments: </BR>
</BR>
<?php echo $this->further_comments1; ?></td>
</tr>
<BR>
</table>
<BR>
<p>Back to List</p>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
?>
To use:
<?php
//**********************************************************************************
// Add the classes here by way of include() or just pasted at the top of the page...
//**********************************************************************************
// Start up the database connection
MySQLConn::SetConnection();
// Assign database connection
$handler = MySQLConn::$connect;
// Checks if the submitted is a number. If so, isolates the ID and adds "where" clause
$id = (!empty($_GET['ID']) && is_numeric($_GET['ID']))? " where ID = '".$_GET['ID']."'" : "";
// Add the $id to the end of the string
// A single call would be SELECT * FROM guestquestionnaire where ID = '1'
$query = $handler->query("SELECT * FROM guestquestionnaire{$id}");
$query->setFetchMode(PDO::FETCH_CLASS, 'guestquestionnaireEntry');
// Assign data
while($r = $query->fetch()) {
$setEntry[] = $r->entry;
}
// Implode with break
if(isset($setEntry))
echo implode("<br />",$setEntry);
?>
Related
I don’t know, how I do this: I want to add $id from database to $_SESSION["dbID"] and after click, it shows me more information from database. But table generates in while function and $_SESSION["dbID"] every time set to the highest number of row from table. Please, Can you anyone change my code as I have $_SESSION["dbID"] on every <tr> of table different? Thank you
while($row = $result->fetch_assoc())
{
$id=$row['ID'];
$name=$row['Name'];
$subject=$row['Subject'];
$date=$row['Date'];
echo
'<tr class="trX" id="'.$id.'" href="google.com&id='.$row['ID'].'">
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php">' . $id . '</a></td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php">' . $name . '</td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php">' . $subject . '</td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php">' . $date . '</td>
</tr>';
}
$_SESSION["dbID"] = $id;
echo ' </table> ';
Explanation
You can do away with all of the a tags and use JavaScript to handle the redirect...
$url = "/path/to/file.php?id=" . $id;
Set the URL to the page that you want to link to. The line above shows the link to the file "file.php" on the server with the query string "id=$id".
onclick="window.location.href='...'"
The line above is a JS equivalent of href. If you want to navigate to a server outside of your domain remember to add the full url e.g. https://www.website.com
Code example
while ($row = $result->fetch_assoc()) {
$id = $row['ID'];
$name = $row['Name'];
$subject = $row['Subject'];
$date = $row['Date'];
$url = "/url/path.php?id=" . $id;
echo <<<EOT
<tr class="trX" onclick="window.location.href='{$url}'">
<td class="tdX">{$id}</td>
<td class="tdX">{$name}</td>
<td class="tdX">{$subject}</td>
<td class="tdX">{$date}</td>
</tr>
EOT;
}
echo ' </table> ';
if (mysqli_num_rows($sql) > 0) {
$row = mysqli_fetch_assoc($sql);
}
while($row = $result->fetch_assoc()){ ?>
<tr class="trX" id="'.<?php echo $row['ID']; ?>.'" href="google.com&id='.$row['ID'].'">
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php"><?php echo $row['ID']; ?></a></td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php"><?php echo $row['Name']; ?></td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php"><?php echo $row['Subject']; ?></td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php"><?php echo $row['Date']; ?> </td>
</tr>
<?php } ?>
Dont define the rows just make a call for them in the databse.
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.
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.
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.
I am attempting to update the code for my web page's search function, right now it is not returning anything. I have been working with it for a little while and not getting anything out of it.
This is the HTML search code:
<form method="post" action="words_results1.php">
<table align="center">
<tr>
<td>Keyword</td>
<td><input type="text" name="Keyword" /></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" name="Author" /></td>
</tr>
<tr>
<td valign=bottom>Words Posted<BR />on or before</td>
<td valign=top>
<table>
<tr>
<td width="33%">Day</td>
<td width="33%">Month</td>
<td width="34%">Year</td>
</tr>
<tr>
<td>
<select name=Day>
<?php
echo '<option></option>';
for($count = 1; $count <= 31; ++$count)
{
echo "<option>$count</option>";
}
?>
</select>
</td>
<td>
<select name=Month>
<?php
echo '<option></option>';
for($count = 1; $count <= 12; $count++)
{
echo "<option value=$count>".date("M", mktime(0,0,0,$count,1, 2000))."</option>";
}
?>
</select>
</td>
<td>
<select name=Year>
<?php
echo '<option></option>';
for($count = date("Y"); $count >= 1997; $count--)
{
echo "<option>$count</option>";
}
?>
</select>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan=2 align=center>
<BR />
<input type="submit" value="Search" />
<input type="submit" name="cancel" value="Cancel" />
</td>
</tr>
</table>
</form>
PHP
<?php
if(isset($_POST['cancel']))
{
echo("index.html");
exit;
}
$qry_string = "SELECT * FROM Words";
$search = "";
if(!empty($Keyword))
{
$End_String = "(Word LIKE '%$Keyword%' OR Title LIKE '%$Keyword%')";
$search .="&Keyword=$Keyword";
}
if(!empty($Author))
{
if(isset($End_String))
{
$End_String .= " AND (Author LIKE '%$Author%')";
}
else
{
$End_String = "(Author LIKE '%$Author%')";
}
$search .="&Author=$Author";
}
if(!empty($Day))
{
if(isset($End_String))
{
$End_String .= " AND (DAYOFMONTH(Date_Created) = '$Day')";
}
else
{
$End_String = "(DAYOFMONTH(Date_Created) = '$Day')";
}
$search .="&Day=$Day";
}
if(!empty($Month))
{
if(isset($End_String))
{
$End_String .= "AND (MONTH(Date_Created) = '$Month')";
}
else
{
$End_String = "(MONTH(Date_Created) = '$Month')";
}
$search .="&Month=$Month";
}
if(!empty($Year))
{
if(isset($End_String))
{
$End_String .= " AND (YEAR(Date_Created) = '$Year')";
}
else
{
$End_String = "(YEAR(Date_Created) = '$Year')";
}
$search .="&Year=$Year";
}
if (!isset($offset)) $offset=0;
if(isset($End_String))
{
$qry_string = $qry_string." WHERE ".$End_String . " ORDER BY Date_Created DESC LIMIT $offset,101";
}
else
{
$qry_string = $qry_string." ORDER BY Date_Created DESC LIMIT $offset,101";
}
// echo $qry_string . "<P><HR><P>";
$result = mysql_query($qry_string);
echo mysql_error();
?>
This last bit is the code that forms the table, I have an assumption that the problem lies here but honestly am not sure at this point
<table style="margin: 5px 15px; 5px 20px;" align="center" bgcolor="#666666" border="0" cellpadding="3" cellspacing="1">
<tbody><tr style="background: #04C1DE; font-family: Verdana; font-weight: bold; font-size: 18px;">
<td style="width: 50%; padding: 5px;">
Word
</td>
<td style="width: 20%; padding: 5px;">
Author
</td>
<td style="width: 10%; padding: 5px;">
Date
</td>
<td>Category</td>
<td>Active?</td>
<td> </td>
<td> </td>
</tr>
</tbody>
</tr>
<?php
$count = 1;
$bgc = 0;
while($row = mysql_fetch_array($sql))
{
if ($count > 100) break;
echo '<tr style="background: ';
if ($bgc==0) echo "#FFFFFF";
else echo "#CFEBFD";
$bgc == 0?$bgc=1:$bgc=0;
echo ';">';
echo "<td><a href=../../words/display_word.php?ID=$row[ID]>$row[Title]</a></td>";
echo "<td>$row[Author]</td><td>$row[Display_Date]</td><td>$row[category]</td>";
if($row[active])
{
echo "<td>YES</td>";
}
else
{
echo "<td>NO</td>";
}
echo "<td>$row[link_count]</td>";
if($row[Title] != "")
{
echo "<td><a href=words_edit.html?ID=$row[ID]>Edit</a></td></tr>";
}
else
{
echo "</tr>";
}
$count++;
}
?>
It seems,you are not collecting the value of
$Keyword=$_POST['Keyword'];
and add ,closing table tag to display the results in the table format correctly.