Insert multiple values in php mysql -
i have here sample code updating multiple value in php mysql. wondering how can insert multiple values?
<?php include('connect.php'); $column1=$mysqli->real_escape_string($_post["column1"]); $column2=$mysqli->real_escape_string($_post["column2"]); $counter=$mysqli->real_escape_string($_post["counter"]); $n = count($counter); for($i=0; $i < $n; $i++) { $result = $mysqli->query("update table set column1='$column1[$i]', column2='$column2[$i]' counter='$counter[$i]'"); } ?>
use standard mysql insert statement mysqli bind_param , php's call_user_func_array.
$n = count($_post['counter']); $query = "insert table (column1, column2) values (?,?)". str_repeat(',(?,?)', $n-1); $st = $mysqli->prepare($query); $placeholders = str_repeat('s', $n*2); $params = array($placeholders); foreach($_post['column1'] $i => $c1) { $c2 = $_post['column2'][$i]; $params[] = $c1; $params[] = $c2; } call_user_func_array(array($st, 'bind_param'), refvalues($params)); $st->execute() or die($mysqli->error); $st->close(); function refvalues($arr){ if (strnatcmp(phpversion(),'5.3') >= 0) //reference required php 5.3+ { $refs = array(); foreach($arr $key => $value) $refs[$key] = &$arr[$key]; return $refs; } return $arr; }
mostly copied here.
Comments
Post a Comment