Checking and Returning values from database - php

I have this little issue:
I want to retrieve some rows from the database, it retrieves fine, but when i insert a particular value in the text field which is not present in the database to track, it returns an empty/blank page, below is the code i used:
<form id="track" name="track" method="post" action="track_now.php">
<h2>Track your shipment Here</h2>
<p><label> Tracking Reference:
<input type="text" id="reference" name="reference" value="" maxlength="40" required="required" /></label></p>
<div class="button_holder">
<p> <input type="submit" id="track" value="Track Now" maxlength="40" required="required" /></label>
</label></p>
</div>
</form>
and this is the track_now.php
<form id="track" name="track" method="post" action="">
<h2>Your Shipment Result</h2>
<?php
//error_reporting(0);
$ref = mysql_real_escape_string($_POST['reference']);
// conmnecting to the database
if(isset($ref))
{
$db = mysql_connect('localhost', 'admin', "admin") or die(mysql_error("Cannot Connect to Database"));
mysql_select_db('tracking') or die(mysql_error());
$sql = "SELECT * FROM order_tracking WHERE ship_ref = '".$ref."' ";
$rs = mysql_query($sql);
if($row = mysql_fetch_array($rs)) {
echo '<table width="518" border="1";>';
echo '<tr>';
echo '<td width="137" style="font-size:12px; padding: 5px;" >Shipment Reference: </td>';
echo '<td width="365" style="background-color:#fcfcfc; padding: 10px; font-size:12px;">' . $row['ship_ref'] . "<br />" . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td width="137" style="font-size:12px; padding: 5px;" >Shipment Type: </td>';
echo '<td width="365" style="background-color:#fcfcfc; padding: 10px; font-size:12px;">' . $row['ship_type'] . "<br />" . '</td>';
echo '</tr>';
}
echo "</table>";
}
else if ($rs != $row) {
print 'Invalid Tracking Number, Please click here to try again' ;
}
mysql_close();
?>
Please, what am i doing wrong here?

Your condition could be simplified, try this way:
if(isset($ref)){
$db = mysql_connect('localhost', 'admin', "admin") or die(mysql_error("Cannot Connect to Database"));
mysql_select_db('tracking') or die(mysql_error());
$sql = "SELECT * FROM order_tracking WHERE ship_ref = '".$ref."' ";
$rs = mysql_query($sql);
if(!rs){
die(mysql_error());
}
if($row = mysql_fetch_array($rs)) {
echo '<table width="518" border="1";>';
echo '<tr>';
echo '<td width="137" style="font-size:12px; padding: 5px;" >Shipment Reference: </td>';
echo '<td width="365" style="background-color:#fcfcfc; padding: 10px; font-size:12px;">' . $row['ship_ref'] . "<br />" . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td width="137" style="font-size:12px; padding: 5px;" >Shipment Type: </td>';
echo '<td width="365" style="background-color:#fcfcfc; padding: 10px; font-size:12px;">' . $row['ship_type'] . "<br />" . '</td>';
echo '</tr>';
echo "</table>";
}
mysql_close();
}
else{
print 'Invalid Tracking Number, Please click here to try again' ;
}
because else if ($rs != $row) will have undefined value if first condition is not met.
As #marco pointed out, you can check for rows without fetching:
if(mysql_num_rows($rs) > 0){
//found a row
}

Related

Checkbox selection in table

