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/
Related
I know I have done this before. I am not sure why I am struggling to do something so simple.
All I am trying to do is add a single quote to a comma separated string.
The php process initially looks like this:
<?php
$checknumber = mysqli_real_escape_string($dbc,trim($_POST['checknumber']));
$splitnumber = preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$checknumber )));
$numbers = "'" . implode("', '", $splitnumber ) ."'";
echo $checknumber;
echo $splitnumber;
echo $numbers;
?>
The results look like this:
// $checknumber
AMD111111,AMD222222,AMD333333
// $splitnumber
AMD111111,AMD222222,AMD333333
// $numbers
''
I need the results of $numbers to look like this:
'AMD111111','AMD222222','AMD333333'
The funny thing is I am using a piece of code I've used before that works. So I am at a loss as to why the code is not working here.
The implode() function requires an array as second argument.
It looks like your $splitnumber is just a simple string not an array of strings as it should probably be.
Try splitting your $splitnumber by commas using the explode() function and put the result of that in the implode function.
Should look like that (not tested):
$splitnumber = ...;
$splittedNumbers = explode(",", $splitnumber);
$numbers = "'" . implode("', '", $splittedNumbers) ."'";
There is probably a cleaner solution by just replacing all occurences of , with ','.
Your implode isn't setup correctly.
$numbers = "'" . implode("','", $splitnumber) . "'";
I am using the following code for adding the singles quotes for a string
$gpids=implode("','",array_unique($groupIds));
My output coming like these
156','155','161','151','162','163
I want my output like these
'156','155','161','151','162','163'
please help me
Using concatenation operator
$gpids = "'".implode("','",array_unique($groupIds))."'";
Just concate quote :
<?php
$gpids="'" . implode("','",array_unique($groupIds)) . "'";
echo $gpids;
?>
You have two options:
Simple one:
$string = "'" . implode("','",array_unique($groupIds)) . "'";
Second one:
function add_quotes($str) {
return sprintf("'%s'", $str);
}
$string = implode(',', array_map('add_quotes', array_unique($groupIds)));
Try this
$query=$key.'='."'$value'".',';
Here $value will have single quotes.
This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";
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'
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