Reputation: 826
I was trying to learn MySqli prepared statements, but i got stuck in dynamic binding.
This is my code. this is working fine but i am getting all the results instead of user_id=1. not sure what i am missing here. please help me..
public function prepareSelectSql($from,$feilds="*",$where = '',$bind=false,$params)
{
if($this->conn)
{
$query = "SELECT ".$feilds." FROM `".$from."`";
$stmt = $this->conn->prepare($query);
if($stmt === false)
{
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $this->conn->errno . ' ' . $this->conn->error, E_USER_ERROR);
}
if($bind)
{
echo "<br/><br/>";
echo $query .= $where;
$id='1';//call_user_func_array(array($stmt, 'bind_param'), $params);
$stmt->bind_param("i",$id);
echo "<br/><br/>Here";
}
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc())
{
print_r($myrow);
}
}
else { echo "Not Aavailable";}
}
i am calling this function as below.
$where = 'WHERE `ID`=?';
$params = array('i','1');
$feilds = '`user_nicename`';
$this->db->prepareSelectSql('wp_users',$feilds,$where,true,$params);
Upvotes: 1
Views: 462
Reputation: 12039
In $bind
condition you concat your SQL
but you prepare it before condition. I suggest you to prepare query after completing full query string.
$query = "SELECT ".$feilds." FROM `".$from."` ";
if($stmt === false){
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $this->conn->errno . ' ' . $this->conn->error, E_USER_ERROR);
}
if($bind){
$query .= $where;
$stmt = $this->conn->prepare($query);
$id = '1';
$stmt->bind_param("i",$id);
}else{
$stmt = $this->conn->prepare($query);
}
Upvotes: 2