I've seen similar questions on here but the code is different when I try to implement it. I'm using php and html to connect to my db2 database, pull data from a table and display the pulled data in an html table. I'm trying to add functionality to my 'delete' button and would like to be able to mark a check-box that would highlight the selected row in the table. I'm working on my delete.php but for now I would like to implement this row selection. I found a line of code that I put at the start of my table, but how do I highlight the row? Here's what I have so far:
<html>
<head><title>DB Testing</title></head>
<style>
table{
font-family: arial, sans-serif;
border-collapse: collapse;
width: 80%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
<body>
<?php
//db2 express c (v10.5) in local
$database = "db";
$user = "user";
$password = "password";
//create connection
$conn = db2_connect($database, $user, $password);
//check connection
if($conn) {
//echo "DB2 Connection succeeded.<br><br>";
} else{
exit("failed".db2_conn_errormsg());
}
//select fields from database
$sql = "select 'JUNK', A, B, START_TIME, END_TIME, START_DAY,
END_DAY, C, ID, BUSINESS_AREA, ENVIRONMENT from testtable where A='D'
and AVAILABILITY = 'Y'";
$stmt = db2_prepare($conn, $sql);
//db2_execute executes a sql statement that was prepared by db2_prepare
if($stmt){
$result = db2_execute($stmt);
if(!$result){
echo "exec errormsg: " .db2_stmt_errormsg($stmt);
}
//the echos below output the data in an html table
echo '<table border = 1>';
echo '<thead>';
echo '<tr>';
echo'<th></th>';
echo'<th>A</th>';
echo'<th>B</th>';
echo'<th>START_TIME</th>';
echo'<th>END_TIME</th>';
echo'<th>START_DAY</th>';
echo'<th>END_DAY</th>';
echo'<th>C</th>';
echo'<th>ID</th>';
echo'<th>BUSINESS_AREA</th>';
echo'<th>ENVIRONMENT</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = db2_fetch_assoc($stmt)) {
echo '<tr>';
echo "<td><input name=\"checkbox[]\" type=\"checkbox\" value=\"".$rows['']. "\" /></td>";
echo '<td>' . $row['A'] . '</td>';
echo '<td>' . $row['B'] . '</td>';
echo '<td>' . $row['START_TIME'] . '</td>';
echo '<td>' . $row['END_TIME'] . '</td>';
echo '<td>' . $row['START_DAY'] . '</td>';
echo '<td>' . $row['END_DAY'] . '</td>';
echo '<td>' . $row['C'] . '</td>';
echo '<td>' . $row['ID'] . '</td>';
echo '<td>' . $row['BUSINESS_AREA'] . '</td>';
echo '<td>' . $row['ENVIRONMENT'] . '</td>';
echo '</tr>';
echo '</tbody>';
}
echo '</table>';
}else {
echo "exec errormsg: ".db2_stmt_errormsg($stmt);
}
db2_close($conn);
?>
<?php
function print_r2($val){
echo '<pre>';
print_r($val);
echo '</pre>';
}
?>
</body>
</html>
You'll need some javascript to do the trick, see the snippet:
function hl(ob){
if(ob.checked == true){
ob.parentNode.parentNode.style.backgroundColor='red';
}
if(ob.checked != true){
ob.parentNode.parentNode.style.backgroundColor='white';
}
}
<table border=1 cellspacing=0 cellpadding=5>
<tr>
<td><input type="checkbox" name="checkbox" value="1" onClick="hl(this)" /></td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox" value="2" onClick="hl(this)" /></td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox" value="3" onClick="hl(this)" /></td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
EDIT
<html>
<head>
<title>DB Testing</title>
<script type="text/javascript">
function hl(ob){
if(ob.checked == true){
ob.parentNode.parentNode.style.backgroundColor='red';
}
if(ob.checked != true){
ob.parentNode.parentNode.style.backgroundColor='white';
}
}
</script>
<style>
table{
font-family: arial, sans-serif;
border-collapse: collapse;
width: 80%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
</head>
<body>
<?php
//db2 express c (v10.5) in local
$database = "db";
$user = "user";
$password = "password";
//create connection
$conn = db2_connect($database, $user, $password);
//check connection
if($conn) {
//echo "DB2 Connection succeeded.<br><br>";
} else{
exit("failed".db2_conn_errormsg());
}
//select fields from database
$sql = "select 'JUNK', A, B, START_TIME, END_TIME, START_DAY,
END_DAY, C, ID, BUSINESS_AREA, ENVIRONMENT from testtable where A='D'
and AVAILABILITY = 'Y'";
$stmt = db2_prepare($conn, $sql);
//db2_execute executes a sql statement that was prepared by db2_prepare
if($stmt){
$result = db2_execute($stmt);
if(!$result){
echo "exec errormsg: " .db2_stmt_errormsg($stmt);
}
//the echos below output the data in an html table
echo '<table border = 1>';
echo '<thead>';
echo '<tr>';
echo'<th></th>';
echo'<th>A</th>';
echo'<th>B</th>';
echo'<th>START_TIME</th>';
echo'<th>END_TIME</th>';
echo'<th>START_DAY</th>';
echo'<th>END_DAY</th>';
echo'<th>C</th>';
echo'<th>ID</th>';
echo'<th>BUSINESS_AREA</th>';
echo'<th>ENVIRONMENT</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = db2_fetch_assoc($stmt)) {
echo '<tr>';
echo "<td><input name=\"checkbox[]\" type=\"checkbox\" value=\"".$rows['']. "\" onClick=\"hl(this)\" /></td>";
echo '<td>' . $row['A'] . '</td>';
echo '<td>' . $row['B'] . '</td>';
echo '<td>' . $row['START_TIME'] . '</td>';
echo '<td>' . $row['END_TIME'] . '</td>';
echo '<td>' . $row['START_DAY'] . '</td>';
echo '<td>' . $row['END_DAY'] . '</td>';
echo '<td>' . $row['C'] . '</td>';
echo '<td>' . $row['ID'] . '</td>';
echo '<td>' . $row['BUSINESS_AREA'] . '</td>';
echo '<td>' . $row['ENVIRONMENT'] . '</td>';
echo '</tr>';
echo '</tbody>';
}
echo '</table>';
}else {
echo "exec errormsg: ".db2_stmt_errormsg($stmt);
}
db2_close($conn);
?>
<?php
function print_r2($val){
echo '<pre>';
print_r($val);
echo '</pre>';
}
?>
</body>
</html>

