Paginating With Mysqli And Prepared Statements - php

I am learning PHP. I tried building a script that shows records from MySQL by pagination.
I set the code to show 1 record per page. There are 4 records or matches on the MySQL table for the recipient 'admin123'. I have logged-into this account.
And so, this pagination script should pull 4 records to show me. 1 record per page. Total 4 pages. It gives echo 2 results found (it should show 4). And then only shows 1 record on the page as expected. But, I do not see the pagination section. No links to the other pages are getting shown like this:
Page 1234.
I am confused now. Please take a look and let me know where I am going wrong.
<?php
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include 'configurations.php';
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
else
{
//Get Page Number. Default is 1 (First Page).
$page_number = $_GET["page_number"];
if ($page_number == "")
{
$page_number = 1;
}
$sender_username = $mod; //$mod defined in configurations.php
$recipient_username = $user;
$links_per_page = 1;
$max_result = 30;
$offset = ($page_number*$links_per_page)-$links_per_page;
$query_1 = "SELECT COUNT(*) FROM messages WHERE recipient_username = ?
AND sender_username = ? ORDER BY id LIMIT ? OFFSET ?";
$stmt_1 = mysqli_prepare($conn,$query_1);
mysqli_stmt_bind_param($stmt_1,'ssii',$recipient_username,$sender_username,$ links_per_page,$offset);
mysqli_stmt_execute($stmt_1);
$result_1 = mysqli_stmt_bind_result($stmt_1,$matching_rows_count);
mysqli_stmt_fetch($stmt_1);
mysqli_stmt_free_result($stmt_1);
$total_pages = ceil($matching_rows_count/$links_per_page);
$query_2 = "SELECT id,date_and_time,recipient_username,sender_username,warning_messages FROM
messages WHERE recipient_username = ? AND sender_username = ? ORDER BY id
LIMIT ? OFFSET ?";
$stmt_2 = mysqli_prepare($conn,$query_2);
mysqli_stmt_bind_param($stmt_2,'ssii',$recipient_username,$sender_username,$links_per_page,$offset);
mysqli_stmt_execute($stmt_2);
$result_2 = mysqli_stmt_bind_result($stmt_2,$id,$date_and_time,$recipient_username,$sender_username,$warning);
mysqli_stmt_fetch($stmt_2);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional/EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv=" content-type">
<title><?php echo "$site_name User $user Warnings in $server_time time."; ?>
</title>
</head>
<body>
<br>
<p align="center"><span style="font-weight:bold;"><?php echo "$site_name
User $user Warnings in $server_time time."; ?></span></align>
<br>
<br>
<table width="1500" border="0" cellpadding="5" cellspacing="2"
bgcolor="#666666">
<?php if(!$stmt_2)
{
?>
<tr>
<td bgcolor="#FFFFFF">No record found! Try another time.</td>
</tr>
<?php
}
else
{
if(($offset+1)<=$max_result)
{
printf("<b> %d Result Found ...</b>\n",$matching_rows_count); ?><br>
<br>
<tr name="headings">
<td bgcolor="#FFFFFF" name="heading_submission-
number">Submission Number</td>
<td bgcolor="#FFFFFF" name="heading_date-and-
time">Date & Time in <?php echo "$server_time" ?></td>
<td bgcolor="#FFFFFF" name="heading_recipient-
username">To</td>
<td bgcolor="#FFFFFF" name="heading_sender-
username">From</td>
<td bgcolor="#FFFFFF" name="heading_warning">Warning</td>
</tr>
<tr name="user-details">
<td bgcolor="#FFFFFF" name="submission-number"><?php
printf("%s",$id); ?></td>
<td bgcolor="#FFFFFF" name="date-and-time"><?php
printf("%s",$date_and_time); ?></td>
<td bgcolor="FFFFFF" name="recipient-username"><?php
printf("%s",$recipient_username); ?></td>
<td bgcolor="#FFFFFF" name="sender-username"><?php
printf("%s",$sender_username); ?></td>
<td bgcolor="#FFFFFF" name="warning"><?php printf("%s",$warning); ?>
</td>
</tr>
<?php
while(mysqli_stmt_fetch($stmt_2))
{
?>
<tr name="user-details">
<td bgcolor="#FFFFFF" name="submission-number"><?php
printf("%s",$id); ?></td>
<td bgcolor="#FFFFFF" name="date-and-time"><?php
printf("%s",$date_and_time); ?></td>
<td bgcolor="#FFFFFF" name="recipient-username"><?php
printf("%s",$recipient_username); ?></td>
<td bgcolor="#FFFFFF" name="sender-username"><?php
printf("%s",$sender_username); ?></td>
<td bgcolor="#FFFFFF" name="warning"><?php
printf("%s",$warning);
?></td>
</tr>
<?php
?>
<tr name="pagination">
<td colspan="10" bgcolor="#FFFFFF"> Result Pages:
<?php
if($page_number < $total_pages)
{
for($i=1;$i<=$total_pages;$i++) //Show Page Numbers in
Serial.
echo "<a href=\"{$_SERVER['PHP_SELF']}?
user=$user&page_number={$i}\">{$i}</a> ";
}
else
{
for($i=$total_pages;$i>=1;$i--) //Show Page Numbers in
Reverse.
echo "<a href=\"{$_SERVER['PHP_SELF']}?
user=$user&page_number={$i}\">{$i}</a> ";
}
?>
</td>
</tr>
<?php
}
}
}
?>
</table>
<br>
<br>
<p align="center"><span style="font-weight:bold;"><?php echo "$site_name
User $user Warnings in $server_time time."; ?></span></align>
<br>
</div>
<br>
</body>
</html>
<?php
mysqli_stmt_free_result($stmt_2);
mysqli_stmt_close($stmt_2);
mysqli_close($conn);
}
?>

