我想在我的tbl_category中添加类别。在添加之前,我想检查类别名称是否已存在。我尝试以下代码,但它给了我
致命错误:未捕获的异常' PDOException'
带有消息
SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法出错;
public function save_category($data) {
$category_name = $data['category_name'];
$category_description = $data['category_description'];
$publication_status = $data['publication_status'];
$sql = "SELECT category_name FROM tbl_category WHERE category_name='$category_name' ";
$result = $this->pdo->query($sql);
$num_rows= $result->fetchColumn();
if($num_rows != 0) {
echo 'Category already exist';
}
else {
try {
$query = "INSERT INTO tbl_category(category_name, category_description, publication_status) VALUES(:category_name, :category_description, :publication_status)";
$stmt = $this->pdo->prepare($query);
$stmt->bindParam(':category_name', $category_name, PDO::PARAM_STR);
$stmt->bindParam(':category_description', $category_description, PDO::PARAM_STR);
$stmt->bindParam(':publication_status', $publication_status, PDO::PARAM_INT);
$stmt->execute();
$message = "Save category information successfully";
return $message;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
答案 0 :(得分:0)
答案 1 :(得分:0)
Nishan,使用$ this-> pdo->也可以选择。 并为“rowCount()”更改“fetchColumn()”,查看正确的代码
public function save_category($data) {
$category_name = $data['category_name'];
$category_description = $data['category_description'];
$publication_status = $data['publication_status'];
$result = $this->pdo->prepare("SELECT category_name FROM tbl_category WHERE category_name='$category_name'");
if($result->execute()){
$num_rows= $result->rowCount();
if($num_rows != 0) {
echo 'Category already exist';
}
else {
try {
$query = "INSERT INTO tbl_category(category_name, category_description, publication_status) VALUES(:category_name, :category_description, :publication_status)";
$stmt = $this->pdo->prepare($query);
$stmt->bindParam(':category_name', $category_name, PDO::PARAM_STR);
$stmt->bindParam(':category_description', $category_description, PDO::PARAM_STR);
$stmt->bindParam(':publication_status', $publication_status, PDO::PARAM_INT);
$stmt->execute();
$message = "Save category information successfully";
return $message;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
} else {
echo "error in select";
}
}