Tuesday 4 September 2018

if / else does not work in PHP

I have created a search for on my website and dependent what term is written in the string, it needs to run a different php code.

For example people could type in #rtp drum and bass music it will then do the php code for that.
Another is if some types in “radio that plays drum and bass music” I will then need it to run a different code.
Finally, some one could type #rtp robbie williams songs it will also need it to run different code. My code below does not work though. Any ideas?
if(preg_match('[#rtp|music]', $a)){
    preg_match('/#rtp (.*) music/', $a, $match);
    $tags = $match[1];
}

if(preg_match('[radio|that|plays|music]', $a)){
    preg_match('/plays (.*) music/', $a, $match);
    $tags = $match[1];
}

if(preg_match('[#rtp|songs]', $a)){
    preg_match('/#rtp (.*) songs/', $a, $match);
    $tags = $match[1];
}

$tags = explode(' ', $tags);
$tags = implode("%' OR `tags` LIKE '%", $tags);
$result1 = mysql_query("SELECT * FROM `Stations` WHERE `tags` LIKE '%$tags%'" );
$num_rows1 = mysql_num_rows($result1);

echo $num_rows1;


You must replace the two last if with elseif, otherwise $tags will be overwritten.
if(preg_match('[#rtp|music]', $a)){
    preg_match('/#rtp (.*) music/', $a, $match);
    $tags = $match[1];
}
elseif(preg_match('[radio|that|plays|music]', $a)){
    preg_match('/plays (.*) music/', $a, $match);
    $tags = $match[1];
}
elseif(preg_match('[#rtp|songs]', $a)){
    preg_match('/#rtp (.*) songs/', $a, $match);
    $tags = $match[1];
}

if (!empty($tags)) {
    ...

As an aside comment, using square brackets as pattern delimiters is not the best choice of the universe since it is confusing with character classes. I suggest to replace them with a slash:
if(preg_match('/#rtp|music/', $a))

0 comments:

Post a Comment