Related

Row with button submitting wrong data to server

Ive been working on this issue for some time now, basically, i have a table and at the end of row is a button that submits that rows batchID and Priority value to my .php that handles post requests. the problem comes when i hit submit it takes the batchID column from the last row regardless of which button is pressed. i have this exact same code running on another site which works as intended. when i inspect the network data being sent it shows that all the data in column batchID is being sent to upload.php, but i only need the corresponding batchID to be sent.
<?php
$con = mysqli_connect("localhost", "root", "", "production_management");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
require('databaseDetails.php');
session_start();
$userNameTmp = $_SESSION["usrName"];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Received Request Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p><button class="button button2">Dashboard</button><p>
<form name="form" method="post" action="upload.php">
<div class="form">
<h1>Batch's</h1>
<p>Hello <?php echo $userNameTmp;?> </p>
<table class="responsive-table" width="100%" border="1" style="border-
collapse:collapse;">
<thead>
<tr>
<th><strong>Started By</strong></th>
<th><strong>Batch Type</strong></th>
<th><strong>Date</strong></th>
<th><strong>Batch ID</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Progress</strong></th>
<th><strong>Priority</strong></th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM batch";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result)) { ?>
<td align="center"><?php echo $row["startedBy"]; ?></td>
<td align="center"><?php echo $row["batchType"]; ?></td>
<td align="center"><?php echo $row["date"]; ?></td>
<td align="center"><?php echo $row["batchID"]; ?></td>
<td align="center"><?php echo $row["quantity"]; ?></td>
<td align="center"><?php echo $row["progress"]; ?></td>
<td align="center"><?php echo $row["priority"]; ?></td>
<td align="center"><input type="hidden" name="postMethod" value="3"></td>
<td align="center"><input type="hidden" name="batchID" value="<?php echo
$row["batchID"]; ?>"></td>
<td align="center"><input type="submit" value="test"></td></tr>
<?php
}
?>
</tbody>
</table>
</div>
</form>
</body>
</html>

PHP/MySQL: Sort database results by clicking on hyperlink in the page

