473,813 Members | 3,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can't get if statement to work

155 New Member
If the query returns nothing based on the criteria, then say - "Be the first to comment on this recipe!"

If the query does return something based on the criteria, then show the results. Sounds simple enough, but I don't think if ever been able to get one of these to work.

[PHP]<strong>Comment s:</strong><br><br>

<table width="95%" cellpadding="0" cellspacing="0" border="0">

<?php
include('includ es/dbcomment.php') ; //has database connect stuff
$result = mysql_query("SE LECT * FROM commenttable WHERE page_title = '$title' AND allow = 'yes'");
if (!$result)
{
echo "Be the first to comment on this recipe!";
}
else
{
while ($row = mysql_fetch_arr ay($result, MYSQL_ASSOC))
{
$commentname = stripslashes($r ow['commentname']);
$commentpost = nl2br(stripslas hes($row['commentpost']));
$commentpost = str_replace("<b r />","<br>",$comm entpost);

echo '
<tr>
<td>
<blockquote>
<!--Name:<br>-->
' . $commentpost . '<br>
<!--Comment:<br>-->
~ ' . $commentname . '
</blockquote>
</td></tr>
<tr><td>&nbsp ;</td></tr>
';
}
}
echo "</table>";[/PHP]
Nov 5 '07 #1
10 1644
pedalpete
110 New Member
it might not be the proper way to do it, but I always seem to use
if ($result = "") {
echo "be the first to comment";
}

I'm not sure why this seems to work rather than !, and I'm not sure which is the proper way, but that's the way I do it.
Nov 5 '07 #2
Atli
5,058 Recognized Expert Expert
Hi.

You can use the mysql_num_rows function to see if any rows were returned, and based on that, either print your message or print the results.

Somewhat like this:
Expand|Select|Wrap|Line Numbers
  1. # Connect to database
  2. # ... You know the drill
  3.  
  4. # Execute query
  5. $sql = "SELECT * FROM tbl";
  6. $result = mysql_query($sql, $db) or die(mysql_error());
  7.  
  8. # Check if any rows were returned
  9. if(mysql_num_rows($result) <= 0) {
  10.   echo "Be the first to comment.";
  11. }
  12. else {
  13.   # Show your results.
  14. }
  15.  
Also, if you are printing multiple lines of HTML code, consider using the echo statement like so:
Note, the TSDN code parser shows this incorrectly. Everything between the END keywords is printed.
Expand|Select|Wrap|Line Numbers
  1. echo <<<END
  2. This uses the "here document" syntax to output
  3. multiple lines with $variable interpolation. Note
  4. that the here document terminator must appear on a
  5. line with just a semicolon. no extra whitespace!
  6. END;
  7.  
Nov 6 '07 #3
DavidPr
155 New Member
Neither of those worked for me, so I used a do while statement and got it working, albeit with errors sometimes. Sometimes it works great and sometimes it don't.

I'm getting this on some links:
[PHP]Warning: mysql_fetch_arr ay(): supplied argument is not a valid MySQL result resource in /blah/blah/blah/blah/mysite.com/viewrecipe2.php on line 217[/PHP]
and this is line 217:
[PHP]if($row = mysql_fetch_arr ay($result, MYSQL_ASSOC))[/PHP]

The whole thing:
[PHP]<table width="95%" cellpadding="0" cellspacing="0" border="0">

<?php
include('includ es/dbcomment.php') ;
$query = "SELECT * FROM commenttable WHERE page_title = '" . $title . "' AND allow = 'yes'";
$result = mysql_query($qu ery);

if($row = mysql_fetch_arr ay($result, MYSQL_ASSOC))
{
do
{
$commentname = stripslashes($r ow['commentname']);
$commentpost = nl2br(stripslas hes($row['commentpost']));
$commentpost = str_replace("<b r />","<br>",$comm entpost);

echo '
<tr>
<td>
<blockquote>
' . $commentpost . '<br>
~ ' . $commentname . '
</blockquote>
</td>
</tr>
<tr><td>&nbsp ;</td></tr>
';
}
while($row = mysql_fetch_arr ay($result, MYSQL_ASSOC));
}
else
{
echo "
<tr>
<td>
<blockquote>
Be the first to comment on this recipe!
</blockquote>
</td>
</tr>
<tr><td>&nbsp ;</td></tr>
";
}
echo '
</table>[/PHP]
Nov 6 '07 #4
Atli
5,058 Recognized Expert Expert
I would guess you get that error when there are no rows returned and it could also happen if there is only one row returned, but then it should move down to the while statement.
The do-while combo there is not an ideal solution, even tho it may work.

The code that I posted should work. I used a code similar to it quite frequently before I started using the mysqli extension.

