Displaying message when no results found in PHP MySQL search - php

I have a PHP search script which queries a MySQL database. Currently, when no results are displayed the script shows and error. How can I make it display a message like "No Results were found" when nothing is returned?
My PHP script is:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM links WHERE `title` LIKE '%{$query}%' LIMIT 8";
$searchResult=mysql_query($searchSQL);
while ($row=mysql_fetch_assoc($searchResult)){
$results[]="<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></div>";
}
echo implode($results);
}
?>

if (empty($results)) {
echo 'No results found';
} else {
echo implode($results);
}

Create a MYSQL Connection and paste this code below
$sql="SELECT * FROM tablename WHERE columnname LIKE your variable or constant ";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count>=1){if result was found}
else {if result was not found}
?>

You could count the number of elements in the array, and either continue with your implode or display the message you mentioned.
<?php
if(count($results) > 0){
echo implode($results);
}
else {
echo "No results were found.";
}
?>
You also really should not be using the mysql_* functions. Use either the improved version (mysqli_*) or PDO.

Try the following:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM links WHERE `title` LIKE '%{$query}%' LIMIT 8";
$searchResult=mysql_query($searchSQL);
if(mysql_num_rows($searchResult) <= 0)
{
echo "No results";
} else {
while ($row=mysql_fetch_assoc($searchResult)){
$results[]="<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></div>";
}
echo implode($results);
}
}
?>
Also please either use MySQLi or PDO as it is safer and better to use, some information can be found below. Personally I prefer MySQLi but prepared statements in PDO is really good and saves some lines of code every time you query ;)
MySQLi and PHP
PDO and PHP

<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query = mysql_real_escape_string(trim($_GET['q']));
$searchSQL = "SELECT * FROM links WHERE `title` LIKE '%{$query}%' LIMIT 8";
$searchResult = mysql_query($searchSQL);
// the query was run successfully
// and it returned at least a result
if(is_resource($searchResult) && mysql_num_rows($result) > 0){
while ($row=mysql_fetch_assoc($searchResult)){
$results[]="<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></div>";
}
echo implode($results);
} else{
echo 'No Results were found';
}
}
?>

You could also use the function mysql_num_rows, which will tell you the number of rows returned by your query.
$rows = mysql_num_rows($searchResult);
if($rows <= 0){
/* Code if there are no rows */
}
else{
/* At least one row has been found */
}

if (mysql_num_rows($searchResult) == 0) {
echo "some error message";
} else {
... process data
}

How about a simple counter in the while statement:
$i = 0;
while (condition) {
$i++;
do stuff;
}
if ($i ==0) {echo 'No results found';}

Related

Select from multiple MySQL tables

i'm trying to select value from different tables but i face some errors in the result i want to check if there is any values i will echo "Yes" otherwise echo "No"
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username=$_POST['username'];
require_once('dbConnect.php');
$sql="SELECT donator.national_id, needy_people.national_id".
"FROM donator, needy_people".
" WHERE donator.national_id='$username' OR needy_people.national_id='$username' limit 50";
$result=mysqli_query($con,$sql);
if($check>0){
while($row=mysql_fetch_array($sql)){
$check=mysqli_fetch_array(mysqli_query($con,$sql));
}
}
if(isset($check)){
echo'YES';
}else{
echo'Noooo';
}
mysqli_close($con);
}else{
echo'error';
}
can anybody solve this problem help!
When you put as condition if($check>0), $check is not defined yet, so it won't be processed, hence $check stay unset.
Also you should use the empty() function to test existence of values in it
If you're trying to check if a row exists when you run your query consider using the function mysqli_num_rows
if (mysqli_num_rows($result) > 0) {
echo "Has row";
}
$count=mysqli_num_rows($check);
if($count>0)
echo "yes";
else
echo "no";

Inserting a HTML code in between MySQL results

