How to display "no results found" on mysqli_fetch_assoc? - php

I am trying to display a message when the search finds 0 results. I have tried several different ways to do it but nothing works; I always get a blank page or manage to display the message even when search finds results.
The code:
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
isset($post['Näytön_aste']) &&
isset($post['Vaikutusten_vahvuus']) &&
isset($post['Käyttökelpoisuus']))
{
$Kohderyhmä = $post['Kohderyhmä'];
$Näytön_aste = $post['Näytön_aste'];
$Vaikutusten_vahvuus = $post['Vaikutusten_vahvuus'];
$Käyttökelpoisuus = $post['Käyttökelpoisuus'];
}
else
{
echo '<!-- Virhe -->'; /*die ('<h2>Ei hakutermiä syötetty. Avaa haku</h2>');*/
}
$count = 0;
$and = "";
$query = "";
if (!empty($Kohderyhmä) && $Kohderyhmä !="Kaikki" ) {
if ($count > 0) {
$and = " AND ";
}
$count++;
$query = $query.$and."`Kohderyhmä` LIKE '%".$Kohderyhmä."%'";
}
if (!empty($Näytön_aste) && $Näytön_aste !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Näytön aste` LIKE '%".$Näytön_aste."%'";
}
if (!empty($Vaikutusten_vahvuus) && $Vaikutusten_vahvuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Vaikutusten vahvuus` LIKE '%".$Vaikutusten_vahvuus."%'";
}
if (!empty($Käyttökelpoisuus) && $Käyttökelpoisuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Käyttökelpoisuus` LIKE '%".$Käyttökelpoisuus ."%'";
}
if ($count > 0) {
$query = "SELECT * FROM `tietokanta` WHERE ".$query;
} else {
$query = "SELECT * FROM `tietokanta`";
}
//echo $query;
if ($results = $conn->query($query)) {
while ($row = $results->fetch_assoc()) {
echo '<h3>' . $row['Nimi'] . '</h3>';
echo $row['Kokonaisarvio'] ."<br /><br />";
echo $row['Kuvaus'] ."<br /><br />";
}
} else {
echo '<h2>Haku ei tuottanut yhtään tulosta. Muuta hakuehtoja ja hae uudestaan.</h2>';
}

I have tried to find tutorials and other tips from the internet and php.net pages but I can't find a working solution.
That is quite strange because this question is asked every week. Not to mention you can read on mysqli_query's manual page that this function's return value is always positive, no matter whether it was found anything or not
Change your code to this
if ($results = $conn->query($query)->fetch_all(MYSQLI_ASSOC)) {
foreach ($results as $row) {
echo '<h3>' . $row['Nimi'] . '</h3>';
echo $row['Kokonaisarvio'] ."<br /><br />";
echo $row['Kuvaus'] ."<br /><br />";
}
} else {
echo '<h2>Haku ei tuottanut yhtään tulosta. Muuta hakuehtoja ja hae uudestaan.</h2>';
}

Try this following code
$results = $conn->query($query);
if ($results->num_rows >= 1){
while ($row = $results->fetch_assoc()) {
echo '<h3>' . $row['Nimi'] . '</h3>';
echo $row['Kokonaisarvio'] ."<br /><br />";
echo $row['Kuvaus'] ."<br /><br />";
}
}
else{
echo '<h2>Haku ei tuottanut yhtään tulosta. Muuta hakuehtoja ja hae uudestaan.</h2>';
}

Related

Displaying MySQL results in two columns (editing existing code)

I have been asked to revise an existing site, it's still using PHP5.3 and an old version of PHPmyDirectory, and the code is a little messy.
I'm trying to revise it to just display the list of cities in two columns. I'm trying to do it as a table, as it seemed easiest, but I could also just pull the results into to side by side divs, as there are never more than 26 cities listed (so first half or first 13 in div one, the rest in div two).
Here's the existing original code (I know its not mysqli, but we'll be redoing this site shortly so there's no sense trying to redo a million pages of code right now):
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
return $output;
}
This is what is looks like currently: Current Site
Here's what I've tried to do:
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$result_array = array();
while ($service = fetch_array($result)) {
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2) {
break;
}
else {
while ($service2 = fetch_array($result2)) {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
echo "<table>";
for ($j=0; $j<$i; $j=$j+2) {
echo "<tr>";
echo "<td>".$title_array[$j]."</td><td>".$title_array[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<p><b>".$title." will travel for an additional fee!</b></p>";
}
else {
$output .="";
}
}
return $output;
}
And here's what I'm getting: DEV site
I'm very much a PHP newbie, and my understanding is pretty spotty, but I've tried a bunch of different solutions I've found here, and can't get them to work. I'm sure I'm missing something obvious.
Thanks for any pointers!
if I got it correct you should change your
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
with
else {
$output = "<table>";
$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "";
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<tr><td>'."{$service2['title']}".'</td>';
$even_odd=false;
} else {
$output .= '<td>'."{$service2['title']}".'</td></tr>';
$even_odd=true;
}
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
if (!$even_odd)$output .="<td></td></tr>";
$output .="</table>";
}
}
Try this, I couldn't test it of course, since I've got no access to the data being loaded.
echo "<table>";
$result_array = array();
while ($service = fetch_array($result))
{
//this will loop multiple times. 7 times for Tony S. in the example.
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2)
{
break;
}
else
{
while ($service2 = fetch_array($result2))
{
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
}
}
for ($j=0; $j < count($result_array); $j++)
{
if ($j % 2 == 0)
{
echo "<tr>";
}
echo "<td>".$result_array[$j][0]." (".$result_array[$j][1].")</td>";
if ($j % 2 == 0)
{
echo "</tr>";
}
if ($j % 2 == 1 && $j == count($result_array)-1)
{
echo "<td></td></tr>";
}
}
echo "</table>";
Paste and replace between this lines:
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
.... PASTE IN HERE ....
}
Building on Kim's code, I was able to get it working with some revisions. I also scrapped the table for divs, since it seems less messy to me and it seemed like the table styling was interfering somehow.
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
} else {
$output = "<div>";
//$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<div style="float:left;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=false;
} else {
$output .= '<div style="float:right;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=true;
}
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<div style='clear:both;width:90%;float:none;'><p><b>".$title." will travel for an additional fee!</b></p></div>";
} else {
}
}
return $output;
}
Thanks so much Kim and Mouser!

Why can't I echo all variables correctly?

Edited, please scroll down
I am trying to display 3 variables which consist of data stored in a SQL database. However, only the first gets echoed successfully (topLeftUrl). It is worth noting that the same PHP file also receives data from an input (also in the same PHP file) and stores it in the same SQL database. This code was written for testing purposes and may not be entirely safe.
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Store input in SQL database
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//First echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done2 == 0)
{
$topLeftUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
//Second echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topRight" && $done3 == 0)
{
$topRightUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
//Third echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "message" && $done == 0)
{
echo $row["cont"];
}
}
Edit:
I updated the code, and the problem seems to have changed. For some reason, echo $messageCont; displays an old value of cont WHERE id='message'. The database itself is updated successfully, though, and I see the new value of cont once I refresh the page/re-submit the form. Why do I not see the current value of cont immediately after form submission, though? Here is the new code:
/* Before <!DOCTYPE html> */
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Query and update
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//Query again and read
$done0 = 0;
$done1 = 0;
$done2 = 0;
mysqli_data_seek ($result, 0);
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done0 == 0)
{
$topLeftUrl = $row["cont"];
$done0 = 1;
}
else if ($row["id"] == "topRight" && $done1 == 0)
{
$topRightUrl = $row["cont"];
$done1 = 1;
}
else if ($row["id"] == "message" && $done2 == 0)
{
$messageCont = $row["cont"];
$done2 = 1;
}
else null;
}
/* After <!DOCTYPE html> */
/* Form code was omitted as it works perfectly. It is in this same file, though. */
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo $messageCont;
Any help is appreciated.
Edit: I only had to replace mysqli_data_seek () with the line beginning by $result (cut/paste). Thank you.
I ran into this same problem on my site....you run multiple mysql_fetch_array() on the same query ($result)...I thought this would work on my site but this failed for all but the first of 6 while loops which all referenced the same query on my site (I'm sorry but I don't remember the exact error message in my error_log). Try condensing your 3 while loops into 1 loop, something like this:
while ($row = mysqli_fetch_array ($result)) {
if ($row["id"] == "topLeft" && $done2 == 0) {
$topLeftUrl = $row["cont"];
} else if ($row["id"] == "topRight" && $done3 == 0) {
$topRightUrl = $row["cont"];
} else if ($row["id"] == "message" && $done == 0) {
echo $row["cont"];
} else null;
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";

PHP doesn't echo text for last row

I'm trying to write a relatively simple twitter query in php with result like this:
from:TravisBenjamin3 OR from:AshleyElisaG OR from:tncvaan ...
This code works accept it doesn't echo the second OR, also I don't want to display an OR on the last row.
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < count($row)) {
echo " OR";
}
}
Some help would be greatly appreciated. Thanks,
<?php
$tweets = array();
while($row = mysql_fetch_array($result)) {
$tweets[] = $row['twitter'];
}
if(count($tweets) > 0) {
echo "from:" . implode(" OR from:", $tweets);
}
?>
$rowCount = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < $rowCount) {
echo " OR";
}
}
$count = mysql_num_rows($result);
for($r = 0; $r < $count; $r++)
{
$row = mysql_fetch_array($result));
echo " from:";
echo $row['twitter'];
if ($r < ($count - 1))
{
echo " OR";
}
}
Or, even easier:
$search = "";
while($row = mysql_fetch_array($result))
{
$search .= " from:" . $row['twitter'] . " OR";
}
// Cut the last " OR"
$search = substr($search, 0, strlen($search) - 3);
echo $search;
Which is actually a poor man's implementation for implode() suggested by Aaron W..

Grouping WHILE loop results

At the moment I'm using a WHERE loop to display 2 columns of information in my database. Here's the code:
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
/*These if & while statements decide whether or not the information should be displayed. If no results are returned from the query above then an alternative message is shown.*/
if (mysql_num_rows($result2) > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"] . "<br/><br/>";
}
}
else {
echo "Error";
}
This outputs the following:
08:00:00-12:30:00
13:30:00-16:30:00
09:00:00-17:00:00
18:00:00-20:00:00
09:00:00-17:00:00
18:00:00-20:00:00
08:00:00-17:00:00
18:00:00-20:00:00
09:00:00-17:00:00
18:00:00-20:00:00
Now, what I need to do is group every 2 lines that are turned so instead it would look like:
08:00:00-12:30:00 13:30:00-16:30:00
09:00:00-17:00:00 18:00:00-20:00:00
09:00:00-17:00:00 18:00:00-20:00:00
08:00:00-17:00:00 18:00:00-20:00:00
09:00:00-17:00:00 18:00:00-20:00:00
Is this possible? Thanks for any help
edit: Thanks for all the answers everyone...I used Shakti's answer as it was the first one I saw but by the looks of it everyone's are pretty similar.
if(mysql_num_rows($result2) > 0)
{
$count=0;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC))
{
echo $row["open"] . "-" . $row["close"] ;
if ($count % 2 !=0 )
{
echo "<br/><br/>";
}
$count++;
}
}
try this:
$lines = 1;
if(mysql_num_rows($result2) > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"];
echo (($lines%2 == 0)?"<br/><br/>":'');
$lines++;
}
} else {
echo "Error";
}
if(mysql_num_rows($result2) > 0){
$counter = 0;
while($row = mysql_fetch_array($result2, MYSQL_ASSOC)){
echo $row["open"] . "-" . $row["close"] . " ";
if(++$counter % 2 == 0){
echo "<br/><br/>";
$counter = 0;
}
}
}
if($result2) {
$printTimes = function($r) {echo $row["open"] . "-" . $row["close"];};
$newLine = false;
while ($row = mysql_fetch_assoc($result2))
{
$printTimes($row);
echo $newLine ? '<br /><br />' : ' ';
$newLine = !$newLine;
}
}
My version of code.
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
if(mysql_num_rows($result2) > 0) {
while (true) {
$row1 = mysql_fetch_array($result2, MYSQL_ASSOC);
$row2 = mysql_fetch_array($result2, MYSQL_ASSOC);
if (!($row1 and $row2)) break;
echo $row1["open"] . "-" . $row1["close"] . " ";
echo $row2["open"] . "-" . $row2["close"] . "<br/><br/>";
}
} else {
echo "Error";
}
$i=1;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
if ($i == 1) {
echo $row["open"] . "-" . $row["close"];
$i++;
} else {
echo $row["open"] . "-" . $row["close"] . "<br /><br />";
$i=1;
}
Output <br/><br/> only on every other iteration of the loop. (BTW, a <p> or <ul> or <div> would be more semantic.)
$counter = 0;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"] . " ";
// Break line after every two items
$counter = ($counter + 1) % 2;
if ($counter == 0)
echo "<br/><br/>";
}
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
/*These if & while statements decide whether or not the information should be displayed. If no results are returned from the query above then an alternative message is shown.*/
int row_count=mysql_num_rows($result2)
if(row_count > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
row_count--;
echo $row["open"] . "-" . $row["close"] ;
if(row_count > 0 && ($row = mysql_fetch_array($result2, MYSQL_ASSOC)){
row_count--;
echo $row["open"] . "-" . $row["close"] ;
}
"<br/><br/>"
}
} else {
echo "Error";
}
should do it, u may need to catch if there is an odd number

help with php search

How would I do let the user know if there wasnt any rows found?
And if it finds (for example) 26 rows I want it to print that it found 26 hits (Your search for "hey" gave 26 results)
$name = mysql_real_escape_string($_POST['player_name']);
$q = mysql_query("SELECT * FROM players WHERE name LIKE '%$name%'");
while ($row = mysql_fetch_array($q)) {
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
Use mysql_num_rows:
$rowCount = mysql_num_rows($q);
if ($rowCount === 0)
{
echo 'Found nothing!';
}
else
{
echo "Found $rowCount rows!";
while ($row = mysql_fetch_array($q))
{
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
}
Check out mysql_num_rows
mysql_num_rows
$numberOfResults = mysql_num_rows($q);

Categories