What i want to do is to create a permalink like system such as the wordpress permalink.
For example:
$value = 'abc';
if($query_result > 0){
$value = 'abc1'; // if exists check abc2, abc3, abc4, abc5, etc. etc.
} else{
return $value
}
The query results is a search for the number of rows $query_result = mysql_num_rows
At this moment i created this:
if(!empty($_POST['ajax'])){
if($_POST['ajax'] == 'pages'){
echo prettyName($_POST['title']);
}
}
function prettyName($string)
{
$echo = strtolower(str_replace(array(' ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($string))));
$sql = "SELECT * FROM posts WHERE post_pretty = '".$echo."'";
$res = mysql_query($sql) or die (mysql_error());
$num = mysql_num_rows($res);
if($num){
$echo = $echo.'-'.pretty2($echo, $num);
}
return $echo;
}
function pretty2($echo,$num,$i = 1)
{
$sql = "SELECT * FROM posts WHERE post_pretty = '".$echo.'-'.$i."'";
$res = mysql_query($sql) or die (mysql_error());
$num = mysql_num_rows($res);
if($num){
$i++;
$i = pretty2($echo,$num,$i);
}
return $i;
}
What does it do:
- check if
$value($_POST['title']) exists - convert to a prettystring (by example: a b c = a-b-c)
- check if prettystring exists else +1 (by example: a-b-c exists, a-b-c-1 – a-b-c-9999)
- loop prettystring until free name doesn’t exists.
But what goes wrong is:
if i create a new Post for example:
new post 1 name = testpage // results in testpage
new post 2 name = testpage // results in testpage-1
new post 3 name = test-page // results in testpage-2 // should be test-page
if i create a new Post with to much whitespaces in it it also get’s wrong what could i use to remove all the white spaces? Tried to user TRIM function but that didn’t work. Or should i be using javascript to avoid that?
It will return
abcif num rows are 0PS. try to use PDO for your next development. A good Tutorial
for your problem: