ale
ale

Reputation: 11820

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 having 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 :).

Upvotes: 0

Views: 96

Answers (6)

veritas
veritas

Reputation: 2052

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)."')";

Upvotes: 0

Poomalairaj
Poomalairaj

Reputation: 5048

You can try this

$str = "INSERT INTO table ('$val1','$val2','$val3')";

Upvotes: 3

sirbrialliance
sirbrialliance

Reputation: 3692

Use prepared statements for that: https://www.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.

Upvotes: 2

sarkiroka
sarkiroka

Reputation: 1542

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

Upvotes: 0

sanmai
sanmai

Reputation: 30881

How about

echo implode(",", array(
   '"'.$val1.'"',
   '"'.$val2.'"',
   '"'.$val3.'"',
));

But I must say that you can do it much easier with prepared statements.

Upvotes: 0

zerkms
zerkms

Reputation: 254906

$str = sprintf("INSERT INTO table ('%s', '%s', ...", $val1, $val2);

or use prepared statements

Upvotes: 5

Related Questions