I have a page that executes a query from a database. There are 5 columns, and I want the first and last column to be a sorting hyperlink. This is my code. I want to be able to click on column "price" or "course ID" to sort them by the category. When I click the link, nothing happens, but the ?sort=price shows on the url. I am fairly new to PHP and MySQL and I cannot find anything online. Thank you in advance.
<?php
require_once ('mysqli_connect.php');
//grab data from database
$course = "SELECT course.courseID, course.courseTitle, course.credit,
book.bookTitle, book.price, book.isbn13
FROM course
INNER JOIN coursebook ON course.courseID=coursebook.course
JOIN book ON coursebook.book=book.isbn13
ORDER BY course.courseID";
$course_response = mysqli_query($dbc, $course);
$isbn = "SELECT isbn13 FROM book";
$isbn_response = mysqli_query($dbc, $isbn);
// Close connection to the database
mysqli_close($dbc);
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>Book Catalog</title>
</head>
<!-- the body section -->
<body>
<main>
<div>
<h1 align='center'>Book Catalog</h1>
<?php $array = array(); // make a new array to hold data
$index = 0;
?>
<?php if($course_response){ ?>
<table align="left" cellspacing="5" cellpadding="8">
<tr>
<td align="left"><a href="index.php?sort=course"><b>Course #</b>
</td>
<td align="left"><b>Course Title</b></td>
<td align="left"><b>Book Image</b></td>
<td align="left"><b>Book Title</b></td>
<td align="left"><b>Price</b>
</td>
</tr>
<?php
if ($_GET['sort'] == 'price') {
$query .= " ORDER BY book.price";
}elseif ($_GET['sort'] == 'course') {
$query .= " ORDER BY Description";
}
?>
<?php while($row = mysqli_fetch_array($course_response)){ ?>
<tr>
<td align="left">
<a href="www.barnesandnoble.com">
<?php echo $row['courseID']; ?></a></td>
<td align="left"> <?php echo $row['courseTitle']; ?> (<?php echo
$row['credit']; ?>)</td>
<td align="left"> <a href='bookDetails.php'>
<?php $isbnrow = $row['isbn13']; ?><img src='images/<?php echo
$isbnrow?>.jpg' width='90px' height='100px'></a></td>
<td align="left"> <?php echo $row['bookTitle']; ?></td>
<td align="left"> <?php echo "$" . $row['price']; ?></td>
</tr>
<?php } ?>
<?php } else {
echo "Couldn't issue database query<br />";
echo mysqli_error($dbc);
} ?>
</table>
</div>
</main>
</body>
</html>
You are not passing the get paramaters to the mysql query to order the results.
update your codes by following code,
<?php
require_once ('mysqli_connect.php');
//grab data from database
$order_by = null;
if($_GET){
switch($_GET['sort']){
case 'price' :
$order_by = 'ORDER BY book.price ASC';
break;
case 'course' ;
$order_by = 'ORDER BY course.courseID DESC';
break
}
}
$course = "SELECT course.courseID, course.courseTitle, course.credit,
book.bookTitle, book.price, book.isbn13
FROM course
INNER JOIN coursebook ON course.courseID=coursebook.course
JOIN book ON coursebook.book=book.isbn13 ";
$course .= (!is_null($order_by)) ? $order_by : "ORDER BY course.courseID ASC";
$course_response = mysqli_query($dbc, $course);
if(!$course_response){
die("Error in query: " . mysqli_error($dbc));
}
?>
<!DOCTYPE html>
<html>
<head><title>Book Catalog</title></head>
<body>
<main>
<div>
<h1 align='center'>Book Catalog</h1>
<?php if($course_response){ ?>
<table align="left" cellspacing="5" cellpadding="8">
<tr>
<td align="left"><a href="index.php?sort=course"><b>Course #</b></td>
<td align="left"><b>Course Title</b></td>
<td align="left"><b>Book Image</b></td>
<td align="left"><b>Book Title</b></td>
<td align="left"><b>Price</b></td>
</tr>
<?php while($row = mysqli_fetch_array($course_response)){ ?>
<tr>
<td align="left"><?php echo $row['courseID']; ?></td>
<td align="left"> <?php echo $row['courseTitle']; ?> (<?php echo $row['credit']; ?>)</td>
<td align="left"> <a href='bookDetails.php'><?php $isbnrow = $row['isbn13']; ?><img src='images/<?php echo $isbnrow?>.jpg' width='90px' height='100px'></a></td>
<td align="left"> <?php echo $row['bookTitle']; ?></td>
<td align="left"> <?php echo "$" . $row['price']; ?></td>
</tr>
<?php } ?>
<?php } else { echo 'results not found!'; } ?>
</table>
</div>
</main>
</body>
</html>
<?php
// Close connection to the database
mysqli_close($dbc);
?>

perform multiple sql queries when clicking a submit button on PHP Page

