php - Dynamic mysqli prepared statement -


i need creating method dynamic mysqli prepared statements. code below has errors. know i'm off way mysqli_stmt_bind_param set can't figure out solution. coding style strange since i'm using oo php, procedural mysqli. haven't had time figure out oo mysqli since books , videos read/watch use procedural mysqli. of solutions i've seen problem use oo mysqli. i'd prefer short-term fix rather having learn pdo after spent time learning mysqli.

public function create($sql, $param_type, $param){     //param_type should set $param_type = "'ssss'" single quotes passed variable     //param should array     //param array items should escaped     $stmt = mysqli_prepare($this->dbc, $sql);     mysqli_stmt_bind_param($stmt, $param_type, join(array_values($param), ", "));     $result = mysqli_stmt_execute($stmt);      if($result){         return true;     } else{         return false;     }     mysqli_stmt_close($stmt); } 

to use oo mysqli simple:

  1. change every mysqli_blah($this->dbc) call $this->dbc->blah().
  2. change every mysqli_stmt_blah($stmt) call $stmt->blah().
  3. profit!

also, always check return value prepare() , execute(). return false when there's error in parsing or execution, , need check these , report errors every time.

the mysqli_stmt_bind_param() function tricky because expects variable number of arguments, 1 each letter in param type argument, not string of comma-separated values. also, requires pass variables reference, not scalars, , not single array.

  • wrong: mysqli_stmt_bind_param($stmt, "sss", "red,green,blue");

  • wrong: mysqli_stmt_bind_param($stmt, "sss", "red", "green", "blue");

  • wrong: mysqli_stmt_bind_param($stmt, "sss", $param_array);

  • right: mysqli_stmt_bind_param($stmt, "sss", $param1, $param2, $param3);

this makes difficult , confusing you're doing: writing general-purpose function prepare , execute sql statement dynamic number of parameters. have use call_user_func_array() have rewrite array of arguments array of references.

i wrote examples in couple of past answers:

pdo solves more easily, don't have bind anything, pass array execute().


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -