php - imploding and adding characters to a string to generate a sql statement -


i received input textarea in format:

value0 value1 value2 value3 

now want explode array, , implode string that

insert `table` (`valuefield`, `myfield`) values ('value0','assignedvalue'), ('value1','assignedvalue'), ('value2','assignedvalue'), ('value2','assignedvalue') 

where assignedvalue fixed.

here did:

$myarray = explode(php_eol, $_post['input']); foreach ($myarray $key => $value) {     $myarray[$key] = trim(preg_replace('/\s\s+/', ' ', $value)); } $data = "('" . implode("','assignedvalue'),'", $myarray) . "'"; $sql = "insert `table` (`valuefield`, `myfield`) values $data"; echo $sql; 

as result, wrong:

insert `table` (`valuefield`, `myfield`) values ('value0','assignedvalue'),'value1','assignedvalue'),'value2','assignedvalue'),'value3' 

also if there better way in regex please.

if want using implode have do:

$data = "('" . implode("','assignedvalue'),('", $myarray) . "','assignedvalue')"; 

a little nicer is:

foreach ($myarray $key => $value) {     $value = trim(preg_replace('/\s\s+/', ' ', $value));     $myarray[$key] = '(\''. $value .'\',\'assingedvalue\')'; } $data = implode(',', $myarray); 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -