Add quotation marks to comma delimited string in PHP - php

I have a form which is a select multiple input which POSTs values like this: option1,option2,option3 etc..
How is the best way to convert this to 'option1','option2','option3' etc...
Currenty I'm doing this, but it feels wrong??
$variable=explode(",", $variable);
$variable=implode("','", $variable);
The reason why I'm doing this is because I want to use the form select multiple inputs in a SQL Query using IN.
SELECT * FROM TABLE WHERE some_column IN ('$variable')

You can wrap whatever code in a function to make the "feels wrong" feeling disapear. E.g.:
function buildSqlInClauseFromCsv($csv)
{
return "in ('" . str_replace(",", "','", $csv) . "') ";
}

If $variable = "option1,option2,option3"
you can use:
"SELECT * FROM TABLE WHERE FIND_IN_SET(some_column, '$variable')"

Here is what I used:
WHERE column IN ('".str_replace(",", "','", $_GET[stringlist])."')

we know that implode converts array to string,we need to provide the separator and then array as shown below, here we have (coma ,) as a separator.
Implode breaks each element of an array with the given separator,I have conceited '(single quotes) with the separator.
$arr = array();
$arr[] = "raam";
$arr[] = "laxman";
$arr[] = "Bharat";
$arr[] = "Arjun";
$arr[] = "Dhavel";
var_dump($arr);
$str = "'".implode("','", $arr)."'";
echo $str;
output: 'raam','laxman','Bharat','Arjun','Dhavel'

There is only one correct way to escape strings for SQL - use the function provided by the database api to escape strings for SQL. While mysyl_* provides mysql_real_escape_string():
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = "'".mysql_real_escape_string($choice)."'";
$choices = implode(",", $choices);
PDO provides a method that will add quotes at the same time:
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = $pdoDb->quote($choice);
$choices = implode(",", $choices);
Note that PDO::prepare doesn't really work here

Related

PHP Convert a string of comma separated values into another format without using a loop

In php, if I had a string of comma separated data like this which came from a database:
John,Paul,Ringo,George
how could I convert it to something like this, without using a for loop or any extra processing. Does php have a function that can do this?
$str = 'John','Paul','Ringo','George';
I currently split the string using explode and then reformat it. Anyway to achieve this without doing that?
The formatted string is sent to a SQL where it's used in a MySQL IN() function.
If you absolutely don't want to use explode() you could use
$str = 'John,Paul,Ringo,George';
$newStr = "'" . str_replace(",","','", $str) . "'";
You can use preg_replace with $1 thing.
UPDATED:
See usage example:
echo preg_replace('((\\w+)(,?))', '"$1"$2', 'John,Paul,Ringo,George');
you can use explode like below
$db_data = 'John,Paul,Ringo,George';//from your db
$l = explode(',',$db_data);
echo "select * from table where column IN('".implode("','",$l)."')";
output:
select * from table where column IN('John','Paul','Ringo','George')
You can use the explode and implode functions in PHP.
$names = explode(',', 'John,Paul,Ringo,George');
echo implode(',', $names);
I hope I got you right:
$str_1 = 'John,Paul,Ringo,George';
$str_2 = explode(',', $str_1);
$str_3 = implode('\',\'', $str_2);
$str_4 = '\''.$str_3.'\'';
echo $str_4;
Output: 'John','Paul','Ringo','George'
$l = 'John,Paul,Ringo,George';
$lx = "'" . implode("','", explode(",", $l)) . "'";
echo $lx; // 'John','Paul','Ringo','George'

split array inside single quotes without using loop

I have array of Ids (123456,654789,395855). I will need to split it with single qoute and comma to be able to use it in mysql query. In fact I need this for IN() function.
Is there any native php function that puts all array nodes inside quotes (retrieve string ) without using any loop?
so far I come up with this. but I am looking at better way.
$ids = array(123456,654789,395855);
foreach ($ids as $id){
$stringIds .= "'". $id . "',";
}
$stringIds = rtrim ($stringIds, ",");
debug($stringIds);
Just use implode() as usual, with some extra quotes before/after:
$ids = array(123456,654789,395855);
$string = "'" . implode("','", $ids) . "'";
No, there is not a native function that does this. What you have will work just fine.
You can use implode and array_map to achieve this:
implode(', ', array_map(function($id) { return "'$id'"; }, $ids));
You can use array_map and implode you may also look into array_reduce
$ids = array(123456,654789,395855);
$quoted = array_map(function($id) { return "'$id'"; }, $ids);
$stringIds = implode(', ', $quoted);
echo $stringIds;
See the ideone
You can separate an array into single quotes and comma separated list using php's implode function.
$array = array(123456,654789,395855);
$comma_list = "'" .implode("', '", $array) . "'";
echo $comma_list;
Here is reference to an article.
http://codingcyber.com/how-split-array-single-quotes-and-comma-separated-list-php-57/

separate with commas

hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);

How do I place a comma between each character in a string with PHP? [duplicate]

hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);

How to remove last comma (,) from array?

I've gone through this address:
Passing an array to a query using a WHERE clause
and found that if I use a join clause to separate values , is also at the end of the array. How can I remove last?
I am using like this
$ttst=array();
$ttst=array();
$tt = "SELECT frd_id FROM network WHERE mem_id='$userId'";
$appLdone = execute_query($tt, true, "select");
foreach($appLdone as $kk=>$applist){
$ttst[] = $applist['frd_id'];
}
$result = implode(',', $ttst);
then also coming last ,
Thanks.
but it doesn't give single quote to each value .
join(',', array_filter($galleries))
array_filter gets rid of empty elements that you seem to have. Of course, you should take care not to have empty elements in there in the first place.
You could use trim() (or rtrim()):
$myStr = 'planes,trains,automobiles,';
$myStr = trim($myStr, ',');
$str = "orange,banana,apple,";
$str = rtrim($str,',');
This will result in
$str = "orange,banana,apple";
Update
Based on your situation:
$result = implode(',', $ttst);
$result = rtrim($result,',');
$arr = array(...);
$last = end($arr);
unset($last);
If the trailing "," is an array element of itself, use array_pop(), else, use rtrim()
$array = array('one','two',3,',');
array_pop($array);
print_r($array);
Gives:
Array ( [0] => one 1 => two 2 => 3
)
No need for length. Just take from beginning to the (last character - 1)
$finalResult = $str = substr($result, 0, -1);
Use implode() instead! See Example #1 here http://php.net/manual/en/function.implode.php
Edit:
I think a quick fix would be (broken down in steps):
$temp = rtrim(implode(',', $ttst), ','); //trim last comma caused by last empty value
$temp2 = "'"; //starting quote
$temp2 .= str_replace(",", "','", $temp); //quotes around commas
$temp2 .= "'"; //ending quote
$result = $temp2; // = 'apples','bananas','oranges'
This should give you single-quote around the strings, but note that if some more values in the array are sometimes empty you will probably have to write a foreach loop and build the string.

Categories