gpt4 book ai didi

php - 添加存储在数据库中的标题时,自动创建 slug

转载 作者:行者123 更新时间:2023-11-29 23:27:57 26 4
gpt4 key购买 nike

我有一个基本的插入记录,它将用户捕获的数据插入到数据库中。这是一个非常简单的表格,包含标题、文章和日期。我也想创建一个 slug 条目。因此,如果我输入:这是一个新闻标题,那么我希望它将其存储在标题列中,同时还将“这是新闻标题”存储在 slug 列中。

我正在使用它来创建连字符:

function create_url_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
}

我有一个这样的插入:

$hostname_slugs = "localhost";
$database_slugs = "slugs";
$username_slugs = "root";
$password_slugs = "root";
try{
$conn = new PDO('mysql:host=$hostname_slugs;dbname=$database_slugs', '$username_slugs', '$password_slugs');

$slug = create_url_slug($_POST['newsarticle']);

//we'll use a prepared statement, which will sanitize our strings for us!
$stmt = $conn->prepare('INSERT INTO news (articledate, newsheadline, headlineslug, newsarticle) VALUES (:articledate, :newsheadline, :headlineslug, :newsarticle)');
$stmt->bindParam(':articledate', $_POST['articledate']);
$stmt->bindParam(':newsheadline', $_POST['newsheadline']);
$stmt->bindParam(':headlineslug', $_POST['headlineslug']);
$stmt->bindParam(':newsarticle', $slug);

$stmt->execute();

echo 'Successfully saved article!';

} catch(PDOException $e){
echo "There was an error: ".$e->getMessage();
exit();
}

但我不知道如何实现我想要的。

最佳答案

看起来您有 headline slug,这正是您想要的。正确的?因此,让我们将其包装在函数 create_url_slug()

create_url_slug(GetSQLValueString($_POST['headlineslug'], "text"))

应该是您所需要的。

让我们按照上述先生的建议使用 PDO 来实现!

try{
$conn = new PDO('mysql:host=host;dbname=yourdatabasename', 'user', 'pass');

$slug = create_url_slug($_POST['newsarticle']);

//we'll use a prepared statement, which will sanitize our strings for us!
$stmt = $conn->prepare('INSERT INTO news (articledate, newsheadline, headlineslug, newsarticle) VALUES (:articledate, :newsheadline, :headlineslug, :newsarticle)');
$stmt->bindParam(':articledate', $_POST['articledate']);
$stmt->bindParam(':newsheadline', $_POST['newsheadline']);
$stmt->bindParam(':headlineslug', $_POST['headlineslug']);
$stmt->bindParam(':newsarticle', $slug);

$stmt->execute();

echo 'Successfully saved article!';

} catch(PDOException $e){
echo "There was an error: ".$e->getMessage();
exit();
}

资源

  1. PDO connection
  2. PDO Prepared Statements

关于php - 添加存储在数据库中的标题时,自动创建 slug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26806968/

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