What a wild 3 weeks (and php question).

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Publisher Bucks
    Confirmed User
    • Oct 2018
    • 1330

    #1

    Tech What a wild 3 weeks (and php question).

    So a few weeks ago I was told I had covid, so after 3 weeks of pure hell, sleeping non-stop, vomiting, aches and pains plus coughing, I finally get the all clear and am back at it.

    No clue how I even got it as I have pretty much remained a hermit this whole time.

    Anyway, I'm trying to get caught up on some of my personal projects, including a little recipe site that I'm having an issue with... I'm using the following code on an index page for a website..

    PHP Code:
    <?php
    $con=mysqli_connect("localhost","recipes","password","recipelist");
    // Check connection
    if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    
    $result = mysqli_query($con,"SELECT * FROM Recipes");
    
    echo "<table border='1'>
    <tr>
    <th>ID</th>
    <th>Title</th>
    <th>Method</th>
    <th>Ingredients</th>
    </tr>";
    
    while($row = mysqli_fetch_array($result))
    {
        $link = "recipes.php?id=".$row['RecipeID'];
        echo "<tr>";
        echo "<td><a href = ". $link . ">" . $row['Title'] . "</a></td>";
        echo "<td>" . $row['Ingredients'] . "</td>";
        echo "<td>" . $row['Method'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    mysqli_close($con);
    ?>
    Which does everything that it is supposed to for that page (for now).

    However, when the link that is generated is clicked on to go to recipes.php?id=4 it keeps telling me the page isnt working.

    This is the code im using in the recipes.php page, can anyone give me a little guidance as to what is messed up please?

    PHP Code:
    <?php
        // check incoming params exist
        if ( ! isset($_GET['id'] ) {
            // missing param, go to an error page for example
            header('Location: index.php');
            exit;
        }
    
        // You can now use $_GET['id'] which will be the id number passed
        // any way you want.
    
        // For example using a PDO connection called $pdo
    
        $table = "Recipes";
    
        $sql = "SELECT * FROM $table WHERE id = :RecipeID";
    
        try {
            $stmt = $pdo->prepare($sql);
    
            $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
            $stmt->execute();
    
            $rows = $stmt->FetchAll();  // $rows now contains all the results of the query
        }
        catch( PDOException $e) {
            echo $e-getMessage();
        }
    
        foreach ( $rows as $row ) {
            // do things with the $row['column_name'] data
        }
    while($row = mysqli_fetch_array($result))
    {
        echo "<tr>";
        echo "<td>" . $row['Title'] . "</td>";
        echo "<td>" . $row['Ingredients'] . "</td>";
        echo "<td>" . $row['Method'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    ?>
    Its basically not showing anything.

    What it *should* be doing is displaying a table of all the data for the MYSQL database recordwith a RecipeID of 4 on that recipes.php page.

    Any help would be greatly appreciated.

    Oh and to top the last 3 weeks of dealing with covid off... New Orleans is now expecting to be hit by a cat 4 hurricane and parts of the area have been issued a mandatory evacuation, thankfully I'm in an area where its only voluntary and well inside the levee protection system
    Extreme Link List - v1.0
  • k33n
    Confirmed User
    • Feb 2009
    • 201

    #2
    Print $sql and make sure the query is valid...i don't think you are passing the $GET['id'] value. And, you say that you want the RecipeID column but you are querying id column, it will fail because your table doesn't have a column "id".

    Comment

    • Colmike9
      (>^_^)b
      • Dec 2011
      • 7230

      #3
      // check incoming params exist
      if ( ! isset($_GET['id'] ) {
      // missing param, go to an error page for example
      header('Location: index.php');
      exit;
      }


      is missing a )
      Join the BEST cam affiliate program on the internet!
      I've referred over $1.7mil in spending this past year, you should join in.
      I make a lot more money in the medical field in a lab now, fuck you guys. Don't ask me to come back, but do join Chaturbate in my sig, it still makes bank without me touching shit for years..

      Comment

      • hornyasf
        Confirmed User
        • Jul 2021
        • 185

        #4
        Another tiny error

        " echo $e-getMessage(); "

        Missing a >

        Comment

        • Publisher Bucks
          Confirmed User
          • Oct 2018
          • 1330

          #5
          Originally posted by Colmike9
          // check incoming params exist
          if ( ! isset($_GET['id'] ) {
          // missing param, go to an error page for example
          header('Location: index.php');
          exit;
          }


          is missing a )
          Thank you!
          Extreme Link List - v1.0

          Comment

          • Publisher Bucks
            Confirmed User
            • Oct 2018
            • 1330

            #6
            Originally posted by hornyasf
            Another tiny error

            " echo $e-getMessage(); "

            Missing a >
            Much appreciated
            Extreme Link List - v1.0

            Comment

            • Publisher Bucks
              Confirmed User
              • Oct 2018
              • 1330

              #7
              Originally posted by k33n
              Print $sql and make sure the query is valid...i don't think you are passing the $GET['id'] value. And, you say that you want the RecipeID column but you are querying id column, it will fail because your table doesn't have a column "id".
              Could you show me where im messing up on that?

              I tried changing it in a couple of spots and still running into 500 errors.

              (Sorry only been working on php for a couple of months so still pretty green with it).

              Thank you for the explanation
              Extreme Link List - v1.0

              Comment

              • plsureking
                bored
                • Aug 2003
                • 4898

                #8
                hey if you still live in New Orleans stay safe and good luck! it doesn't look pretty.



                #
                PornCMS / low cost paysite management with hosting

                Comment

                • Publisher Bucks
                  Confirmed User
                  • Oct 2018
                  • 1330

                  #9
                  Originally posted by plsureking
                  hey if you still live in New Orleans stay safe and good luck! it doesn't look pretty.



                  #
                  Thanks.

                  Its still relatively calm here right now, a little high wind and some light rain, that's about it (so far).

                  A few miles away several of the parishes have lost power and I'm seeing reports of flooding, still nothing majorly serious, we lose power and flood as a city all the time

                  The media (at this point in time) is definitely playing it up for ratings.
                  Extreme Link List - v1.0

                  Comment

                  • sarettah
                    see you later, I'm gone
                    • Oct 2002
                    • 14293

                    #10
                    First, stay safe.

                    Second, as someone said above, you have an error in your if statement, you are missing a paren.

                    You have:

                    // check incoming params exist
                    if ( ! isset($_GET['id'] ) {
                    // missing param, go to an error page for example
                    header('Location: index.php');
                    exit;
                    }

                    That should be:

                    // check incoming params exist
                    if ( ! isset($_GET['id'] ) ){
                    // missing param, go to an error page for example
                    header('Location: index.php');
                    exit;
                    }


                    Thirdly:

                    In the recipe.php you do not establish a database connection. In the first program you are establishing a mysqli connection. In the Recipe.php you do not establish any database connection and then you try to use a pdo connection that does not exist.

                    Instead of mixing between mysqli and pdo, use one. You are using mysqli in the first program, use that again in the second. You use it at the bottom of the second to iterate through the rows.

                    Put an error_reporting(E_ALL) at the start of the program and it should show you your errors. Once you have everything debugged change that to error_reporting(0) so it won't show the errors.


                    <?php
                    error_reporting(E_ALL);

                    // check incoming params exist
                    if ( ! isset($_GET['id'] ) ){
                    // missing param, go to an error page for example
                    header('Location: index.php');
                    exit;
                    }

                    // open a mysqli connection
                    $con=mysqli_connect("localhost","recipes","passwor d","recipelist");

                    // Check connection
                    if (mysqli_connect_errno())
                    {
                    die("Failed to connect to MySQL: " . mysqli_connect_error());
                    }

                    $table = "Recipes";
                    $sql = "SELECT * FROM" . $table . " WHERE id =" . $_GET['id'];

                    // do the query
                    $result = mysqli_query($con, $sql);

                    echo "<table>";
                    while($row = mysqli_fetch_array($result))
                    {
                    echo "<tr>";
                    echo "<td>" . $row['Title'] . "</td>";
                    echo "<td>" . $row['Ingredients'] . "</td>";
                    echo "<td>" . $row['Method'] . "</td>";
                    echo "</tr>";
                    }
                    echo "</table>";
                    ?>

                    Something like that should work. I have not checked to see if there are any other syntax issues.

                    You should also do some validation on $_GET['id']. I used it raw above and that is not really safe. It is fine for right now while you are trying to figure things out but for something open to the net it isn't.

                    For example is the id field an integer?

                    Then you would want to do a validation such as making sure it is an int coming in.

                    $recipeid=0;

                    if(isset($_GET['id']))
                    {
                    $recipeid=intval($_GET['id']);
                    }

                    if($recipeid==0)
                    {
                    echo "Bad id value coming in or something like that...";
                    }

                    .
                    All cookies cleared!

                    Comment

                    • Publisher Bucks
                      Confirmed User
                      • Oct 2018
                      • 1330

                      #11
                      Originally posted by sarettah
                      First, stay safe.

                      Second, as someone said above, you have an error in your if statement, you are missing a paren.

                      You have:

                      // check incoming params exist
                      if ( ! isset($_GET['id'] ) {
                      // missing param, go to an error page for example
                      header('Location: index.php');
                      exit;
                      }

                      That should be:

                      // check incoming params exist
                      if ( ! isset($_GET['id'] ) ){
                      // missing param, go to an error page for example
                      header('Location: index.php');
                      exit;
                      }


                      Thirdly:

                      In the recipe.php you do not establish a database connection. In the first program you are establishing a mysqli connection. In the Recipe.php you do not establish any database connection and then you try to use a pdo connection that does not exist.

                      Instead of mixing between mysqli and pdo, use one. You are using mysqli in the first program, use that again in the second. You use it at the bottom of the second to iterate through the rows.

                      Put an error_reporting(E_ALL) at the start of the program and it should show you your errors. Once you have everything debugged change that to error_reporting(0) so it won't show the errors.


                      <?php
                      error_reporting(E_ALL);

                      // check incoming params exist
                      if ( ! isset($_GET['id'] ) ){
                      // missing param, go to an error page for example
                      header('Location: index.php');
                      exit;
                      }

                      // open a mysqli connection
                      $con=mysqli_connect("localhost","recipes","passwor d","recipelist");

                      // Check connection
                      if (mysqli_connect_errno())
                      {
                      die("Failed to connect to MySQL: " . mysqli_connect_error());
                      }

                      $table = "Recipes";
                      $sql = "SELECT * FROM" . $table . " WHERE id =" . $_GET['id'];

                      // do the query
                      $result = mysqli_query($con, $sql);

                      echo "<table>";
                      while($row = mysqli_fetch_array($result))
                      {
                      echo "<tr>";
                      echo "<td>" . $row['Title'] . "</td>";
                      echo "<td>" . $row['Ingredients'] . "</td>";
                      echo "<td>" . $row['Method'] . "</td>";
                      echo "</tr>";
                      }
                      echo "</table>";
                      ?>

                      Something like that should work. I have not checked to see if there are any other syntax issues.

                      You should also do some validation on $_GET['id']. I used it raw above and that is not really safe. It is fine for right now while you are trying to figure things out but for something open to the net it isn't.

                      For example is the id field an integer?

                      Then you would want to do a validation such as making sure it is an int coming in.

                      $recipeid=0;

                      if(isset($_GET['id']))
                      {
                      $recipeid=intval($_GET['id']);
                      }

                      if($recipeid==0)
                      {
                      echo "Bad id value coming in or something like that...";
                      }

                      .
                      Damn! Thank you so much for the detailed response

                      Going to see if I can get this working with those fixes you made and the changes.

                      Out of interest, is there a specific time/reason I should use mysqli vs PDO in this type of scripting? Also, is there any significant difference in using echo vs print for the output data?

                      Winds are starting to pick up, no real damage here as yet though (2 miles outside the Quarter) unless you count a couple of upturned garbage cans that weren't secured properly by neighbors.

                      Power and Internet is still working, there was an advisory an hour or so back not to use dishwashers, washing machines or other appliances that utilize a lot of water due to the sewerage plant system losing power, other than that, nothing major to report here yet.

                      Have enough food, smokes and liquor to last a week if the power does go out and I just finished a huge pan of baked ziti, so should be somewhat comfortable if utilities do get knocked out at this point.

                      Again, thank you so much for your detailed reply, going to play around with this now.

                      #Quick Editing#

                      Yes, RecipeID goes from 001 through 3600 at the present time so will look into validation of that to protect from SQL injection once I have this working how I want before setting the whole thing live.

                      I honestly didn't think this pet project would take so long to get up and running, but I'm glad its finally in the process of being built haha
                      Extreme Link List - v1.0

                      Comment

                      • sarettah
                        see you later, I'm gone
                        • Oct 2002
                        • 14293

                        #12
                        edited in: This got posted while you were posting apparently. It is not meant as a response ot your last post but rather a continuation of my post.

                        .................................................. ...

                        OP, You had posted about this same program a while back.

                        https://gfy.com/fucking-around-and-b...-web-page.html

                        Did you revisit that thread at all? Vdbucks gives a nice solution there. You should study the code that he, I and several other people have shown you. If you don't understand the code that you are looking at, play with it, ask questions, play with it some more until you understand exactly what it is doing and why it is doing it.

                        The recipe.php you posted indicates to me that you did not really examine the code at all before yelling for help. If you had, you would see that the comments in there are trying to guide you through how to use it but are not actually providing the code you should be using. For example, it says:

                        // You can now use $_GET['id'] which will be the id number passed
                        // any way you want.

                        // For example using a PDO connection called $pdo
                        It then shows you the code you might choose to use if you had a pdo connection established. It was not intended to be just run, it was intended to be modified before being run.

                        A programmer should never use code that they do not fully understand. Just my opinion, of course.

                        .
                        All cookies cleared!

                        Comment

                        • sarettah
                          see you later, I'm gone
                          • Oct 2002
                          • 14293

                          #13
                          Originally posted by Publisher Bucks
                          Out of interest, is there a specific time/reason I should use mysqli vs PDO in this type of scripting? Also, is there any significant difference in using echo vs print for the output data?
                          Nope. I just went with the mysqli because you already had a working connection in the first program.

                          Myself, I almost always use pdo because it makes the code more portable in that pdo will work with many different databases while mysqli is mysql specific.

                          .
                          All cookies cleared!

                          Comment

                          • k33n
                            Confirmed User
                            • Feb 2009
                            • 201

                            #14
                            Sarettah's approach is better but for learning purposes, check the red notes. Tested.

                            Code:
                            <?php
                                // check incoming params exist
                            
                                if ( ! isset($_GET['id'] ) ) { [COLOR="Red"]//1.you were missing a )[/COLOR]
                                    // missing param, go to an error page for example
                                    header('Location: index.php');
                                    exit;
                                }
                            
                                // You can now use $_GET['id'] which will be the id number passed
                                // any way you want.
                            
                                // For example using a PDO connection called $pdo
                               // [COLOR="Red"]2. Do the PDO connection[/COLOR]
                            
                               $pdo = new PDO("mysql:host=localhost;dbname=yourdbname", "dbusername","dbpass");
                                $table = "Recipes";
                               //[COLOR="red"]3. Your query was looking for a column called id, but your column is called RecipeID[/COLOR]
                               //use this instead
                                  $sql = "SELECT * FROM $table WHERE RecipeID = :id";
                                try {
                                    $stmt = $pdo->prepare($sql);
                            
                                    $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
                                    $stmt->execute();
                            
                                    $rows = $stmt->FetchAll();  // $rows now contains all the results of the query
                                }
                                catch( PDOException $e) {
                                    echo $e-getMessage();
                                }
                                //Added the table as i've seen a </table> below
                                echo "<table border='1'>
                            			<tr>
                            			<th>ID</th>
                            			<th>Title</th>
                            			<th>Method</th>
                            			<th>Ingredients</th>
                            			</tr>";
                                foreach ( $rows as $row ) {
                                    // do things with the $row['column_name'] data
                                   echo "<tr>";
                                   echo "<td>" . $row['Title'] . "</td>";
                                   echo "<td>" . $row['Ingredients'] . "</td>";
                                   echo "<td>" . $row['Method'] . "</td>";
                                   echo "</tr>";
                                }
                              // [COLOR="Red"]4. You are using PDO, mysqli_fetch_array($result) will throw error:  [I][COLOR="Yellow"]mysqli_fetch_array() expects parameter 1 to be mysqli_result[/COLOR][/I].And $result is undefined.  [/COLOR] 
                            
                            while($row = mysqli_fetch_array($result))
                            {
                                echo "<tr>";
                                echo "<td>" . $row['Title'] . "</td>";
                                echo "<td>" . $row['Ingredients'] . "</td>";
                                echo "<td>" . $row['Method'] . "</td>";
                                echo "</tr>";
                            }
                            echo "</table>";
                            ?>

                            Comment

                            • Publisher Bucks
                              Confirmed User
                              • Oct 2018
                              • 1330

                              #15
                              Originally posted by sarettah
                              Did you revisit that thread at all? Vdbucks gives a nice solution there. You should study the code that he, I and several other people have shown you. If you don't understand the code that you are looking at, play with it, ask questions, play with it some more until you understand exactly what it is doing and why it is doing it
                              .
                              I tried running a search on the board for it but couldn't find it, I remembered posting about this issue a few weeks back before getting the rona, just didn't see it in the results.
                              Extreme Link List - v1.0

                              Comment

                              Working...