uneeb uneeb - 1 month ago 16
PHP Question

query execution with prepared statements not working

i am using ajax to display dynamic data on my website! previously it was done using simple mysqli queries now i am improving my website's security by adding prepared statements,i have two queries one is written in mysqli and other in prepared statements here's the mysqli query

$sql = "SELECT DISTINCT model_trim FROM `tbl_02_models` WHERE model_year='$year' and model_name='$model' and model_make_id='$make' ";
$run = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($run)) {
if($row['model_trim']){
$data2[$i]['model_trim']=$row['model_trim'];
$i++;
}
}


and here's the prepared statement query

$query="SELECT DISTINCT model_trim FROM `tbl_02_models` WHERE model_year=? and model_name=? and model_make_id=?";
$stmt = $db->prepare($query);
if($stmt){

$stmt->execute();
$stmt->bind_param("iss",$year,$model,$make);
$stmt->bind_result($model_trim);
while ($stmt->fetch())
{
if($model_trim)
{
$data2[$i]['model_trim']=$model_trim;
$i++;
}

}
$stmt->close();
}


the query written in simple mysqli is working fine but when i am using the same query in prepared statements it is returning me null! any idea?

Answer

Execute method is called after bind the comments.

Try below code :

$query="SELECT DISTINCT model_trim FROM `tbl_02_models` WHERE model_year=? and model_name=? and model_make_id=?";
                $stmt = $db->prepare($query);
                if($stmt){

                    $stmt->bind_param("iss",$year,$model,$make);
                    $stmt->bind_result($model_trim);
                    $stmt->execute();
                    while ($stmt->fetch()) 
                    {
                        if($model_trim)
                        {
                        $data2[$i]['model_trim']=$model_trim;
                        $i++;
                        }

                    }

                        $stmt->close();                 
                    }

For more reference follow this link - http://www.w3schools.com/php/php_mysql_prepared_statements.asp

Comments