<?php
$hostname = "localhost";
$username = "ODBC";
$password = "";
$dbname = "db_students";
try{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
echo"Connected to database"."<br/>";
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("DELETE FROM enrolments
WHERE student_name = :name");
$stmt->bindParam(":name",$name,PDO::PARAM_STR,255);
$name = "Pietie Kock";
$stmt->execute();
if($student_name > 0)
{
echo "record deleted ". $student_name;
}else{
echo "record doesn't exist". $student_name;
$dbh = null;
}catch(PDOException $e){
echo $e->getMessage();
}
?>
答案 0 :(得分:0)
$student_name
要检查受上一个SQL语句影响的行数,我们使用 rowCount()
$stmt->execute();
if ($stmt->rowCount > 0) {
echo "record deleted " . $student_name;
} else {
echo "record doesn't exist" . $student_name;
$dbh = null;
}
您也忘了关闭try
您的代码
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
echo"Connected to database" . "<br/>";
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("DELETE FROM enrolments
WHERE student_name = :name");
$stmt->bindParam(":name", $name, PDO::PARAM_STR, 255);
$name = "Pietie Kock";
$stmt->execute();
if ($stmt->rowCount > 0) {
echo "record deleted " . $student_name;
} else {
echo "record doesn't exist" . $student_name;
$dbh = null;
}
} catch (PDOException $e) {// close you try
echo $e->getMessage();
}