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

时间:2014-11-07 17:42:25

标签: php mysql

我有一个基本的插入记录,用于将用户捕获的数据插入数据库。这是一个非常简单的形式,标题,文章和日期。我想创建一个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();
}

但我不确定如何实现我想要的。

1 个答案:

答案 0 :(得分:0)

看起来你有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