PDO query doesn't display results?

Ok, so I'm new to PDO statements, so I'm not sure if I made a syntax error or anything else. There are no errors in the php file:

<?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 goal is to pull an item using bootpraps datepicker, but for this testing I use itemName. Is the php file empty?

I checked the field names, db_config and don’t know where this problem came from.

Please let me know if I made a mistake in my statement or something that seems to be wrong.

+4
source share
3 answers

First, you use the MySQL reserved word , which is order, and this requires special attention; mainly using ticks around it.

, , $itemName .

<?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'];
    }
?>
  • , "", ​​ .

" php :"

, .

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); .



, , MySQL:

1064 SQL; , MySQL, "order

  • near 'order "".

, - - , MySQL, , .., .

, :

$itemName = "Timmy Sour Dough";

WHERE itemName = 'Timmy Sour Dough' 

, .

, .

Edit

prepare new to PDO , , . .

  $sql = "SELECT * FROM `order` WHERE itemName = ? "; 
  $stmt = $conn->prepare($sql);
  $stmt->execute(array($itemName));

, ?, execute. :)

+4

, PDO. - , , :

$itemName = 'Item1';

$sql = "SELECT * FROM order WHERE itemName = ?"; 
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $item, PDO::PARAM_STR);
$stmt->execute();

bindParam().


script :

ini_set('display_errors', 1);
error_reporting(E_ALL);

.

+1

, sql . itemName varchar, , :

$sql = "SELECT * FROM order WHERE itemName = '$itemName';"; 
0

Source: https://habr.com/ru/post/1585015/


All Articles