I've already seen a lot of questions similar to mine but mine is different: My error is not caused by the use of a "keyword"
in SQL!
when I run my code, if I cancel the WHERE
clause or I use an hard coded value such as " WHERE customerNumber = 356"
it works fine but if I try to use the value of the variable $custom_n
, it throw an error.
<?php
$custom_n = $_POST["emp"];
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=classicmodels", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn -> prepare("SELECT phone, salesRepEmployeeNumber, creditLimit FROM customers WHERE customerNumber = $custom_n");
$stmt -> execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
?>
If i do an echo to custom_n and gettype i get: 353 string which is what i wanted.
This is the full error:
Connection failed: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
As suggested by Magnus Eriksson, If I do a var_dump($custom_n);
i get this output: string(12) ""
customerNumber = :number
and change the execute to:$stmt->execute([':number' => $custom_n]);
– M. Eriksson