我有一个基本的插入记录,它将用户捕获的数据插入数据库。这是一个非常简单的表格,有标题、文章和日期。不过我也想创建一个slug条目。所以,如果我键入:这是一个新闻标题,那么我希望它将其存储在标题列中,但也将this-is-news-title存储在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
段塞,这正是您想要的。正确的让我们把它封装在函数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();
}
资源
- PDO连接
- PDO编制的报表