Even if it doesn't work as it is posted, you can still incorporate the mysql_num_rows function into your code to accomplish your goal. It will simply tell you if there are any rows, so that you can see if you need to print the results or the "no comments" message.
Nov 6 '07 #5
DavidPr
155 New Member
It worked in that it displayed the message when the query didn't return any results, but it would not display the results if there were items in the database.

And I need to update my last post - I get the error message on all querys and not just some. Queer thing is that it still runs the query fine, it just displays that message. And I'm operating in a limited width space so it pushes everything down because the error message is 20' long.

I copied the do while statement from another script, so I don't want to mislead anyone in thinking that I know what I'm doing - I don't. I have no clue as to what this do while script is doing or why or how it's working. But it has gotten me further down the road than with anything else I've tried so far.

I don't know why I am getting the error message that I'm getting, but I would like to find out and how to correct it so I can put this thing to bed. So I'll try anything.

**EDITED**

OK, I'm back to only getting this error messages on some queries. Here's where it starts, I have a list of recipes under a certain category like- Breads.
I'm getting the error message on the recipes that have an ' (single quote) in the title. So there is something about this line that don't like single quotes:
[PHP]if($row = mysql_fetch_arr ay($result, MYSQL_ASSOC))[/PHP]


I have to define the variables and stripslashes, and I'm doing it somehow in this do while script using:
[PHP]while($row = mysql_fetch_arr ay($result, MYSQL_ASSOC));
{
$commentname = stripslashes($r ow['commentname']);
}[/PHP]
I don't know how I'd do them with:
[PHP]if(mysql_num_ro ws($result) <= 0)
{[/PHP]
Nov 6 '07 #6
Atli
5,058 Recognized Expert Expert
It worked in that it displayed the message when the query didn't return any results, but it would not display the results if there were items in the database.
My code snipped is not a complete program. I assumed you would fill in the code that was missing, namely the code that shows the results. (By adding the while loop from your original code at line 13 in my code.)

If your code is working, with the exception of the warning you are being shown, try adding a @ sign in front of the function that is causing the warning. It should suppress any error from that function.
Be careful tho, if the code starts acting weird, it may be suppressing something else.
Nov 6 '07 #7
DavidPr
155 New Member
I put my code in it, but it wouldn't display the results. Each comment should be inside a blockquote. I tested on a recipe title that I knew had 2 comments. The code only showed 1 box that was empty. Nothing I could do would get the comment to display and I tried several methods that have worked for me in other scripts.

I don't know what to do. I have tried over 2 dozen different ways of writing the code but nothing works. I know that part of the problem is that some recipe titles have single quotes. And it is these that I'm getting the error messages with. I've tried stripping slashes and adding slashes but nothing works.

Someone in another forum suggested I change the "allow" row in the database table that contains the comments from "yes" and "no" to "0" for no (false) and "1" for yes (true). Instead of using varchar use tinyint. I don't what the difference is though, as I'm getting the exact same results.

Maybe it just can't be done.
Nov 7 '07 #8
DavidPr
155 New Member
Here's one code I've tried. I don't get the error message with the recipe titles with single quotes but neither do I get the comments that I know are there.

[PHP]$file = addslashes($rec ipe_title);
// $file = $recipe_title;

include('includ es/dbcomment.php') ;

$query = 'SELECT * FROM commenttable where recipe_title="$ file" and allow="1"';
$result = mysql_query($qu ery) or die(mysql_error () . "<br>" . $query);

if(mysql_num_ro ws($result) <= 0)
{
echo "
<tr>
<td>
<blockquote>
Be the first to comment on this recipe!
</blockquote>
</td>
</tr>
<tr><td>&nbsp ;</td></tr>
";
}
else
{
while($row = mysql_fetch_arr ay($result, MYSQL_ASSOC));
{
$commentname = stripslashes($r ow['commentname']);
$commentpost = nl2br(stripslas hes($row['commentpost']));
$commentpost = str_replace("<b r />","<br>",$comm entpost);

echo '
<tr>
<td>
<blockquote>
' . $commentpost . '<br>

~ ' . $commentname . '
</blockquote>
</td></tr>
';
}
}

echo '
</table>[/PHP]
Nov 7 '07 #9
Atli
5,058 Recognized Expert Expert
Did you try something like this?
I simply copied your code for displaying the rows into my mysql_num_rows example.
Expand|Select|Wrap|Line Numbers
  1. # Connect to database
  2. # ... You know the drill
  3.  
  4. # Execute query
  5. $sql = "SELECT commentname, commentpost FROM tbl";
  6. $result = mysql_query($sql, $db) or die(mysql_error());
  7.  
  8. # Check if any rows were returned
  9. if(mysql_num_rows($result) <= 0) {
  10.   echo "Be the first to comment.";
  11. }
  12. else {
  13.   # Print all rows
  14.   while($row = mysql_fetch_assoc($result));
  15.   {
  16.     $commentname = stripslashes($row['commentname']);
  17.     $commentpost = nl2br(stripslashes($row['commentpost']));
  18.     $commentpost = str_replace("<br />","<br>",$commentpost);
  19.  
  20.     echo <<<END
  21.     <tr>
  22.     <td>
  23.     <blockquote>
  24.     $commentpost<br> 
  25.     ~ $commentname
  26.     </blockquote>
  27.     </td></tr>
  28. END;
  29.   }
  30. }
  31.  
O, and I just noticed:
Expand|Select|Wrap|Line Numbers
  1. /* This */
  2. SELECT * FROM commenttable where recipe_title="$file" and allow="1"
  3.  
  4. /* Should be */
  5. SELECT commentname, commentpost FROM commenttable where recipe_title='$file' and allow=1
  6.  
MySQL does not use double-quotes around strings, only single-quotes. And numbers should never be quoted, unless of course you are using the character 1 rather than the number 1.
Also, avoid using the * (wild-card) sign when fetching data. It returns all rows, even those you never use, causing unnecessary overhead on the server.
Nov 7 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

11
1788
by: Paul Rubin | last post by:
I frequently find myself writing stuff like # compute frob function, x has to be nonnegative x = read_input_data() assert x >= 0, x # mis-use of "assert" statement frob = sqrt(x) + x/2. + 3. This is not really correct because the assert statement is supposed to validate the logical consistency of the program itself, not the input data. So, for example, when you compile with optimization on, assert
65
12637
by: Skybuck Flying | last post by:
Hi, I needed a method to determine if a point was on a line segment in 2D. So I googled for some help and so far I have evaluated two methods. The first method was only a formula, the second method was a piece of C code which turned out to be incorrect and incomplete but by modifieing it would still be usuable. The first method was this piece of text:
5
8773
by: charliewest | last post by:
I've implemented the USING statement to ensure that my newly created sql connection closes when my method is finished using it. The USING statement is wrapped in try/catch error handling statement. This works fine. When i try to implement the "SqlTransation" class, the code does not work as the SqlTransation object is out-of-scope in the catch statement, and/or, after the USING statement ends, the sql connection object is automatically...
13
2141
by: Andy Baxter | last post by:
Can anyone recommend a good online guide to using objects in javascript? The book I bought (DHTML Utopia) suggests using objects to keep the code clean and stop namespace clashes between different parts of the code, but as far as I can see, the way objects work in javascript is quite awkward. I had it working the way they suggest in the book, and it was going OK until I wanted to call one object method from another - I couldn't find a...
14
3105
by: Matt | last post by:
I need to add the following variable into an SQL statement and not sure how to do it. strGCID needs to be inserted into the following statement: SQL = "SELECT tblContacts.* FROM tblContacts INNER JOIN tblGC ON tblContacts.GCID = tblGC.gcID WHERE (((tblContacts.GCID)=strGCID))" i am just not sure of the proper syntax.
6
9771
by: Ivan | last post by:
Hello to all and thanks for answer to my topics. I made one stored procedure that delete one table, but when call/execute the procedure this show SQL0532N A parent row cannot be deleted because the relationship "TXN_TRANSACTION.FK_SCLI " restricts the deletion. Then in the procedure it adds one delete of the foreign keys. This it
37
4012
by: jht5945 | last post by:
For example I wrote a function: function Func() { // do something } we can call it like: var obj = new Func(); // call it as a constructor or var result = Func(); // call it as a function
11
4811
by: npm | last post by:
Hi, I'm trying to add an IF statement to this javascript that will select/display only those xml nodes either with a certain attribute or attribute value. Here's my xml code: <stations> <station timezone="PT" PT=""> <city>Seattle</city> <freq>93.1 FM</freq>
26
3056
by: machineghost | last post by:
First off, let me just say that as someone with no DBA training whatsoever, any help I can get with this issue will be very, very much appreciated. My company recently migrated our database from DB2 v7 to DB2 v9. We hired a consultant to help us, and things went pretty smoothly ... up until a few weeks after, when a co-worker tried to insert JavaScript in to our database. That's when we learned that v9, unlike v7, has a problem with...
1
2523
by: Maklar60 | last post by:
I am attempting to execute an INSERT statement on my page but continually get the following error: Microsoft OLE DB Provider for ODBC Drivers error '80040e14' Incorrect syntax near '<'. /int_code04/myNMLC/insertNewTrackRecord.asp, line 97 I've tested the INSERT stmt both within SQL Server and as a string literal within the page's code with hardcoded values to ensure that the statement works, which is does. But when I assign this...
0
9734
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9607
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10667
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10422
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10139
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7681
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5568
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4358
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3885
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.