Home > Back-end >  Take some strings plus date and insert into MySQL
Take some strings plus date and insert into MySQL

Time:10-22

I am trying to fix a script for seo-friendly url and it is almost working but my brain is almost dead trying to understand why I get the wrong value in MySQL

The script uses the following values to prepare the variables to be inserted:

$date=date("Ymd");
$newtitle=string_limit_words($title, 6);
$urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
$newurltitle=str_replace(" ","-",$newtitle);

Nothing strange with that, but now I am fixing the following variable to prepare the mysqli insert and this is the one with problem:

$url='news/'.$date.'/'.$newurltitle.'';

To submit the query I use the following code:

mysqli_query($con,"insert into blog(title,body,url) 
values('$title','$body','$url')");
}

The result saved in MySQL should be something like this:

news/20221021/this-is-an-example-url

But the result I get saved in MySQL is this:

news/.$date./.$newurltitle.

So the values are not passing, I tried using $url='news/'$date.'/'$newurltitle.''; and $url='news/'.$date'/'.$newurltitle''; but no one of them will work. Any ideas why ?

CodePudding user response:

I can't explain the result you're getting if the code you posted is accurate. You'd get that result if you wrote

$url = 'news/.$date./.$newurltitle.';

because variables are not expanded inside single quotes. However, you can write that simply using double quotes.

$url = "news/$date/$newurltitle";
  • Related