I have a PHP page, that on clicking the submit button process a few MySQL queries.
in MySQL PHPMyAdmin the query works 100% and both queries execute. However, when in my PHP Code the queries do not execute.
Any help would be appreciated, I bet this is a simple one for decent PHP coders.
Thanks in advance Ryan.
My Code is:
<?php
mysql_connect("localhost", "hulamin_hulamin", "Hulamin2011")or die("cannot connect");
mysql_select_db("hulamin_loc")or die("cannot select DB");
$sql="SELECT `dispatcharea`,`customer`,`casenumber`,`weight` from loaddetails where loadid = 0 order by dispatcharea";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<html>
<head>
<title>
Plan Local PMB Delivery - Step 2
</title>
</head>
<html>
<table border=0>
<tr>
<td>
<form name="form1" method="post">
<table border=1>
<tr>
<td width=150>Dispatch Area</td>
<td width=300>Customer</td>
<td width=150>Case Number</td>
<td width=100>Weight</td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['dispatcharea']; ?></td>
<td><?php echo $rows['customer']; ?></td>
<td><?php echo $rows['casenumber']; ?></td>
<td><?php echo $rows['weight']; ?></td>
</tr>
<?php
}
?>
</table>
<input name="Next" type="submit" id="Next" value="Next">
<?php
if($_REQUEST['Next']=='Next') {
{
$sql="update loaddetails set loadid= (select max(loadid)+1 from loadcounterid) where loadid=0; update loadcounterid set loadid= (select max(loadid) from loaddetails) where loadid>0;";
$final=mysql_query($sql);
if($final)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=planlocalpmbstep3.php\">";
}
}
}
?>
</table>
</form>
</td>
</tr>
</table>
Thanks again,
Ryan
According to the PHP docs, mysql_query doesn't support multiple queries. PHPMyAdmin is probably separating the queries before executing them. Try splitting your query into two parts. (Also, the PHP docs say that you shouldn't end mysql_queries in semicolons, but it doesn't appear to hurt.)
I think that this is likely to be your problem
while($rows=mysql_fetch_array($result)){
Should be
while($rows=mysql_fetch_assoc($result)){
To refer to them as
echo $rows['dispatcharea'];
EDIT:
You also need to split both of your queries up in to two separate queries, because you cannot run two queries in one mysqli_query() tag.
You will need to split them as shown below:
// First update query
$sql1="update loaddetails set loadid= (select max(loadid)+1 from loadcounterid) where loadid=0";
// Second update query
$sql2="update loadcounterid set loadid= (select max(loadid) from loaddetails) where loadid>0";
// Run both queries independently
$final_query1 = mysql_query($sql1);
$final_query2 = mysql_query($sql2);
// Check for query success
if ($final_query1 && $final_query2)
{
// Success running the queries
}
else
{
// Unsuccessful running the queries
}
If you want to execute multiple queries at once, you can change over to using mysqli functions.
There is a mysqli function mysqli_multi_query() that can be used to execute multiple queries at once.
Please refer to:
http://php.net/manual/en/mysqli.multi-query.php
Here's a rough rewrite of the code using mysqli_multi_query() in an object oriented style:
<?php
$link = mysqli_connect('localhost', 'hulamin_hulamin', 'Hulamin2011', 'hulamin_loc');
$sql = "SELECT `dispatcharea`,`customer`,`casenumber`,`weight` from loaddetails where loadid = 0 order by dispatcharea";
$result = $link->query($sql);
$count = $result->num_rows($result);
?>
<html>
<head>
<title>
Plan Local PMB Delivery - Step 2
</title>
</head>
<html>
<table border=0>
<tr>
<td>
<form name="form1" method="post">
<table border=1>
<tr>
<td width=150>Dispatch Area</td>
<td width=300>Customer</td>
<td width=150>Case Number</td>
<td width=100>Weight</td>
</tr>
<?php
while($rows = $link->fetch_array($result)){
?>
<tr>
<td><?php echo $rows['dispatcharea']; ?></td>
<td><?php echo $rows['customer']; ?></td>
<td><?php echo $rows['casenumber']; ?></td>
<td><?php echo $rows['weight']; ?></td>
</tr>
<?php
}
?>
</table>
<input name="Next" type="submit" id="Next" value="Next">
<?php
if($_REQUEST['Next']=='Next'){
{
$multi_sql = "update loaddetails set loadid= (select max(loadid)+1 from loadcounterid) where loadid=0;";
$multi_sql .= "update loadcounterid set loadid= (select max(loadid) from loaddetails) where loadid>0";
$final = $link->multi_query($multi_sql);
if($final)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=planlocalpmbstep3.php\">";
} }
}
?>
</table>
</form>
</td>
</tr>
</table>
I thought I would just post my complete code that is now working. thanks to all who replied to my question, it is greatly appreciated. It is really awesome to be a part of this community that is so responsive.
My code is:
<?php
mysql_connect("localhost", "username", "password")or die("cannot connect");
mysql_select_db("dbname")or die("cannot select DB");
$sql="SELECT `dispatcharea`,`customer`,`casenumber`,`weight` from loaddetails where loadid = 0 order by dispatcharea";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<html>
<head>
<title>
Plan Local PMB Delivery - Step 2
</title>
</head>
<html>
<table>
<tr>
<td>
<center>
Load Number
</td>
<td>
<center>
Number of Cases
</td>
<td>
<center>
Load Weight
</td>
<td>
<center>
Other Detail
</td>
</tr>
<tr>
<td width=150>
<center>
<?php
$loadid = mysql_query('SELECT max(loadid)+1 FROM loaddetails');
if (!$loadid) {
die('Could not query:' . mysql_error());
}
echo mysql_result($loadid, 0);
?>
</td>
<td width=150>
<center>
<?php
$nocases = mysql_query('SELECT count(*) FROM loaddetails where loadid = 0');
if (!$nocases) {
die('Could not query:' . mysql_error());
}
echo mysql_result($nocases, 0);
?>
</td>
<td width=150>
<center>
<?php
$weight = mysql_query('SELECT SUM(WEIGHT) FROM loaddetails where loadid = 0');
if (!$loadid) {
die('Could not query:' . mysql_error());
}
echo mysql_result($weight, 0);
?>
</td>
<td width=150>
<center>
</td>
</tr>
</table>
<hr>
<table border=0>
<tr>
<td>
<form name="form1" method="post">
<table border=1>
<tr>
<td width=150>Dispatch Area</td>
<td width=300>Customer</td>
<td width=150>Case Number</td>
<td width=100>Weight</td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['dispatcharea']; ?></td>
<td><?php echo $rows['customer']; ?></td>
<td><?php echo $rows['casenumber']; ?></td>
<td><?php echo $rows['weight']; ?></td>
</tr>
<?php
}
?>
</table>
<input name="Next" type="submit" id="Next" value="Next">
<?php
// First update query
$sql1="update loaddetails set loadid= (select max(loadid)+1 from loadcounterid) where loadid=0";
// Second update query
$sql2="update loadcounterid set loadid= (select max(loadid) from loaddetails) where loadid>0";
if($_REQUEST['Next']=='Next'){
// Run both queries independently
$final_query1 = mysql_query($sql1);
$final_query2 = mysql_query($sql2);
if ($final_query1 && $final_query2)
{
// Success running the queries
echo "<meta http-equiv=\"refresh\" content=\"0;URL=planlocalpmbstep3.php\">";
}
else
{
// Unsuccessful running the queries
}
}
?>
</table>
</form>
</td>
</tr>
</table>

