PHP MySQL Search Doesn't Work? - php

I have made a simple MySQL query search in one of my PHP site, but it doesn't work as I expect. When user search a term in my search bar, if the content he/she looking for doesn't exist, my function should return 'no results'. but it just display blank, no message nothing.
Here is my code for the search:
function querySearch($searchTerm) {
$query = "SELECT * FROM content_en WHERE content_body LIKE '%{$searchTerm}%' ORDER BY id DESC ";
return $query;
}
function getSearch($searchTerm) {
$queryContents= querySearch($searchTerm);
$exeQuery = mysql_query($queryContents);
while( $fetchSet = mysql_fetch_array($exeQuery) ){
if(empty($fetchSet)){
echo "No Results Found";
}else{
if(empty($fetchSet['content_title'])){
echo 'Sorry No results Found';
}else{
echo '<h2>'.$fetchSet['content_title'].'</h2><br/>';
echo '<div>'.shortText($fetchSet['content_body'], 220).'</div><br/><br/>';
}
}
}
}
Just my forcing it to work , so that's why there are two check for fetchSet array one for whole array one for only one key. But yea it doesn't work.

The reason it's not working is because there is either an error in your query or it has returned no results.
First, you should add some sort of error handling to your mysql_query, like this:
$exeQuery = mysql_query($queryContents) or die(mysql_error());
Second, the reason it would never print anything out if no results are found is because mysql_fetch_array will only loop over the results if there is a result to obtain. Therefore, if 0 rows are returned, the whole while loop is skipped completely. Instead you can use mysql_num_rows BEFORE you loop.
For example:
if (mysql_num_rows($exeQuery) > 0) {
while( $fetchSet = mysql_fetch_array($exeQuery) ){
echo '<h2>'.$fetchSet['content_title'].'</h2><br/>';
echo '<div>'.shortText($fetchSet['content_body'], 220).'</div><br/><br/>';
}
}
else {
echo "No Results Found";
}

Try this code
function querySearch($searchTerm) {
$query = "SELECT * FROM content_en WHERE content_body LIKE '%{$searchTerm}%' ORDER BY id DESC ";
return $query;
}
function getSearch($searchTerm) {
$queryContents = querySearch($searchTerm);
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows($exeQuery) > 0)
{
while( $fetchSet = mysql_fetch_array($exeQuery) )
{
echo '<h2>'.$fetchSet['content_title'].'</h2><br/>';
echo '<div>'.shortText($fetchSet['content_body'], 220).'</div><br/><br/>';
}
}
else
{
echo "No Results Found";
}
}

I'm not 100% sure about this, but I do recall that mysql_fetch_array will work only if there are actual results fetched. The while loop will only run when the mysql_fetch_array function runs successfully. However, when the query returns no results, mysql_fetch_array will not run successfully, so the loop will not run, thus, your if block is not given the opportunity to run either.
Edit: Habeeb's code should fix your problem for you :p. Keeping my answer here though, since I do provide some explanation as to the problem with your code. I'm sure it will be a useful reference to someone who might look at this in the future.

Try This one..
function querySearch($searchTerm) {
$query = "SELECT * FROM content_en WHERE content_body LIKE '%{$searchTerm}%' ORDER BY id DESC";
return $query;
}
function getSearch($searchTerm) {
$queryContents= querySearch($searchTerm);
$exeQuery = mysql_query($queryContents);
$num_rows = mysql_num_rows($exeQuery);
if($num_rows)
{
while( $fetchSet = mysql_fetch_array($exeQuery) ){
echo '<h2>'.$fetchSet['content_title'].'</h2><br/>';
echo '<div>'.shortText($fetchSet['content_body'], 220).'</div><br/><br/>';
}
}else{
echo "No Result Found!";
}
}

Related

