0

Users of my site can submit post title and post content by form. The post title will be saved and converted to SEO friendly mode (eg: "title 12 $" -> "title-12"). this will be this post's url.

My question is if a user entered a title that is identical to previous entered title, the url's of those posts will be identical. So can be the new title be modified automatically by appending a number to the end of the title?

eg:

"title-new" -> "title-new-1" or if "title-new-1" present in db convert it to "title-new-2"

I'm sorry I'm new to this, maybe it's very easy, Thanks for your help.

I'm using PDO.

4

3 回答 3

0

thank you @Ratna & @Borniet for your answers. i'm posting explained code to any other user who want's it. if there is somrthing should be added or removed or better way please let me know.

//first i'm going to search the "new unchanged title name" whether it's present in db.

$newtitle= "tst-title";   
$dbh = new PDO("mysql:host=localhost;dbname='dbname', 'usrname', 'password');
$stmt = $dbh->prepare("SELECT * FROM `tablename` WHERE `col.name` = ? LIMIT 1");
$stmt->execute(array($newtitle));
if ( $stmt->rowCount() < 1 ) {
// enter sql command to insert data
    }
else {
$i='0';
do{
$i++;
$stmt = $dbh->prepare("SELECT * FROM `tablename` WHERE `url` = ? LIMIT 1");
$stmt->execute(array($newtitle.'-'.$i));
}
while($stmt->rowCount()>0);
// enter sql command to insert data
}

that's it. the reason i'm dividing in to two is because i want to add '-' to the url instead of just number.

于 2013-05-11T01:57:53.873 回答
0

在您的数据库中选择该标题,然后使用 rowCount() 检查您有多少结果。如果结果为0:可以添加,如果结果为n,则在标题中添加n。

要追加使用这样的东西(不正确):

$count = $del->rowCount(); //Assuming this returns 1

if($count){
  $title = $title . "-" . $count;
}

这会给你“theduplicatetitle-1”

于 2013-05-10T12:54:14.863 回答
0

保存帖子标题时,您可以查询数据库是否存在?如果它存在,只需附加一个数字并再次查询,如果它再次存在,则将其加一,因此。

于 2013-05-10T12:48:33.903 回答