Jump to content


Function To Add To Database Using Prepared Statements And Binding Parameters Dynamically

  • Please log in to reply
1 reply to this topic

#1 masterlayouts


    Advanced Member

  • Members
  • PipPipPip
  • 64 posts

Posted 18 March 2012 - 12:00 AM

I've seen this on nettuts, but similar functions are on PHP site. The function is used to display/view/read the results of a query using prepared statements by binding the result dynamically.


function read()
$parameters = array();
$results = array();

$mysql = new mysqli('localhost', 'root', 'root', 'db') or die('There was a problem connecting to the database');

$stmt = $mysql->prepare('SELECT product, price, category FROM products') or die('Problem preparing query');

$meta = $stmt->result_metadata();

while ( $field = $meta->fetch_field() ) {

$parameters[] = &$row[$field->name];

call_user_func_array(array($stmt, 'bind_result'), $parameters);

while ( $stmt->fetch() ) {
$x = array();
foreach( $row as $key => $val ) {
$x[$key] = $val;
$results[] = $x;

return $results;


$results = read();

I am trying for days to make something similar to add to databse and I fail mainly because when I bound the parameters I have to specify the type of data. Also I am not sure how or where should a MySQL function go - like SHA1(?) in values. Is it possible to create such a function that adds to database with parameters specified dynamically? I am interested to know at least if it's possible to make such a thing, maybe there it is impossible and I am trying for nothing. Some directions will be nice (or even a piece of code?).
  • 0

#2 Larry



  • Administrators
  • 4916 posts
  • LocationState College, PA (USA)

Posted 26 March 2012 - 4:13 PM

Yeah it is possible (almost everything is), but I question the merits of this exercise. This is already a fairly poor design that I wouldn't recommend trying to build upon it. Rather I'd start it off correctly from the scratch.
  • 0