Check if no result found in mysql db [duplicate] - php

This question already has answers here:
Checking if mysqli_query returned any values?
(2 answers)
Closed 4 months ago.
I wrote a php search for a table in mysqli and it works fine but i want to show the correct message to user if no result were found.
here is my current code:
$search_string=$_GET["design"];
$connect= mysqli_connect("mysql.myhost.com","abc","123456","mydb_db");
$query="select * from product where product_design like '%$search_string%'";
$rows= #mysqli_query($connect,$query) or die("Error: ".mysqli_error($connect));
if ($rows!=null)//I put this if to check if there is any result or not but its not working
{
while(($record=mysqli_fetch_row($rows))!=null)
{
.
.//i have working code for showing the result here
.
}
mysqli_close($connect);
}
else{
echo"no result found";
}
could you please help me what is wrong , even when i search for something which is not exist in the db still the program not displaying "no result found"
Thank you

What you need is mysqli_num_rows specifically the mysqli_result::num_rows bit. This adds a num_rows property to mysqli result sets. This means you can do
$rowCount = $rows->num_rows
There's also a non-OO equivalent ...
$rowCount = mysqli_num_rows($rows);
(The difference is purely one of coding style)
Use one of these to determine how many records are returned and output the appropriate messages.

The following line doesn't make sense, that might be the issue.
while(($record=mysqli_fetch_row($rows))!=null)
However, $row wouldn't return 'null' if it was empty, but be not set. Do it like this:
if ($rows) { echo 'works';} else { echo 'no rows'; }

Related

PHP - mysqli_query count always returns 1 [duplicate]

This question already has answers here:
Check if form-posted variable is existing in one of MySql columns [closed]
(3 answers)
Closed 7 years ago.
I am a kind of a beginner in this ...
For some reason This mysqli_query count always returns 1
$class_number = $_POST['class'];
$check_class_number = mysqli_query($con, " SELECT * FROM `Academy` WHERE ClassNumber = '".$class_number."' ");
echo count($check_class_number);
The current situation in my MySql table:
1- I have only two rows
2- Under the column ClassNumber I have the same value 150701-100
I simply need to count the number of the ClassNumber 150701-100, which suppose in my case to returns 2. However as I mentions it always returns 1, even if I added more rows.
My final intention is to add this logical if to the code
if(count($check_class_number)>0){
echo "exists.";
}else{
echo "It does not exist.";
}
Your help is much appreciated.
Use mysqli_num_rows to count the number of rows returned from the query. count() will only work on an array.
if(mysqli_num_rows($check_class_number)>0) {
echo "exists.";
} else {
echo "It does not exist.";
}
you can do as OllyTenerife, or use $check_class_number to get the num of rows.
if($check_class_number->num_rows > 0)
{
doSmt();
}
else
{
echo "Does not exist.";
}

Creating a search box in dreamweaver for website PHP