Php sqlsrv search POST and GET Method multiple parameters

First of all, i want to create a page that show a record of last one week from today date. Then, when user searching, it will show the specific record. The problem now is the pagination that i made clash through the last one week query, so the searching data cannot load its query bcs i set it up as POST method.
$name = null;
$id = null;
if(isset($_POST["search"]))
{
$name = $_POST["name"];
$id = $_POST["id"];
}
if(isset($_GET["search"]))
{
$name = $_GET["name"];
$id = $_GET["id"];
}
$stmt = " SELECT c.* FROM (SELECT ROW_NUMBER() OVER(ORDER BY CustomerID) AS RowID,* FROM customer WHERE Name LIKE '%".$name."%' and ID LIKE '%".$id."%'
WHERE c.RowID > $row_start AND c.RowID <= $row_end";
This is if else statement
if (isset($_POST['search'])) {
if ($num_rows == 0) {
echo "No data ";
echo "<br/ >";
} else {
echo "<table style='border: 1px solid black;><tr>"
. "<th><font color='white'>Student <br> ID</font></th>"
. "<th><font color='white'>Name</font></th>"
. " <th><font color='white'>Date</font></th>"
. "</tr>";
while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
echo "<tbody style='border: 1px solid black; border-collapse: collapse; background-color: white'><tr>"
. "<td align='center' for='Student_ID'>" . "<a href='http://localhost:808/jjjl/newdashboard/Studensdf.php?Student_ID=" . $row['Student_ID'] . "'>" . $row['Student_ID'] . "</a>" . "</td>"
. "<td align='left'>" . $row['Name'] . "</td>"
. "<td align='center' for='Dates'>" . $row['Dates']->format('d/m/Y') . "</td>";
}
echo "</tbody";
echo "<br / >";
}
} else {
?>
<div class="col-md-12">
<?php
/*for last one week*/
if ($num_rows1 == 0) {
echo "No data for a week ago";
echo "<br/ >";
} else {
echo "<table style='border: 1px solid black;><tr>"
. "<th><font color='white'>Student <br> ID</font></th>"
. "<th><font color='white'>Name</font></th>"
. " <th><font color='white'>Date</font></th>". "</tr>";
while ($row = sqlsrv_fetch_array($query2, SQLSRV_FETCH_ASSOC)) {
echo "<tbody style='border: 1px solid black; border-collapse: collapse; background-color: white'><tr>"
. "<td align='center' for='Student_ID'>" . "<a href='http://localhost:8080/hhol/nhhhboard/Stukhhtail.php?Student_ID=" . $row['Student_ID'] . "'>" . $row['Student_ID'] . "</a>" . "</td>"
. "<td align='left'>" . $row['Name'] . "</td>"
. "<td align='center' for='Dates'>" . $row['Dates']->format('d/m/Y') . "</td>";
}
echo "</tbody";
echo "<br / >";
}
}
And the form
<form name="frmSearch" class="form-horizontal" action="<?php echo $script; ?>" method="post">
<label class="col-md-4">Student ID</label>: <input type="text" name="studentid" id="txtKeyword" value="<?php echo $studentid; ?>"><br>
<label class="col-md-4">Name</label>: <input type="text" name="name" id="txtKeyword1" value="<?php echo $name; ?>">
<input type="submit" name="search" value="Search"></th>
and pagination
if ($prev_page) {
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$prev_page'><< Back</a> ";
}
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $page) {
echo "[ <a href='$_SERVER[SCRIPT_NAME]?Page=$i&'>$i</a> ]";
} else {
echo "<b> $i </b>";
}
}
if ($page != $num_pages) {
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$next_page'>Next>></a> ";
}
sqlsrv_close($conn);

