Bijan
Bijan

Reputation: 8602

PHP: Append every element of array to string/query

I have a string that has a few of URLs separated by a | i.e. http://URL1|http://URL2|...|http://URL#

I am trying to build a string to be used in a query so the result will be:

$query = "OR page_url LIKE '%http://URL1%' OR page_url LIKE '%http://URL2%' OR page_url LIKE '%http://URL3%'"

This string will be added into a query I am preparing

$result = $db->prepare("SELECT * FROM table WHERE column1 = 'abc' :urlquery");
$result->bindValue(':urlquery', $query);

Would this work? Also is this the best way to run the query where I have OR page_url LIKE '% ... %' for every URL?

Upvotes: 1

Views: 84

Answers (3)

Vineet1982
Vineet1982

Reputation: 7918

You have to do like this

$urls="'%" . str_replace("|", "%'|'%", $url) . "%'";

to make the url like this:

'%http://URL1%'|'%http://URL2%'|...|http:%'

now split them

$split = explode('|', $urls);

then implode them:

 $query = implode('OR page like ', $split);

Upvotes: 0

CapeStar
CapeStar

Reputation: 147

$array = explode('|', $numbers);

now you have all the URLs in this array. So you can use it.

Upvotes: 0

Standej
Standej

Reputation: 753

Separating string should be like this

$array = explode('|',$string);

Then you get an array of all urls. Then you can prepare new string

$query = "OR page_url LIKE '%";
foreach($array as $element){
    $query .= $element."%' OR page_url LIKE '%";
}
$query = rtrim($query," OR page_url LIKE '%");

I think now you have your query created to use it

Upvotes: 1

Related Questions