im creating a website and within the website there will be a search box that will let you search for items on your website. I have code but i keep getting an error message.
<?php
include 'connect.php';
$search = $_POST['search']."*";
$search_query = $link->prepare("SELECT name FROM products WHERE MATCH(name)
AGAINST (? IN BOOLEAN MODE)")
$search_query->bind_param('s', $search);
$search_query->execute();
$search_query->store_result();
$search_rows = $search_query->num_rows;
$search_query->bind_result($product_name);
if($search_rows > 0){
while($search_query->fetch()){
echo "Your search returned $search_rows results";
echo $product_name."<br>";
}
} else { echo "Your search returned no results, sorry :("; }
is it possible to run a search using a mysql query from the database to return searches??
Any advice would be deeply appreciated.
Thanks
The error is most probably because of your syntax.
$search_query->store_result();
$search_rows = $search_query->num_rows;
$search_query->bind_result($product_name);
Here, you are first trying to store the results and later binding the results to variable $product_name which leads to the said error.
The bind_result states:
Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
That code needs some work.
That loop looks flawed. Try something like this:
echo "Your search returned $search_rows results";
while($search_query->fetch()){
echo $product_name . "<br>";
}

Recursive function returns nothing [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I have a database full of autopart numbers that needs old part numbers prices updated. Each row features a part number (field name "master") a price and a field with superseded (newer) part numbers (field name "pnc"). The script needs to check if the "pnc" field isn't empty. If it's not, it should go and grab the price for that number. Easy enough.
However, some part numbers have an unknown level of numbers to go through until it reaches the most current part number and price. So, I figured a recursive function would be the best solution. However, it's not working correctly. Here's the code:
public function updatePricing()
{
//method to update pricing by referencing supersession prices
$sql = "SELECT * FROM prices";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
for($i=0;$i<2000;$i++) //using 2000 for testing, use $num_rows after
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$super_num = $row['pnc'];
//if there is a supersession in this row find original
if(!empty($super_num))
{
$final_super_price = $this->findSuperPrice($super_num);
echo "partnum: " . $row['master'];
echo " ";
echo "price: " . $final_super_price . "<br /><br />";
}
}
}
public function findSuperPrice($part_num)
{
$sql = "SELECT * FROM prices WHERE master='" . $part_num . "'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if (empty($row['pnc'])) //if there aren't any supersession numbers
{
$final_price = $row['list'];
return $final_price;
}
else //recursively call itself until we find the last number
{
$this->findSuperPrice($row['pnc']);
}
}
What's happening is the updatePricing() function runs until it finds a row that has an entry in the "pnc" field. When it does, the findSuperPrice() function is called. The findSuperPrice() function should run recursively until the "pnc" field is empty. When that happens a number is returned.
However, if it actually reaches the else part of the if statment in findSuperPrice(), it doesn't return anything. Basically, if it's more than one level deep. I'm not getting any errors, it's just returning a blank statement. I've verified there is information there that it should be returning also. Thanks.
Also, I should mention this is inside of a larger class. The rest of the class has no bearing on these two methods.
You need to return a value. Change this code:
else //recursively call itself until we find the last number
{
$this->findSuperPrice($row['pnc']);
}
To this:
else //recursively call itself until we find the last number
{
return $this->findSuperPrice($row['pnc']);
}
You currently do not get a return value because the result of findSuperPrice is ignored if $row['pnc'] is not empty. Correctly return the value of the recursive calls:
return $this->findSuperPrice($row['pnc']);
You are missing a return statement in the else case inside findSuperPrice.
But... it looks like you are pumping a whole lot of data to look at/manipulate only a single field. You could also write function in mysql, similar to the one I posted here: MySQL: Get Root Node of Parent-Child Structure
That could enable you to query the required value directly from the database. If you have the structure for your tables I'd be happy to help out.

How to list rows for a query or display 'no records' using a single query

How to list records for a query and to display "no records" when no rows returned using a single query?
Currently I am using a COUNT(*) query or using mysql_num_rows() function; then another query in different result set to list data. Can you tell me if it is possible to accomplish the same with a single query?
Important: I assume that the OP uses PHP as (s)he mentions mysql_num_rows. And I hope (s)he will tell me if I am wrong.
It is your job in PHP to check whether the result is an empty set or not. I don't understand why you have to do another query. Maybe you have to clarify your question.
Here a more complete example:
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
// If if result set contains rows
if(0 == mysql_num_rows($result)) {
echo 'no records';
}
else { // Loop over the result set
while(row = mysql_fetch_array($result)) {
// do whatever you want with the data here
}
}
Reference: mysql_num_rows, mysql_fetch_array
Even if you don't use PHP, the approach is the same in other languages and there should be similar functions available.
why do you need another query after mysql_num_rows?
why not to just run your query and then check results with mysql_num_rows?
Try Something like following
if (mysql_num_rows == '0')
'No Records'
else
//YOUE CODE HERE

Is mysql_num_rows efficient and/or standard practice?

A while ago I was poking around with SQLite, trying to port some of my sites to use it instead of MySQL. I got hung up on the lack of a function to count results, like PHP's mysql_num_rows(). After searching a little I discovered this mail list, which says (as I understand it) that SQLite doesn't have that functionality because it's inefficient. It states that it is bad form to write code that needs to know how many rows are returned.
I generally use mysql_num_rows to check for empty return results. For example:
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
}
} else {
echo "<p>No results found</p>";
}
The vehement distaste for the concept of mysql_num_rows() in the SQLite community makes me wonder if it's that terribly efficient for regular MySQL in PHP.
Is there a better, more accepted way for checking the size of a MySQL result set in PHP besides mysql_num_rows()?
EDIT:
I'm not just using mysql_num_rows to get the count--I would use a COUNT query for that. I'm using it to check if there are any results before outputting everything. This is useful for something like displaying search results - it's not always guaranteed that there will be results. In SQLite world, I have to send one COUNT query, check if there is something, and then send a SELECT query to get everything.
You already have something that is telling you if you've got results in mysql_fetch_array(). It returns false if there are no more rows to fetch (from php.net).
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if($results) {
$row = mysql_fetch_array($results);
if($row) {
do {
echo "<p>{$row[whatever]}</p>";
} while($row = mysql_fetch_array($results));
} else {
echo "<p>No results found</p>";
}
} else {
echo "<p>There was an error executing this query.</p>";
}
Regardless of whether or not you actually use what you SELECTed, all of the rows are still returned. This is terribly inefficient because you're just throwing away the results, but you're still making your database do all of the work for you. If all you're doing is counting, you're doing all that processing for nothing. Your solution is to simply use COUNT(*). Just swap COUNT(*) in where you would have your SELECT statement and you're good to go.
However, this mostly applies to people using it as a complete substitute for COUNT. In your case, the usage isn't really bad at all. You will just have to manually count them in your loop (this is the preferred solution for SQLite users).
The reason being is in the underlying SQLite API. It doesn't return the whole result set at once, so it has no way of knowing how many results there are.
As explained on the mailing list you found. It is inefficient to return the count of rows because you need to allocate a lot of memory to hold the entire (remaining) result set. What you could do, is to simply use a boolean to test if you have output anything.
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
$empty_result = true;
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
$empty_result = false;
}
if ($empty_result) {
echo "<p>No results found</p>";
}

Categories