I want to insert a html code in between MySQL results.
My query
if($sql = $mysqli->query("SELECT * FROM table Limit 20")){
$row = mysqli_fetch_array($sql);
//Results display here
$sql->close();
}else{
printf("There seems to be an issue. Please Trey again");;
}
Above query is pulling 20 results at a time. I want to insert <div class="block"></div>after pulling 3rd result and continue other results after that div (using a single query)
Can anyone point me how to do this.
As it simple as it gets.
You just have to count each iteration and when it reaches 3 you print out the div element.
<?php
$mysqli = new mysqli("localhost","","","");
if ($mysqli->connect_errno){
echo "Failed to connect to MySQL";
}
if ($result = $mysqli->query("SELECT * FROM table")) {
$counter = 0;
while ($row = $result->fetch_assoc()) {
echo $row["______"];
if((++$counter) == 3) {
echo '<div class="block"></div>';
}
}
$result->close();
}
$mysqli->close();
?>

Search works properly, only first result not shown

Title should make the problem clear. The search function works as intended, but what should be the first hit will not show at all and i don't know why. Here's the code:
<form action="admin_orders_search.php" method="GET">
<input type="text" name="query" value="Search"/>
</form>
<?php
$query = $_GET['query'];
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$sql = "SELECT * FROM orders WHERE 1";
$matches = preg_split('/\s+/',$query);
foreach($matches as $match){
$sql .= " AND `ship_eta` LIKE '%".$match."%'";
}
$raw_results = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){
while($results = mysql_fetch_array($raw_results))
{
// ---- RESULTS START ---->
$res=mysql_query("select * from orders ".$qry." order by id desc ");
while($row=mysql_fetch_array($raw_results))
{ ?>
// here are the hits shown
}
// ---- RESULT END ---->
}
}
else{
echo "No hits";
}
?>
In the code:
$res=mysql_query("select * from orders ".$qry." order by id desc ");
while($row=mysql_fetch_array($raw_results))
{
//results here
}
You still use the variable $raw_results. I think you want to use the variable $res since you already have a while with the $raw_results
Ive found some unused lines in the code and after removing them it works! The affected lines are these:
...
if(mysql_num_rows($raw_results) > 0){
// ---- RESULTS START ---->
while($row=mysql_fetch_array($raw_results))
{ ?>
// here are the hits
}
// ---- RESULT END ---->
}
else{
echo "No hits";
}
}
else{
echo "error: ".$min_length." needed minimum!";
}
?>
// ---- SEARCH END ---->
<?php
}
}
?>

Echo statement in PHP not executing in a specific manner

