sashomaga

Prepared statements

Oct 22nd, 2013
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.22 KB | None | 0 0
  1. <?php
  2. $con = mysqli_connect('localhost', 'root', '', 'books');
  3.  
  4. // ? - placeholders
  5. $sql = 'SELECT * FROM users WHERE user_name=? AND user_pass =?';
  6. $sql2 = 'INSERT INTO users () VALUES (?,?)';
  7.  
  8. $stmt = mysqli_prepare($con, $sql);
  9. if($stmt){
  10.     echo 'sql is OK';
  11. }
  12. //bind params to placeholders
  13. //second param - data type first letter e.g. string 's', integer 'i' for each param
  14. mysqli_stmt_bind_param($stmt,'ss',$_POST['user'], $POST['pass']);//
  15. mysqli_stmt_execute($stmt);
  16.  
  17. // bind query result to variable for each column
  18. //mysqli_stmt_bind_result($stmt, $user_id);
  19. //take result
  20. //while(mysql_stmt_fetch($stmt)){
  21.     //echo $user_id;
  22. //};
  23.  
  24. ///dynamically create bind params
  25. //gives metadata for column count etc.
  26. $rows = mysqli_stmt_result_metadata($stmt);
  27. while($field = mysqli_fetch_field($rows)){
  28.     // collection of column names
  29.     // values will be stored by reference $stmt->bind_result() in $row array
  30.     $fields[] = &$row[$field->name];
  31. }
  32. //call function of object -> array($stmt, 'mysqli_stmt_bind_result') $stmt->bind_result()
  33. //call function with params from array
  34. call_user_func_array(array($stmt, 'bind_result'), $fields);
  35. while(mysqli_stmt_fetch($stmt)){
  36.     //results column_name -> value
  37.     print_r($row);
  38. };
Advertisement
Add Comment
Please, Sign In to add comment