Thursday, 30 August 2018

The PDO query does not display the results?

Okay so i am new to PDO statements so i am unsure if i have done a syntax error or whatnot. The php file does not show any errors:

<?php
    include('db_config.php');
    $itemName = 'Item1';

    $sql = "SELECT * FROM order WHERE itemName = $itemName;";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        echo $row['itemName'];
    }
?>

My objective is to pull an item using bootstraps datepicker, but for the purpose of this testing i am using the itemName. The php file comes up blank?
I have checked the field names, db_config, and am unsure where the issue is coming from.
Please let me know if i have done an error in my statement or anything that seems wrong.

Firstly, you're using a MySQL reserved word, being order and it requires special attention; mainly using ticks around it.
Then since we're dealing with a string, $itemName needs to be wrapped in quotes.
<?php
    include('db_config.php');
    $itemName = 'Item1';

    $sql = "SELECT * FROM `order` WHERE itemName = '$itemName';";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        echo $row['itemName'];
    }
?>

  • Either use ticks around your table name, or rename it to "orders", it's not a reserved keyword.
"The php file does not show any errors:"
That's because you're not checking for them.
Add $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); right after the connection is opened.


As per a comment you left under your question containing the MySQL error:
1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order
  • Read it near 'order it starts at "order".

Now, if ever your query should ever contain any character that MySQL will complain about, such as a quote etc. then you will need to escape your query and use prepared statements.
For example, if using:
$itemName = "Timmy's Sour Dough";

would translate to
WHERE itemName = 'Timmy's Sour Dough'

in turn throwing a syntax error.
So, it's best to immediately escape any data right away.
Edit
Your use of prepare and new to PDO collectively suggest that you are already trying to use prepared statements, just not the right way. You're just a little off from a well prepared statement. One correct way in your code would be
  $sql = "SELECT * FROM `order` WHERE itemName = ? ";
  $stmt = $conn->prepare($sql);
  $stmt->execute(array($itemName));

Notice how we have a ? in your query then we are sending a value for it in your execute call. There you go :)

0 comments:

Post a Comment