我正在尝试使用PHP
将数据添加到2个表中我的PHP代码:insert.php
<?php
session_start();
$db['host'] = "dbhost";
$db['user'] = "user";
$db['pass'] = "pass";
$db['name'] = "dbname";
//making an array with the data recieved
$data = array('f_name' => $_POST['txt_f_name'],
'l_name' => $_POST['txt_l_name'],
'VNum' => $_POST['txtVisaNo']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=".$db['host']."; dbname=".$db['name']."", $db['user'], $db['pass']);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insertall = "BEGIN; "
. "INSERT INTO students (f_name, l_name) "
. "VALUES (:f_name, :l_name); "
. "INSERT INTO visa (students_id, VNum) "
. "VALUES (:LAST_INSERT_ID(), :VNum); "
. "$addStdInf->execute($data); "
. "COMMIT;";
$addStdInf = $dbh->prepare($insertall);
echo 'Success!';
}
catch(PDOException $e){
echo $sql,'<br />', $e->getMessage();
}
$dbh = null;
?>
通知是“成功!”但它没有插入数据库,请指导我ERROR.Thank你。</ p>
答案 0 :(得分:4)
您只是准备声明 - 您永远不会执行它。在prepare
调用之后,您会收到一个准备执行语句,如果您使用某些参数执行它,它将被插入到数据库中:
http://php.net/manual/en/pdostatement.execute.php
答案 1 :(得分:1)
您忘记执行pdo语句
<?php
session_start();
$db['host'] = "dbhost";
$db['user'] = "user";
$db['pass'] = "pass";
$db['name'] = "dbname";
//making an array with the data recieved
$data = array('f_name' => $_POST['txt_f_name'],
'l_name' => $_POST['txt_l_name'],
'VNum' => $_POST['txtVisaNo']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=".$db['host']."; dbname=".$db['name']."", $db['user'], $db['pass']);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insertall = "BEGIN; "
. "INSERT INTO students (f_name, l_name) "
. "VALUES (:f_name, :l_name); "
. "INSERT INTO visa (students_id, VNum) "
. "VALUES (:LAST_INSERT_ID(), :VNum); "
. "$addStdInf->execute($data); "
. "COMMIT;";
$addStdInf = $dbh->prepare($insertall);
$result = $addStdInf->execute();
if ($result) {
echo 'Success!';
} else {
echo 'please check';
}
}
catch(PDOException $e){
echo $sql,'<br />', $e->getMessage();
}
$dbh = null;
?>