mysql results error on php

hello below is my code for a query with submit from.. the no of rows are correctly count and show in the page and the result rows are not show in my page and show "No results found, please search again", i cant find the error on my code, can anyone help to find it..
<?
### DEBUG
$debugP = 0 ;
### END DEBUG
include 'db_connector.php';
require_once('myfunctions.php');
include('header.php');
#defauts
$maxRows_p = 10;
$pageNum_p = 0;
if (isset($_GET['pageNum_p'])) {
$pageNum_p = $_GET['pageNum_p'];
}
$startRow_p = $pageNum_p * $maxRows_p;
$limit = ' LIMIT '.$startRow_p.', '.$maxRows_p;
## Start building sql for GET varables for advanced search
###Add city
if(isset($_REQUEST['city']) && ($_REQUEST['city'] != ''))
$search[] = ' city = "'.$_REQUEST['city'].'"';
###Add State
if(isset($_REQUEST['district']) && ($_REQUEST['district'] != ''))
$search[] = ' district = "'.$_REQUEST['district'].'"';
###Add lot size
if(isset($_REQUEST['lot_size']) && ($_REQUEST['lot_size'] != ''))
$search[] = ' perches >= '.$_REQUEST['lot_size'];
$search[] = ' availibility = "0" ';
###implode to search string on ' and ';
$searchStr = #implode(' and ',$search);
$sql = 'select * FROM properties WHERE status="1" and'; ###status=1 and
$sql .= $searchStr;
###Add column sorting
if($_REQUEST['sort'] != '')
$sort = ' order by added asc ';
else
$sort = $_REQUEST['sort'];
### DEBUG
if($debugP) echo 'Advanced Search Sql<hr>'.$sql;
$error['Results'] = 'No results found, please search again';
###}
### Finished Building search sql and execting #####
$sql_with_limit = $sql . $sort . $limit;
if($debugP)
echo "<hr>Property Search with Limit SQL: $sql_with_limit";
###Perform search
$searchResults = mysql_query($sql.$sql_with_limit);
### BUILD OUTPUT ####
if (isset($_GET['totalRows_p'])) {
$totalRows_p = $_GET['totalRows_p'];
} else {
if($debugP)
echo "<hr>Property with out limit SQL: $sql $sort";
$all_p = mysql_query($sql.$sort);
$totalRows_p = mysql_num_rows($all_p);
if($debugP)
echo "<br>Result Rows $totalRows_p";
}
$totalPages_p = ceil($totalRows_p/$maxRows_p)-1;
if($debugP)
echo "<hr>Builting Query String for Limit: ";
###Build query string
foreach($_GET as $name => $value){
if($name != "pageNum_p")
$queryString_p .= "&$name=$value";
}
if($debugP)
echo $queryString_p;
?>
<div align="left" class="locText">Home<span class="locArrow"> > </span> Search Results</div>
<hr size="1" color="#666666">
<table border="0" align="center">
<tr>
<td align="center">
<?php if ($pageNum_p > 0) { ### Show if not first page ?>
< href="<?php printf("%s?pageNum_p=%d%s", $currentPage, 0, $queryString_p); ?>" class="pageLink">First</a> |
<?php } ### Show if not first page ?>
<?php if ($pageNum_p > 0) { ### Show if not first page ?>
< href="<?php printf("%s?pageNum_p=%d%s", $currentPage, max(0, $pageNum_p - 1), $queryString_p); ?>" class="pageLink">Previous</a> |
<?php } ### Show if not first page ?>
<?php if ($pageNum_p < $totalPages_p) { ### Show if not last page ?>
< href="<?php printf("%s?pageNum_p=%d%s", $currentPage, min($totalPages_p, $pageNum_p + 1), $queryString_p); ?>" class="pageLink">Next</a> |
<?php } ### Show if not last page ?>
<?php if ($pageNum_p < $totalPages_p) { ### Show if not last page ?>
< href="<?php printf("%s?pageNum_p=%d%s", $currentPage, $totalPages_p, $queryString_p); ?>" class="pageLink">Last</a>
<?php } ### Show if not last page ?>
</td>
</tr>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="pageText" >Showing: <strong><?php echo ($startRow_p + 1) ?> to <?php echo min($startRow_p + $maxRows_p, $totalRows_p) ?> of <?php echo $totalRows_p ?></strong> Listings</td>
<td align="right" class="pageText"></td>
</tr>
</table></td>
</tr>
<tr>
<td height="5">xx</td>
</tr>
<tr>
<td><table width="100%" border="0" cellspacing="1" cellpadding="4" class="resBorder">
<tr>
<td class="colText">Address</td>
<td class="colText">City</td>
<td class="colText">ST</td>
<td class="colText">Price</td>
<td class="colText">Beds</td>
<td class="colText">Baths</td>
<td class="colText">Sqft</td>
</tr>
<?php while($row_p = #mysql_fetch_assoc($searchResults)) { ?>
<tr valign="top">
<td class="bodytext"><?php echo $row_p['address']; ?></td>
<td class="bodytext"><?php echo $row_p['city']; ?></td>
<td class="bodytext"><?php echo $row_p['district']; ?></td>
<td class="bodytext"><?php echo Money($row_p['price'],1); ?></td>
<td class="bodytext"><?php echo $row_p['rooms']; ?></td>
<td class="bodytext"> </td>
<td class="bodytext"><?php echo $row_p['floor']; ?></td>
</tr>
</table></td>
</tr>
<? } ?>
</table></td>
</tr>
<tr>
<td height="5">xx</td>
</tr>
<tr>
<td><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="pageText"> </td>
<td align="right"></td>
</tr>
</table></td>
</tr>
</table>
<p> </p>
<?
## if no results where found
if(#mysql_num_rows($searchResults)<=0){
foreach($error as $name => $value)
print '<div align=center class="error">'.$name . ': ' . $value.'</div>';
}
##Fetch Footer
?>
<script>
document.getElementById('loading').style.display = 'none';
</script>
Try changing:
###Perform search
$searchResults = mysql_query($sql.$sql_with_limit);
To:
###Perform search
$searchResults = mysql_query($sql_with_limit);

