I'm trying to make a query with a PHP variable ($key) from $_POST form data, and I used bindParam to bind the parameter to the variable.
foreach ($_POST as $key => $value) {
if (isset($value) && is_numeric($value)) {
$sql = "SELECT productPrice FROM products WHERE productName=:productName";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':productName', $key, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($result);
}
This returns 'bool(false)' on my page, and I'm not sure why it's doing that. I made sure the $key variable accurately matches the data on the SQL table that I'm querying for.
You are assigning your $key
to $value
foreach ($_POST as $key => $value) {
And after this you are still using $key
instead of $value
in this line
$stmt->bindParam(':productName', $key, PDO::PARAM_STR);
Try using this,
$stmt->bindParam(':productName', $value, PDO::PARAM_STR);
I hope it'll help you.