Can't get if statement to work

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DavidPr
    New Member
    • Mar 2007
    • 155

    Can't get if statement to work

    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]
  • pedalpete
    New Member
    • Oct 2007
    • 109

    #2
    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.

    Comment

    • Atli
      Recognized Expert Expert
      • Nov 2006
      • 5062

      #3
      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:
      [code=php]
      # Connect to database
      # ... You know the drill

      # Execute query
      $sql = "SELECT * FROM tbl";
      $result = mysql_query($sq l, $db) or die(mysql_error ());

      # Check if any rows were returned
      if(mysql_num_ro ws($result) <= 0) {
      echo "Be the first to comment.";
      }
      else {
      # Show your results.
      }
      [/code]

      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.
      [code=php]
      echo <<<END
      This uses the "here document" syntax to output
      multiple lines with $variable interpolation. Note
      that the here document terminator must appear on a
      line with just a semicolon. no extra whitespace!
      END;
      [/code]
      Last edited by Atli; Nov 6 '07, 12:21 AM. Reason: Added notes.

      Comment

      • DavidPr
        New Member
        • Mar 2007
        • 155

        #4
        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]

        Comment

        • Atli
          Recognized Expert Expert
          • Nov 2006
          • 5062

          #5
          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.

          Comment

          • DavidPr
            New Member
            • Mar 2007
            • 155

            #6
            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]

            Comment

            • Atli
              Recognized Expert Expert
              • Nov 2006
              • 5062

              #7
              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.

              Comment

              • DavidPr
                New Member
                • Mar 2007
                • 155

                #8
                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.

                Comment

                • DavidPr
                  New Member
                  • Mar 2007
                  • 155

                  #9
                  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]

                  Comment

                  • Atli
                    Recognized Expert Expert
                    • Nov 2006
                    • 5062

                    #10
                    Did you try something like this?
                    I simply copied your code for displaying the rows into my mysql_num_rows example.
                    [code=php]
                    # Connect to database
                    # ... You know the drill

                    # Execute query
                    $sql = "SELECT commentname, commentpost FROM tbl";
                    $result = mysql_query($sq l, $db) or die(mysql_error ());

                    # Check if any rows were returned
                    if(mysql_num_ro ws($result) <= 0) {
                    echo "Be the first to comment.";
                    }
                    else {
                    # Print all rows
                    while($row = mysql_fetch_ass oc($result));
                    {
                    $commentname = stripslashes($r ow['commentname']);
                    $commentpost = nl2br(stripslas hes($row['commentpost']));
                    $commentpost = str_replace("<b r />","<br>",$comm entpost);

                    echo <<<END
                    <tr>
                    <td>
                    <blockquote>
                    $commentpost<br >
                    ~ $commentname
                    </blockquote>
                    </td></tr>
                    END;
                    }
                    }
                    [/code]

                    O, and I just noticed:
                    [code=mysql]
                    /* This */
                    SELECT * FROM commenttable where recipe_title="$ file" and allow="1"

                    /* Should be */
                    SELECT commentname, commentpost FROM commenttable where recipe_title='$ file' and allow=1
                    [/code]
                    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.

                    Comment

                    • DavidPr
                      New Member
                      • Mar 2007
                      • 155

                      #11
                      Thanks for the information, I didn't know that about mysql.

                      I am happy to report that the code is now working - as it should.

                      Thanks for all the help.
                      David

                      Comment

                      Working...