beginner php mysql - return boolean if row contain specific value [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 5 years ago.
Ok so basically I'm trying to create a simple web app
I want to check if one element is inside the table, and if inside I want to return a boolean value, like for example if "abc" is inside the table named "name" then return YES.
Here's my code, not working:
error_reporting(E_ALL);
$mysql = mysqli_connect(/* PRIVATE DATA */) or die ("ERROR CONNECTING TO THE DB");
if(isset($_POST['submit'])) {
$theAddress = $_POST['youtubeURL'];
$result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";
$query = mysqli_query($mysql, $result);
if (!$query) {
printf("Error");
} else {
printf("NO ERROR");
}
AND HERE'S THE NON-WORKING PART :
while($row = mysqli_fetch_array($query)) {
if ($row == 0) {
echo "NO RESULT LIKE THIS";
}else {
echo "AT LEAST ONE RESULT LIKE THIS";
}
}
}
First, learn to use parameters queries. They really are no harder to use than stuffing a string value into a query.
Second, if you want to know if something exists, then write the query just to do that. The simplest query is probably:
SELECT EXISTS (SELECT 1 FROM data WHERE youtubeURL = ?) as exists_flag
This will return 1 if something matches. Just run the query and read the single value that is returned.
Note that returning select * to check for existence is an anti-pattern. You are returning way more data from the database than you need (both in terms of rows and columns). That is usually not a good idea.
It should be like this.
//in case you want to see total of the wors
if(mysqli_num_rows($query) == 0) {
echo "NO RESULT LIKE THIS";
} else {
echo "AT LEAST ONE RESULT LIKE THIS";
}
//in case you want to check for each of the row
while($row = mysqli_fetch_array($query)) {
if (empty($row)) {
echo "NO RESULT LIKE THIS";
} else {
echo "AT LEAST ONE RESULT LIKE THIS";
}
}
You need to use mysqli_num_rows to count the rows ..
$result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";
$query = mysqli_query($mysql, $result);
if(mysqli_num_rows($query)) {
echo "AT LEAST ONE RESULT LIKE THIS";
} else {
echo "NO RESULT LIKE THIS";
}

mysqli_conn->query... is not giving any results when put inside for loop

I am unable to get result from the "$mysqli_conn->query" statement which is included in a for loop as shown in the code. The reason I am using for-loop is simple and can be judged from the code itself.
$name=$_SESSION["names"];
$size=sizeof($name);
for($i=0; $i<$size; $i++) {
//echo $name[$i]; //for testing
$bname = $name[$i];
$results = $mysqli_conn->query("SELECT product_name, product_code FROM products_list WHERE product_name='$bname'");
if ($row = $results->fetch_assoc()) {
echo $row["product_name"]."<br>";
}
else echo "I am Going Wrong way !!</br>";
}
The output I am getting is : "I am Going Wrong way !!"
I also checked the contents of $_SESSION["names"]. Everything seems to be correct except the results.
You're simply assuming your query can never fail, which is a very bad thing. You are vulnerable to sql injection attacks. you are also simply assuming that your queries will ALWAYS return a result. if there's no rows available, fetch will return false, which you then treat as "wrong way".
At bare minimum, you should have a structure like this:
for(...) {
$results = $mysqli_conn->query($sql);
if (!$results) {
die($mysqli_conn->error());
}
if ($results->num_rows != 0) {
$row = $results->fetch_assoc();
} else {
echo 'no results';
}
}

Not enter while loop after mysql_fetch_assoc

please take a look at this code :
$sql = "SELECT * FROM shop";
$result = mysql_query($sql);
echo $result;
echo "before lop";
while ($xxx = mysql_fetch_assoc($result)) {
echo "inside lop";
echo $xxx['column_name'];
}
echo "after lop";
When I run such code i receive :
Resource id #244
before lop
after lop
It did not enter while lop, and I really don't know why :(
I used before such code and there were no problems.
Can someone help me?
$sql = "SELECT * FROM shop";
$result = mysql_query($sql) or die(mysql_error());
echo mysql_num_rows($result);
Check how many records are present in your shop table. I think shop table is empty.That is why not entering in the while loop.
You can do like this
$count = mysql_num_rows($result);
if($count > 0) {
while ($xxx = mysql_fetch_assoc($result)) {
echo $xxx['column_name'];
}
}
I would guess that the call to mysql_fetch_assoc() has returned false, possibly due to no results being returned from the database, this would cause the while loop to not execute even once. I would check the output of var_dump(mysql_fetch_assoc($result)) to ensure that data has been returned.

PHP - Why is looping between WHILE and DO-WHILE give different results in mysql fetching?

I have one record in a table in my mysql database. I use the following PHP code to retrieve data:
$result = mysql_query($query = "SELECT realname FROM t_user");
if($result)
{
while($data=mysql_fetch_assoc($result)){
echo $data['realname'];
}
}
the results do not appear, but when I use a do-while loop like below:
if($result)
{
$data=mysql_fetch_assoc($result);
do{
echo $data['realname'];
} while($data=mysql_fetch_assoc($result));
}
the results appear, then I tried to add one more record to the table, in the while loop, only shows one data record (the first record), and the do-while loop displays all the data. Why is that? Is it because there is my code wrong?
The code you have shown can't possibly exhibit this problem, so the logical explanation is this:
$result = mysql_query($query = "SELECT realname FROM t_user");
if($result)
{
// Something fetched a row from $result before this statement is run
while($data=mysql_fetch_assoc($result)){
echo $data['realname'];
}
}
Seeing how you're comparing two similar codes, you may have accidentally written something in between the two:
if($result)
{
mysql_fetch_assoc($result);
while($data=mysql_fetch_assoc($result)){
echo $data['realname'];
}
}
$result = mysql_query($query = "SELECT realname FROM t_user");
if($result) { while($data=mysql_fetch_assoc($result)){
echo $data["realname"]; } }
$result = mysql_query($query = "SELECT realname FROM t_user");
var_dump($data);die;
see the result array in your browser. the above while loop should work. check your result.

Making a Message Appear if the Results of a Query Are Zero

I have a variable called $uid, and I would like to print a message if the variable $uid is not contained in the "loginid" field of a MySQL table "tweets" on any row that has another variable, $submissionid. I think my query $tweetquery is okay. Basically, I would like the message to echo if the loginid variables pulled from "tweets" never equal $uid.
How can I do this?
Thanks in advance,
John
$tweetquery = "SELECT loginid
FROM tweets
WHERE submissionid = '$submissionid'";
$tweetresult = mysql_query($tweetquery);
if...
echo '<div>Message</div>';
Have a look at mysql_num_rows($result).
if ( mysql_num_rows($result) > 0 )
{
// Do something
}
else
{
echo 'No results';
}
Call me crazy, but using mysql_num_rows is not the way I'd do this. mysql_fetch_array does not do anything destructive if nothing is returned, so call that as normal.
$row = mysql_fetch_array( $resource );
if(!$row)
{
//do what you would do if the query returned nothing
}
else
{
do
{
// do what you would do with the row
} while( $row = mysql_fetch_array( $resource ) );
}
The problem with mysql_num_rows is that it actually represents a call to the database asking for how many rows exist in the pointer. It is a, frankly, needless back-and-forth which can easily be avoided. So why not avoid it?
You can use mysql_num_rows:
if (mysql_num_rows($tweetresult) > 0)
// results found
Use mysql_num_rows():
if (mysql_num_rows($tweetresult) == 0) {
echo 'Message';
}
if(mysql_num_rows($tweetresult) == 0)
echo "<div>Message</div>";
else {
//Do something if $uid was found
}
mysql_num_rows() returns the numbers of rows fetched from the database. If rows fetched are zero echo a message.
$tweetquery = "SELECT loginid
FROM tweets
WHERE submissionid = '$submissionid'";
$tweetresult = mysql_query($tweetquery);
if(mysql_num_rows($tweetresult) > 0){
// your results here
} else {
echo '<div>Message</div>';
}

Categories