Jump to content
Larry Ullman's Book Forums

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


Recommended Posts

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.

 

<?php

 

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');

$stmt->execute();

 

$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?).

Link to comment
Share on other sites

  • 2 weeks later...

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.

Link to comment
Share on other sites

 Share

×
×
  • Create New...