Why does this condition not work?

I've noticed that the first condition does not work
if (empty($ss)) {
echo "please write your search words";
}
but the second does
else if ($num < 1) {
echo "not found any like ";
Full code:
<?php
require_once "conf.php";
$ss= $_POST["ss"];
$sql2=("SELECT * FROM student WHERE snum = $ss");
$rs2 = mysql_query($sql2) or die(mysql_error());
$num = mysql_num_rows($rs2);
if (empty($ss)) {
echo "please write your search words";
}
else if ($num < 1 ) {
echo "not found any like ";
}else {
$sql=("SELECT * FROM student WHERE snum = $ss ");
$rs = mysql_query($sql) or die(mysql_error());
while($data=mysql_fetch_array($rs)) {
?>
<div id="name">
<table align="center" border="3" bgcolor="#FF6666">
<tr>
<td><? echo $data ["sname"]." "."نتيجة الطالب"; ?></td>
</tr>
</table>
</div>
<div id="ahmed">
<table width="50%" height="50" align="center" border="2px" bgcolor="#BCD5F8">
<tr>
<td width="18%"><strong>جيولوجي</strong></td>
<td width="13%"><strong>تاريخ</strong></td>
<td width="13%"><strong>رياضة</strong></td>
<td width="14%"><strong>عربي</strong></td>
<td width="12%"><strong>علوم</strong></td>
<td width="30%"><strong>المادة</strong></td>
</tr>
<tr>
<td>100</td>
<td>100</td>
<td>100</td>
<td>100</td>
<td>100</td>
<td><strong>الدرجة النهائية</strong></td>
</tr>
<td><? echo $data['geo']; ?></td>
<td><? echo $data['snum']; ?></td>
<td><? echo $data['math']; ?></td>
<td><? echo $data['arab']; ?></td>
<td><? echo $data['history']; ?></td>
<td><strong>درجات الطالب</strong></td>
</tr>
<tr>
<td colspan="5" align="center" valign="middle">
<? $sum= $data['geo'] + $data['snum'] +
$data['math'] + $data['arab'] +
$data['history'];
echo $sum ;
?>
</td>
<td><strong>مجموع الدرجات</strong></td>
</tr>
<tr>
<td colspan="5" align="center">
<?
$all=500 ;
$sum= $data['geo'] + $data['snum'] +
$data['math'] + $data['arab'] +
$data['history'];
$av=$sum/$all*100 ;
echo $av."%" ;
?>
</td>
<td><strong>
النسبة المئوية
</strong></td>
</tr>
</table>
</tr>
</div>
<?
}
};
The full code link is:
http://www.mediafire.com/?2d4yzdjiym0
Are you sure that $ss isset? i.e. there is a POST variable with the name ss. you could test it with.
if (empty($ss) || !isset($ss)) {
echo "please write your search words";
}
or test for it when you read in the post var
if ((!isset($_POST["ss"]) || (!is_numeric($_POST["ss"])))
{
$ss = 0;//empty considers 0 as been empty
}
else
{
$ss = $_POST["ss"];
}
ss looks to be a number too, so checking if it is numeric using is_numeric will help stop SQL errors, if for some reason it is not.
Use
if (!isset($ss)) {
echo "please write your search words";
}
instead of
if (empty($ss)) {
echo "please write your search words";
}
Try changing the condition to
if(empty($_POST['ss'])){ ... }
and continue using $_POST['ss'] instead of $ss.
BTW Always use error_reporting(E_ALL) when developing.
$sql=("SELECT * FROM student WHERE snum = $ss ");
Remove the brackets in the variables ($sql1 and $sql2) that have your query
It should be
$sql="SELECT * FROM student WHERE snum = $ss ";
I think that's why its telling you that you have an error near ...

Categories