I'm having a problem with some specific PHP code that I've been working on for a few days. It's meant to be a reporting code where I can input a day and a month and it will list the total sales of that particular day.
But, I can't seem to make the last statement whereby, if there are no values(there are no data) in the query, it will display 'No Sales on this particular day'. Here's the code I've been working on. But the last echo statement is not executing. Any ideas?
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
$day=#$_POST['day'];
$month=#$_POST['month'];
echo "<center><h2>Sales report on " .$day. "." .$month. ".2013</h2></center>";
echo "<center><table style='border:2px solid black;' align=center width=600>";
echo "<tr><th colspan=12><center><h2>Sales Report</h2><hr size='2' color='black' /></center></th></tr>";
echo " <th width=400> Amount Collected</th>";
?>
<br>
<?php
$x = 1; //counter
//open a connection to a MySQL server using function mysql_connect
//returns a MySQL link identifier on success, or FALSE on failure.
$conn= mysql_connect("localhost","root","");
if (!$conn)
die ("Connection error: ".mysql_error());
else {
//select a MySQL database
//returns TRUE on success or FALSE on failurue.
$db=mysql_select_db("cqfos");
if(!$db)
die ("DB not found: ".mysql_error());
else {
//put query in a variable $query
$query= "select ROUND(sum(orderdetails.tprice),2)
from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '$day' AND MONTH(orders.date) = '$month'";
$result=mysql_query($query);
if(!$result)
die ("Invalid query: ".mysql_error());
//if record exists
else {
//fetch a result row as both associative array and numeric array
if(mysql_num_rows($result)== 1){
while ($row=mysql_fetch_array($result,MYSQL_BOTH)){
echo "<tr>";
echo "<td align='center'>RM ".$row[0]."</td></tr>";
$x++; //increase the counter
}
}
else {
echo "<tr><th colspan=12>No sales made.</td></tr>";}
}
}
}
echo"</table></center>";
?>
Several problems here
your HTML table syntax is incorrect, and your using an old sql library - and it dose not look like your SQL syntax is right... try this code (not tested as I don't have your data)
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
echo '<div style="margin:auto; textalign:center;">';
echo "<h2>Sales report on " .$_POST['day']. "." .$_POST['month']. ".2013</h2>";
echo "<h2>Sales Report</h2>"
echo "<table style='border:2px solid black;' align=center width=600>";
echo "<tr><th width=400> Amount Collected</th></tr>";
?>
<br>
<?php
$conn = new mysqli("localhost","root","","cqfos");///use mysqli, not mysql : mysql is depricated
if ($conn->mysqli)
exit ("Connection error: ".$conn->errno ." : " $conn->error);
else {
//put query in a variable $query
$eDay = $conn->mysql_real_escape_string($_POST['day']);//escape these to protect the database
$eMonth = $conn->mysql_real_escape_string($_POST['month']);;//escape these to protect the database
//your column name is probably not a rounded value, replaced it with * (return all columns)
$query= "select * from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '"
.$eDay."' AND MONTH(orders.date) = '".$eMonth."'";
$result=$con->query($query);
if($conn->errno)
exit ("Invalid query: ".$conn->errno ." : " $conn->error);
//if record exists
else {
$numericArray = $result->fetch_array(MYSQLI_NUM); //fetch a result row as numeric array
$associativeArray = $result->fetch_array(MYSQLI_ASSOC); //fetch as an associtive array this is not used, just an example
$bothArray = $result->fetch_array(MYSQL_BOTH); //both associtive and numeric this is not used, just an example
}
if(!empty($numericArray))
{
foreach ($numericArray as $value) {
echo "<tr><td>RM ".$value[0]."</td><tr>";//is there more then 1 col? if not you should consider an html list
}
} else {
echo "<tr><td>No sales made</td><tr>";
}
echo"</table></center>";
}
?>
Your SQL (likely) returns more than only one row, so change the line I mentioned before to this:
if(mysql_num_rows($result)>0){
Just letting you know your code is vulnerable to SQLi because you have not sanitized $day and $month. Also please consider using PDO.
If you haven't already - Try running the SQL statement into PHPMyAdmin and see where it outputs the error (if there is one), else it will output the data.*
*Manually inputting the day/month substituting for the variables.

Error message in PHP when there's no data via MYSQL?

I've got a php file fetching some data from a MYSQL database. This is my code so far:
<?php
include 'DB.php';
$connection=mysql_connect(DB_SERVER,DB_USER,PASS);
$db=mysql_select_db(DB_Name);
$sql="select * from lookup where id = ".$_GET['id'];
$res=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
?>
What would I have to add so that if there was no data, there'd be an error message? I'm guessing an If/else statement but I'm not sure how to fit it in with the while syntax.. any help?
$res = mysql_query(...) ...;
if (mysql_num_rows($res) == 0) {
die("Hey, nothing here!");
}
Beyond that:
a) you're utterly vulnerable to SQL injection attacks. Stop your coding project and learn about them before you go any further.
b) stop using the mysql_*() functions. They're deprecated.
You can use $count = mysql_num_rows($res); to get the number of rows returend. Then you can use an if statement to display whatever error.
I did it like mentioned above:
$query = "select * from lookup where id = ".$_GET['id'];
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 0){
echo "nothing here</br>";
}
else{
echo "<b> $num_results </b> result(s) match your query</br>";
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
You can of course leave the "echo $num_results..." out, but there you can give the number of results, which is sometimes quite useful.

Categories