php - Using arrays/strings for mysqli prep statement -
i'm running issue mysqli prepared statement. it's rookie mistake; i'm not familiar things this. appreciated.
i have 2 arrays, $alpha[]
, $bravo[]
. both have 20 pairings, simplify:
$alpha = array('name', 'age', 'color'); $bravo = array( 'name' => 'john doe', 'age' => 22, 'color' => 'blue', );
i want insert data $bravo[]
table defining column headers $alpha[]
, binding data $bravo[]
query, , executing query. here's example of want do:
$columns = implode(',', $alpha); $query_values = '?,?,?'; $query = "insert table ($columns) values ($query_values)"; $type = 'sis'; $real_values = implode(',', $bravo); if($stmt = $mysqli->prepare($query)){ $stmt->bind_param($type, $real_values); if($stmt->execute()){ // success } }
this not working me - or insight guys can offer (including other ways accomplish want do) appreciated.
change bind_param
$stmt->bind_param($type, $bravo[0], $bravo[1], $bravo[2]);
while above works, it's not perfect solution requires change parameters mysqli_bind_param
every time want add/remove column data.
here's solution, in example of proper workflow:
// returns array of associative values function ref_array_keys($arr) { $refs = array(); foreach ($arr $key => $value) { $refs[$key] = &$arr[$key]; } return $refs; } $data = array('name' => 'john doe', 'email' => 'user@domain.com', 'color' => 'red'); $type = 'sss'; $cols = implode(',', array_keys($data)); $vals = implode(',', array_fill(0, count($data), '?')); $query = "insert table_name ($cols) values ($vals)"; if ($stmt = new mysqli($query)) { call_user_func_array(array($stmt, "bind_param"), array_merge(array($type), ref_array_keys($data))); }
ref_array_keys() function source: https://stackoverflow.com/questions/3681262/...
Comments
Post a Comment