我正在尝试使用PDO将变量的值保存到数据库中,但是我收到Undefined variable
错误。
奇怪的是,我可以在同一代码块中成功回显该变量,但仍然是错误表明该变量未在下一行定义(在echo语句之后)!
以下是代码:
<?php
$sql = "SELECT po_number FROM po ORDER BY po_number DESC LIMIT 1 ;";
$STH = $pdo ->query($sql);
$row = $STH->fetch();
$myVar = $row['po_number'];
?>
<?php
if(isset($_POST['addProduct'])){
echo $myVar; //the variable can be echoed with the expected value here
$sql1 = "INSERT INTO po_parts (po_number, part_id, quantity) VALUES (?,?,?)";
$statement1->bindParam(1, $myVar);
//I am getting error that $myVar is undefined on the previous line
$statement1->bindParam(2, $_POST['part']);
$statement1->bindParam(3, $_POST['quantity']);
if($statement1->execute()){
$message = "Product was added successfully to the order number $newVar";
}else{
$message = "OP's was NOT added successfully.";
}
}
?>
有谁能告诉我这里有什么问题?
谢谢。
答案 0 :(得分:2)
您必须先准备好您的陈述,然后再使用它。
<?php
$sql = "SELECT po_number FROM po ORDER BY po_number DESC LIMIT 1 ;";
$STH = $pdo ->query($sql);
$row = $STH->fetch();
$myVar = $row['po_number'];
?>
<?php
if(isset($_POST['addProduct'])){
echo $myVar; //the variable can be echoed with the expected value here
$sql1 = "INSERT INTO po_parts (po_number, part_id, quantity) VALUES (?,?,?)";
// Inserted this row
$statement1 = $pdo->prepare($sql1);
$statement1->bindParam(1, $myVar);
//I am getting error that $myVar is undefined on the previous line
$statement1->bindParam(2, $_POST['part']);
$statement1->bindParam(3, $_POST['quantity']);
if($statement1->execute()){
$message = "Product was added successfully to the order number $newVar";
}else{
$message = "OP's was NOT added successfully.";
}
}
?>
答案 1 :(得分:1)
在插入之前,您需要准备语句:
$statement1 = $pdo->prepare($sql1);
有关http://www.w3schools.com/php/php_mysql_prepared_statements.asp的MySQLi PDO语法的更多信息。