I'm fairly new to PHP. I'm in need to bind the parameters in PDO by writing a custom function.
Say these are the 2 sqls I have.
sample_sql_1="select f_name, age, address from table1 where l_name=? and dob >= ? and cty =?"
sample_sql_2="select * from table2 where cty=?"
I would like to write a function that accepts the sql query in question & bind the parameters to be bound to question marks irrespective of how many parameters I pass.
Example: I want to call say,
bind_params(sample_sql_1,array($name,$dob,$cty));
bind_params(sample_sql_2,array($cty));
Here's the function I've writen so far to just connect to the DB
function pdo_db_query($query) {
try {
# MySQL with PDO_MYSQL
$DBH = new dbconn(); // Create DB connection
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
$STH = $DBH->prepare($query);
// Please help to create a dynamic function to bind
bind_params(sample_sql_1,array($name,$dob,$cty));
bind_params(sample_sql_2,array($cty));
/ Execute the query
$STH->execute();
# setting the fetch mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
// Create temporary array variable
$json_arr = array();
while ($row = $STH->fetch()) {
$json_arr[] = $row;
}
# Close the connection
$DBH = null;
// Return the result set as a json
echo json_encode($json_arr);
} catch (PDOException $e) {
echo $e->getMessage();
var_dump($e->getMessage());
}
}
I need help writing the function "bind_params". Any help would greatly benefit me please.