Display current session name

I use this but only one will display...
please help me I need to display same name in a table..
<?php
$id=$_SESSION['SESS_MEMBER_ID'];
$result = mysql_query("SELECT * FROM user_reservation WHERE id = '$id' ");
while($row = mysql_fetch_array($result)){
echo '<tr class="record" id="'.$row['status'].'">';
echo '<td style="border-left: 1px solid #C1DAD7;">'.$row['confirmation'].'</td>';
echo '<td>'.$row['firstname'].' '.$row['lastname'].'</td>';
echo '<td><div align="right">'.$row['email'].'</div></td>';
echo '<td><div align="left">';
echo '</div></td>';
echo '<td><div align="right">'.$row['status'].'</div></td>';
echo '<td><div align="center">delete</div></td>';
echo '</tr>';
}
?>
Use session_start() at the top
<?php
session_start()
$id=$_SESSION['SESS_MEMBER_ID'];
$result = mysql_query("SELECT * FROM user_reservation WHERE id = '$id' ");
while($row = mysql_fetch_array($result)){
echo '<tr class="record" id="'.$row['status'].'">';
echo '<td style="border-left: 1px solid #C1DAD7;">'.$row['confirmation'].'</td>';
echo '<td>'.$row['firstname'].' '.$row['lastname'].'</td>';
echo '<td><div align="right">'.$row['email'].'</div></td>';
echo '<td><div align="left">';
echo '</div></td>';
echo '<td><div align="right">'.$row['status'].'</div></td>';
echo '<td><div align="center">delete</div></td>';
echo '</tr>';
}
?>

The Next iteration

