-5

I have a string like this 'dubai,sharjah,' and I want to make it like this 'dubai','sharja',

I am passing the value dubai,sharjah, in the URL using ajax and my code

$city=$_GET['city'];

$sql  = "SELECT * FROM filter where isdeleted = 0 ";

if ($city !="" && $city !="Empty" ){
     $sql.=" and twon in ('".$citydata."')";                  
}

when I print the query, it's like this

SELECT * FROM filter where isdeleted = 0 and twon in ('dubai,sharjah,')

but I want it like this

SELECT * FROM filter where isdeleted = 0 and twon in ('dubai','sharja')

Can anyone guide me on how to do this using PHP?

xxx
  • 1,153
  • 1
  • 11
  • 23
Xavi
  • 2,552
  • 7
  • 40
  • 59
  • Where are you getting `$citydata` – JBC May 14 '14 at 05:45
  • If you're trying to generate a sql query that you'll actually use to run a query, I'm going to suggest you stop right there and read this on how to use bind variables: http://www.php.net/manual/en/mysqli-stmt.bind-param.php Better to protect yourself from SQL Injection attacks. – Gary Schreiner May 14 '14 at 05:46
  • `$sql.=" and twon in ('".str_replace(",","','",$citydata)."')";` – chiliNUT May 14 '14 at 05:47
  • 2
    @GarySchreiner `mysqli_stmt::bind_param` is a nightmare when dealing with an array of values. I recommend PDO for this type of thing. – Phil May 14 '14 at 06:23
  • 2
    @Phil I agree, was just trying to get prepared statements across in a hurry before 10 answers showed up :) As I mentioned on a comment to your answer, I find your solution the best option. Unfortunately edit window on comments only last for 5 minutes. – Gary Schreiner May 14 '14 at 06:25
  • [Explode on commas and use a prepared statement](https://stackoverflow.com/a/51036322/2943403) – mickmackusa Aug 19 '22 at 10:19

10 Answers10

4

Here's how I would approach it. I'm going to use PDO instead of mysqli because trying to get an array into mysqli_stmt::bind_param is just a pain.

First, create an array of cities, removing any empty values

$params = array_filter(explode(',', $city), function($c) {
    return !empty($c) && $c !== 'Empty';
});
$paramCount = count($params);

$query = 'SELECT * FROM filter where isdeleted = 0';

Now generate a placeholder string for your prepared statement.

if ($paramCount) {
    $placeholders = implode(',', array_fill(0, $paramCount, '?');
    // looks something like '?,?'

    $query .= " AND twon IN ($placeholders)";
}

Now, prepare a statement

// assuming you have a PDO instance in $pdo created with something like
// $pdo = new PDO('mysql:host=localhost;dbname=your_db;charset=utf8', 'username', 'password', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$stmt = $pdo->prepare($query);

Execute and fetch values :)

$stmt->execute($params);
$filters = $stmt->fetchAll(PDO::FETCH_ASSOC);
Phil
  • 157,677
  • 23
  • 242
  • 245
3
$cities = explode(",", $_GET['city']);

//escape!
foreach ($cities as $citykey => $city) {
    $cities[$citykey] = "'" . mysql_real_escape_string($city) . "'";
}

$sql = "SELECT * FROM `filter` where `isdeleted` = 0";
if (!empty($cities)) {
    $sql .= ' and `twon` in (' . implode(',', $cities) . ')';
}
Mikk3lRo
  • 3,477
  • 17
  • 38
  • 1
    Keep in mind that the *mysql* extension has been officially deprecated and is no longer maintained. – Phil May 14 '14 at 06:31
2

An alternative is to use FIND_IN_SET(). No PHP code change needed.

$sql.=" and FIND_IN_SET(town, '".$citydata."')";   
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

You just have to explode and implode here. Rest is the problem with extra , in your string at the end.

$str = "dubai,sharjah,";
$citydata = implode("','",explode(',',rtrim($str,',')));
echo "'$citydata'";

test

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
1

After 6 answers I gotta add a 7th:

$sql.=" and twon in ('".str_replace(",","','",$citydata)."')";
xxx
  • 1,153
  • 1
  • 11
  • 23
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
1

you can try to explode the string

$cityparts = explode(",",$city);

and you can use

$cityparts[0] and $cityparts[1] in your query 

array explode ( string $delimiter , string $string [, int $limit ] )

you can find more information on [http://www.php.net/explode]

hope this helps!!

Malav Shah
  • 143
  • 2
  • 16
0

You can do this.

$string = 'dubai,sharjah';
$cities = explode(',', $string);

echo $cities[0]; //dubai
echo $cities[1]; //sharjah
Jay Bhatt
  • 5,601
  • 5
  • 40
  • 62
0

try this

$str = "dubai,sharjah,";
$arr = explode(",", $str);
$arr_temp = array()
foreach($arr as $s)
{
   if($s!="")
   {
      $arr_temp[] = "'".$s."'";
   }
}

$new_str = implode(",", $arr_temp); 
echo $new_str;  // output 'dubai','sharjah'

Now your Sql will be

$sql = "SELECT * FROM filter where isdeleted = 0 and twon in ($new_str) ";
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

You can use it in $city I fix two values with, you can use here by $_GET ;

$city = "dubai,sharjah,";
$query_string ="";
$words = explode(",",$city);
for($i=0;$i<count($words);$i++){$query_string .= "'".$words[$i]."',";}
$query_string = substr($query_string,0,strlen($query_string)-4);

then use your query

SELECT * FROM filter where isdeleted = 0 and twon in ($query_string)
xxx
  • 1,153
  • 1
  • 11
  • 23
-2
if ($city !="" && $city !="Empty" )
{
     $city_exp = explode(',' $city);
     $sql .= " and twon in ('".implode("', '", $city_exp)."')"; 
}

What we are basically doing here is putting the two values in an array by using explode and then separating each item in that array by using implode

DEMO

asprin
  • 9,579
  • 12
  • 66
  • 119
  • Doesn't work so well if one of the cities is *Sha'am* or similar ~ http://codepad.viper-7.com/r5F0bi – Phil May 14 '14 at 06:11
  • The value is coming from the URL query string. It could be anything – Phil May 14 '14 at 06:14
  • 2
    This answer encourages poor practices in regards to interacting with databases via PHP. You should be using prepared statements as per the answer by @Phil – Alex.Ritna May 14 '14 at 06:15
  • @Alex.Ritna You're right. But I don't think the OP will make an effort to switch over to PDO/mysqli. – asprin May 14 '14 at 06:17
  • 3
    @asprin IMHO, SO isn't just for the OP, but also for everyone else who finds this question & answer on Google. Maybe a good edit would be: "While this answers your question, here's a better way of doing it that won't be susceptible to attacks." I bet most people searching for something like this probably never would have heard about prepared statements, and this would be their first hint at them. – Gary Schreiner May 14 '14 at 06:20
  • @Alex.Ritna In fairness, [Mikk3lRo's answer](http://stackoverflow.com/a/23646581/283366) also addresses the SQL injection vector though it does use the deprecated *mysql* extension. – Phil May 14 '14 at 06:26
  • @Phil Correct. Neither this answer or the one by Mikk3lRo are the best answer in addressing the question **and** promoting good practice. – Alex.Ritna May 14 '14 at 06:34