我写了一些PHP代码将记录插入到MySQL数据库中。我想显示一条消息,指示记录是否已成功添加到数据库。我试了好几次但是我失败了。
代码:
<?php
try {
$db_user = 'root';
$db_pass = 'cea123';
$db = new PDO( 'mysql:host=localhost;dbname=symposium', $db_user, $db_pass );
$form = $_POST;
$sql = "INSERT INTO app (
firstname, lastname, company, homepage, contactno, addressline1, addressline2, city,
postalcode, country, email, abstractdetails )
VALUES (
:firstname, :lastname, :company, :homepage, :contactno, :addressline1, :addressline2,
:city, :postalcode, :country, :email, :abstractdetails )";
$query = $db->prepare( $sql );
$query->execute( array( ':firstname'=>$firstname, ':lastname'=>$lastname, ':company'=>$company, ':homepage'=>$homepage, ':contactno'=>$contactno, ':addressline1'=>$addressline1, ':addressline2'=>$addressline2, ':city'=>$city, ':postalcode'=>$postalcode, ':country'=>$country, ':email'=>$email, ':abstractdetails'=>$abstractdetails ));
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
答案 0 :(得分:2)
您只需使用rowCount功能
即可查看if($query->rowCount() > 0){
echo "Record Inserted Successfully !!";
}
答案 1 :(得分:1)
在您当前的代码中,您永远不会打印出一个文本,向您显示您的Insert已成功完成。
catch(PDOException $e)
{
echo $e->getMessage();
}
如果出现错误,只会显示错误。
要打印一个文本,告诉你它已成功,你必须在try块的末尾插入(在你的catch块之前)
try {
[...]
if($query->rowCount() > 0){
echo "Record Inserted Successfully !!";
}
} catch(PDOException $e) {
[...]
}