I'm having some display problems here.
I have a "backend.php" file where I ask for two inputs.
These inputs are processed by "Addproducts.php" file and this file redirects to backend.php.
Backend.php also shows the current records in the database.
Here's the code for backend.php
<html>
<head>
<title>Inventory - Backend</title>
</head>
<body>
<form action="addproducts.php" method="post">
<table>
<tr>
<td>Product Name : </td>
<td><input type="text" name="pname"/></td>
</tr>
<tr>
<td>Product Quantity : </td>
<td><input type="text" name="productq"/></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td><input type="submit" name="Add Product"/></td>
</tr>
</table>
</form>
<h2>Current Products</h2>
<?php
$db = mysql_connect('127.0.0.1', 'root', '') or die ('Unable to Connect.Check your connection parameters');
mysql_select_db('stock_inventory', $db) or die (mysql_error($db));
$query = 'SELECT * FROM PRODUCTS';
$result = mysql_query($query, $db) or die (mysql_error($db));
echo '<table>';
echo '<tr>';
echo '<th>Product ID </th>';
echo '<th>Producr Name </th>';
echo '<th>Product Stock </th>';
echo '</tr>';
while($row = mysql_fetch_assoc($result))
{
if(mysql_num_rows($result) > 0)
{
echo '<tr>';
echo '<td>' . $row['product_id'] . '</td>';
echo '<td>' . $row['product_name'] . '</td>';
echo '<td>' . $row['product_stock'] . '</td>';
echo '</tr>';
echo '<br/>';
echo '</table>';
}
else
{
echo "No products in the database";
}
}
?>
</body>
</html>
It displays something like this :-
Product ID Producr Name Product Stock
1 NewProduct 1
2HTC One5
3Samsung10
4Sony10
You see?
Only the first product is aligned, the rest are not.
How do I make them all align ?
Thanks.
The reason is you are closing your table tag within the loop, move it outside the loop like follows:
while($row = mysql_fetch_assoc($result))
{
if(mysql_num_rows($result) > 0)
{
echo '<tr>';
echo '<td>' . $row['product_id'] . '</td>';
echo '<td>' . $row['product_name'] . '</td>';
echo '<td>' . $row['product_stock'] . '</td>';
echo '</tr>';
}
else
{
echo "No products in the database";
}
}
echo '<br/>';
echo '</table>';
Update: A better fix (see Barmar's comment below):
if (empty(mysql_num_row($result))) {
echo "<tr><td colspan='3'>No products in the database</td></tr>";
} else {
while($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>' . $row['product_id'] . '</td>';
echo '<td>' . $row['product_name'] . '</td>';
echo '<td>' . $row['product_stock'] . '</td>';
echo '</tr>';
}
}
echo '</table>';
Also start looking into using mysqli(http://php.net/manual/en/book.mysqli.php) or PDO (http://php.net/manual/en/book.pdo.php), mysql_ is deprecated!
I would suggest removing the
<br/>
from within your table. I believe that putting markup like line breaks inside of table markup will break the layout.

php linebreak causes string value to disappear

I have some php querying and printing the info of a mysql table on a medical recruitment website.
Sometimes the users enter, causing line breaks where I would rather not have them, because
it affects the layout of the rendered HTML table in a way that it shouldn't.
I can trim the strings when they fill in the forms and the data get written into the table, but there's already a lot of data there, so i decided to remove the line breaks on the page
where php reads and prints the results.
i declared one of the strings where this causes trouble as such:
$specialtr = trim($special, "\n");
and then where the html table gets rendered:
echo '<td width="150">' . $specialtr . '</td>';
Here is the whole code:
All the code works, it's only the parts above that I added that now causes the column with $specialtr variable not to print/print as empty.
<form action="selected.php" method="POST">
<table border="1" cellpadding="2" cellspacing="2" style="width: 98%; margin-left: auto; margin-right: auto;">
<tr>
<td>
<?php
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (mysql_error($conn));
mysql_select_db($dbname) or die(mysql_error($conn));
$specialtr = trim($special, "\n");
echo '<table border="1" cellpadding="2" cellspacing="2" style="margin-left: auto; margin-right: auto;">';
$query = 'SELECT userid FROM employee
ORDER BY userid ASC';
$result = mysql_query($query, $conn) or die(mysql_error($conn));
$num_entries = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
echo '<tr>';
echo '<td><input type="radio" name="employee" value="' . $row['userid'] . '"/></td>';
echo '<td>Select</td>';
}
}
echo '</tr>';
echo '</table>';
?>
</td>
<td>
<?php
echo '<table border="1" cellpadding="2" cellspacing="2" style="width: 98%; margin-left: auto; margin-right: auto;">';
echo '<tr>';
$query = 'SELECT userid, name, surname, sex, age, nationality, email, telnr, special FROM employee
ORDER BY userid ASC';
$result = mysql_query($query, $conn) or die(mysql_error($conn));
while ($row = mysql_fetch_assoc($result)) {
extract($row);
echo '<td>' . $userid . '</td>';
echo '<td>' . $name . '</td>';
echo '<td>' . $surname . '</td>';
echo '<td>' . $sex . '</td>';
echo '<td>' . $age . '</td>';
echo '<td>' . $nationality . '</td>';
echo '<td>' . $email . '</td>';
echo '<td>' . $telnr . '</td>';
echo '<td width="150">' . $specialtr . '</td>';
echo '</tr>';
}
echo '</table>';
?>
</td>
</tr>
</table>
<br/>
<br/>
<input type="submit" name="go" value="Go!" />
</form>
The code worked well enough, but since I added the trim, that entire column (the $special column disappears).
I hope maybe someone can tell me why it disappears or if my syntax has a little mistake.
Using extract() like that is a horrible thing. The function should be avoided as a general rule.
Also note that you're doing your trim() call BEFORE $special is defined, so your $specialtr variable is going to be an empty string. Calling the function before you start fetching your database results and extracting a result row into $special will not magically apply trim() to reach row you've fetched. If you want the results to be trimmed as you fetch them, then you have to apply the trim AFTER you do the fetch:
while ($row = mysql_fetch_assoc($result)) {
echo '<td>' . $row['userid'] . '</td>';
...
echo '<td width="150">' . trim($row['special']) . '</td>';
^^^^^^^^^^^^^^^^^^^^^
}

Categories