Concatenated many strings in PHP easily
The following code is correct:
$str = "INSERT INTO table ('".$val1."',"."'".$val2."'".","."'".$val3."'".","."'".$val4."')";
but the code below is incorrect:
$str = "INSERT INTO table ('".$val1."',"."'".$val2."'".","."".$val3."'".","."'".$val4."')";
The above example is small but you can see that larger cases of the above are annoying to debug when one misses out a ' or a ". Is there a better way of concatenating strings in PHP? I want to have variables h开发者_Go百科aving single inverted commas on bother sides and I want the string to be made using double inverted commas.
There must be a better way.. I write a lot of queries from PHP that talk to an Oracle DB and I am constantly making mistakes with these strings!!
Thank you :).
$str = sprintf("INSERT INTO table ('%s', '%s', ...", $val1, $val2);
or use prepared statements
You can try this
$str = "INSERT INTO table ('$val1','$val2','$val3')";
Use prepared statements for that: http://us2.php.net/manual/en/pdo.prepared-statements.php
Never just concatenate arbitrary values to create a SQL statement. You will create millions of SQL injection holes in you application. http://xkcd.com/327/
At the very least, use mysql_real_escape_string or equivalent.
I recommend you do some reading about security and application design before writing any PHP application of consequence.
How about
echo implode(",", array(
'"'.$val1.'"',
'"'.$val2.'"',
'"'.$val3.'"',
));
But I must say that you can do it much easier with prepared statements.
create your own function with http://php.net/manual/en/function.func-get-args.php and foreach, and use sql escapeing for each params. see the example1 on page
When dealing with large param sets I prefer to put them into an array and join with implode()
function.implode like in code below:
$params = array('param1','param2','param3');
$param_string = "('".implode("','", $params)."')";
精彩评论