gpt4 book ai didi

php - 使用 PHP 将行插入 MySQL 数据库时如何确保没有现有的帖子标题?

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:27 25 4
gpt4 key购买 nike

我正在使用以下函数将数据插入 MySQL 数据库。

有人可以更新它以便在标题列中已经有名称为“My Test Post”(不区分大小写)的标题时返回错误消息吗? (我不想要任何重复的帖子)

public function insert() {
// Does the Article object already have an ID?
if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR );

// Insert the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO articles ( publicationDate, title, summary, content ) VALUES ( FROM_UNIXTIME(:publicationDate), :title, :summary, :content )";
$st = $conn->prepare ( $sql );
$st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->bindValue( ":summary", $this->summary, PDO::PARAM_STR );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->execute();
$this->id = $conn->lastInsertId();
$conn = null;
}

最佳答案

$sql = "SELECT title from articles where title=:title";
$st = $conn->prepare ( $sql );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->execute();
if($st->rowCount()>0) print "error";
else{

$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO articles ( publicationDate, title, summary, content ) VALUES ( FROM_UNIXTIME(:publicationDate), :title, :summary, :content )";
$st = $conn->prepare ( $sql );
$st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->bindValue( ":summary", $this->summary, PDO::PARAM_STR );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->execute();
$this->id = $conn->lastInsertId();
$conn = null;

}

不区分大小写:

$sql = "SELECT title from articles where LOWER(title)=:title";
$st->bindValue( ":title", strtolower($this->title), PDO::PARAM_STR );

关于php - 使用 PHP 将行插入 MySQL 数据库时如何确保没有现有的帖子标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6864346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com