How to echo message if no row count - php

I am trying to echo the message 'No records found' when I get nothing back from the database.
I have done a row count which shows me how many rows I have but I can't seem to echo the 'No records found' message. Is it in the wrong place? Will it not run for some reason?
<?php if(isset($search_results)){
foreach($search_results as $result) {
$rowcount = $result['rowcount'];
if(!$rowcount < 1) {
echo $rowcount;
echo '<div class="search_result"> <b>'.$result['title'].'</b><br />';
echo '<span class="search_result_url">'.$result['link'].'</span><br />';
echo $result['text'].'<br /></div>';
} else {
echo 'No records found.';
}
}
} else {
echo 'Use the search to find what you are looking for. Enter the term or keyord into the search box and press enter..';
}
?>

Take a look at mysql_num_rows(), and use an if() to see whether your mysql_query() returned any results:
$result = mysql_query("SELECT * FROM table");
if(!mysql_num_rows($result))
{
echo 'No results';
}
else
{
// Results - do stuff.
}

Related

The value still store in database even the number of room is max number

<?php
$sql1 = "SELECT rmType,dateCi, SUM(rmNum) as total FROM reserve GROUP BY rmType,dateCi";
$result = mysqli_query($conn,$sql1);
while ($row1 = mysqli_fetch_assoc($result)) {
if ($row1['dateCi'] == $_SESSION['checkIn']){
if ($row1['rmType'] == 'sBed'){
if ($row1['total'] >= 10) {
echo "<script>alert('Single Bed Room is Full Occupied.')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'tSBed'){
if ($row1['total'] >= 10) {
echo "<script>alert('Two Single Bed Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'dBed'){
if ($row1['total'] >= 5) {
echo "<script>alert('Double Bed Room is Full Occupied')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'fBed'){
if ($row1['total'] >= 12) {
echo "<script>alert('Four-Bed Domitary Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
}
if ($row1['dateCi'] == $_SESSION['checkOut']){
if ($row1['rmType'] == 'sBed'){
if ($row1['total'] >= 10) {
echo "<script>alert('Single Bed Room is Full Occupied.')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'tSBed'){
if ($row1['total'] >= 10) {
echo "<script>alert('Two Single Bed Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'dBed'){
if ($row1['total'] >= 5) {
echo "<script>alert('Double Bed Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
if ($row1['rmType'] == 'fBed'){
if ($row1['total'] >= 12) {
echo "<script>alert('Four-Bed Domitary Room is Full Occupied'></script>";
echo "<script>window.open('index.php','_self')</script>";
}
else {
echo "";
}
}
}
}
?>
<?php
$query = "INSERT INTO `reserve` (`userId`,`userName`,`userEmail`,`rmType`,`rmNum`,`guest`,`dateCi`,`dateCo`,`cost`) VALUES('".$userRow['userId']."','".$userRow['userName']."','".$userRow['userEmail']."','".$roomtype."','".$roomNum."','".$guest."','".$checkIn."','".$checkOut."','".$pay."')";
$res1 = mysqli_query($conn,$query);
if($res1) {
$update = "UPDATE users SET costPay='$pay1' WHERE userId=".$_SESSION['user'];
$run_up = mysqli_query($conn,$update);
if($run_up){
echo "<script>alert('This process reservation has successful.')</script>";
echo "<script>window.open('index.php','_self')</script>";
}}
else
{
echo "Error: " . $res . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
From the coding shown is explain about checking the room number, if it reach the max then it will echo the script that room full and open new window to homepage.
if it do not reach the max then it will store those value into table.
but the problem i met now is even the room is full, it still store those value into the table.
May someone help me please?
You are (wrongly) assuming that echo outputs the contents straight away in all cases. It doesn't. Instead it builds up a buffer to output when:
the buffer reaches a certain size, or
when the script stops executing, or
when the buffer is flushed to force an output
As you build the output and don't have any controls around the insert statement, it will always hit that insert statement, which is what it is currently doing.
Fortunately there's a few ways around this:
put an exit; after each block of echo'd script (that will terminate the script and cause the output to happen)
set a variable after the echo parts and check for that before inserting (or not inserting)
Change the control flow so instead of if ... if ... if ... you make use of if...elseif...else, where the else houses the insert statement which will then only run if none of the other conditions matched
There are other ways of doing the same action, but the up-shot is, the script will try not to output anything until it has completed, and part of that includes the insert.

IF statement with Graph API

I'm trying to show from data from Graph API, however I'm new with PHP and I'm struggling to get it to work. I've been working with the old API and have only just managed to convert some old code to new code, so it's a little messy. Can anyone see what's stopping this from functioning?
echo print_r( $graphObject, 1 );
echo "<br><h2><b><u>First Company</u></b></h2>";
echo 'Name: '.$graphObject->getProperty('name').;
echo 'Phone: '
if .$graphObject->getProperty['phone']. {
echo .$graphObject->getProperty('phone');
} else {
echo "No phone number available.";
}
I've managed to get the 'Name', but I'm trying to create an IF statement as the page doesn't have a phone number available.
Replace:
if .$graphObject->getProperty['phone'].
with
if (isset($graphObject->getProperty['phone']))
This should work
print_r($graphObject);
echo "<br><h2><b><u>First Company</u></b></h2>";
echo 'Name: ';
if (!empty($graphObject->getProperty('name'))) {
echo $graphObject->getProperty('name');
} else {
echo "No name available.";
}
echo 'Phone: ';
if (!empty($graphObject->getProperty('phone'))) {
echo $graphObject->getProperty('phone');
} else {
echo "No phone number available.";
}

If statement within echo?

I was wondering if it's possible to have an if statement within an echo.
I have if statement which works fine when echoing results through the a while loop... This is the statement:
<div><?php if ($row['image'] == '') {}
else {echo "<img src='data:image/jpeg;base64,".base64_encode($row['image'])."'>";} ?>
<?php if ($row['video'] == '') {}
else {echo "<iframe src={$row['video']}></iframe>";} ?></div>`
So basically it's either a video or an image which works fine but then I implemented an infinite scroll to my blog which echoes the data from the database through and if statement like so:
if ($results) {
while($obj = $results->fetch_object())
{
echo '
<div><h3>'.$obj->headline.'</h3> </div>
<div><img src='data:image/jpeg;base64,".base64_encode('.$obj->image.')."'></div>'
So I wondering if anyone knows if it's possible to transfer that if statement within this echo so that it display an image firstly and then knows whether one is present or when a video is present within the database.
Thanks in advance for any help.
PS: I'm very new to coding/php!
Of course. Just split up the echo into multiple statements:
while($row = $results->fetch_object()) {
echo '<div>';
if ($row['image'] == '') {
} else {
echo "<img src='data:image/jpeg;base64,".base64_encode($row['image'])."'>";
}
if ($row['video'] == '') {
} else {
echo "<iframe src={$row['video']}></iframe>";
}
echo '</div>';
}
Try this one.
//first initialize a variable as a string
$result="";
while($obj = $results->fetch_object()) {
$result.="<div>";
if (!empty($obj['image'])){
$result.="<img src='data:image/jpeg;base64,".base64_encode($obj['image'])."'>";
}
elseif (!empty($obj['video'])){
$result.="<iframe src={$obj['video']}></iframe>";
}else{
//show some notification or leave it
//echo 'not Found';
}
$result.="</div>";
}
//finally you need to print the result variable.
echo $result;

How to avoid repeating the same code in this case

In the code below there's a chunck of code that repeats itself. Can this be done in another way so that the code does not repeat. No matter what I try, I keep ending with the same thing. The code is below, but it's a lot more in the production version. This thing does country location.
if ($GL)
{
echo 'Managed to find your location';
}else{
echo "Could not identify GL. Please select from the list below.";
}
This is the entire thing (stripped down).
$GL = false; //GL is detected using ip to location, and returns boolean
$location = 'UK';//Read from a cookie.
if(isset($location))
{
echo 'We found a cookie with your location<br />';
if(array_key_exists($location,$countries))
{
echo 'We found a country in the array. Carrying on<br />';
}else
{
echo 'Did not find a country in the array. Looking for GL';
if ($GL)
{
echo 'Managed to find your location. Carrying on';
}else{
echo "Could not identify GL. Please select from the list below.";
}
}
}
else
{
echo 'Did not find a location cookie<br />';
if ($GL)
{
echo 'Managed to find your location.Carrying on.';
}else{
echo "Could not identify GL. Please select from the list below.";
}
}
There are a couple simple solutions you could do. Such as:
1) Put it in a function:
function validGL($GL)
{
if ($GL)
{
echo 'Managed to find your location.Carrying on.';
}
else
{
echo "Could not identify GL. Please select from the list below.";
}
}
2) Store a boolean to determine if a valid location was found:
$GL = false; //GL is detected using ip to location, and returns boolean
$location = 'UK';//Read from a cookie.
$locationFound = false;
if(isset($location))
{
echo 'We found a cookie with your location<br />';
if(array_key_exists($location,$countries))
{
echo 'We found a country in the array. Carrying on<br />';
$locationFound = true;
}
else
{
echo 'Did not find a country in the array. Looking for GL';
}
}
else
{
echo 'Did not find a location cookie<br />';
}
if (!$locationFound)
{
if ($GL)
{
$GL_msg = 'Managed to find your location. Carrying on';
}
else
{
$GL_msg = "Could not identify GL. Please select from the list below.";
}
}
You can rephrase it like this:
If location is passed and found within valid list of countries, use that.
If not, if GL is found, use that.
Show the list if all else fails.
In code:
if (isset($location) && array_key_exists($location,$countries)) {
echo 'We found a country in the array. Carrying on<br />';
} elseif ($GL) {
echo 'Managed to find your location. Carrying on';
} else {
echo "Could not identify GL. Please select from the list below.";
}
You can make it a function and just call that function with the GL variable. This way you dont have to repeat the same if over and over.

Preventing PHP printing Null Array Results?

I cannot get my PHP script to echo the second else statement if the first result empty.
The way my script currently works is "Print Addresses (from another array) > List Comments", however even if a comment is empty for an address is will either print the comments or nothing, I cannot make the script echo the word "No comment".
if(!empty($row['id']))
{
echo "$row[comment]<br/>";
}
else
{
echo "no comment<br/>";
}
Any help appreciated. Thanks.
Assuming this comes from a database and each row has an id, this will always be true:
if(!empty($row['id']))
Try:
if(!empty($row['comment']))
If id is something else, the same logic applies: check the value that you intend to print:
if (!empty($row['id']) && !empty($row['comment']))
{
echo $row['comment'].'<br/>';
}
else
{
echo "no comment<br/>";
}
EDIT: If this code is looping through all comments attached to a post or something, there will never be any output if there are no comments to loop through. In that case try something like this:
if (count($comments) === 0)
{
echo "no comments<br />";
}
else
{
foreach ($comments as $row)
{
if (!empty($row['comment']))
{
echo $row['comment'].'<br />';
}
else
{
echo "no comment<br />";
}
}
}
OR:
$comment_count = 0;
foreach ($comments as $row)
{
if (!empty($row['comment']))
{
echo $row['comment'].'<br />';
$comment_count++; // We have at least one comment
}
else
{
echo "no comment<br />";
}
}
if ($comment_count === 0) echo 'no comments<br />';

Categories