I'm trying to select a row from a table using mysqli but all I can get is a bunch of null values and I don't really know why. The same query works using normal php mysql and if I try to perform the same query on phpMyAdmin using the parameter I pass goes through fine.
Here's the code:
$con = mysqli_connect('localhost', 'user', 'pass',"db");
if (mysqli_connect_errno()){
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$coupon = $_GET['coupon'];
$sql = mysqli_prepare($con, "SELECT * FROM coupon WHERE coupon=?");
$sql->bind_param('s', $coupon);
$sql->execute();
$sql->store_result();
echo $sql;
returns
"affected_rows":null,
"insert_id":null,
"num_rows":null,
"param_count":null,
"field_count":null,
"errno":null,
"error":null,
"error_list":null,
"sqlstate":null,
"id":null
I already tried to search for an answer either here and on google but I couldn't find anything close to my problem. What am I doing wrong?
author's final solution (moved from question content):
As suggested by user @RiggsFolly I wasn't fetching the results at all, plus I was mixing procedural and OOP approaches as suggested by user @Alex . Here's the working code for future reference to anyone who will arrive here with a similar problem:
$coupon = $_GET['coupon'];
if ($sql = mysqli_prepare($con, "SELECT * FROM coupon WHERE coupon=?;")){
mysqli_stmt_bind_param($sql, 's', $coupon);
mysqli_stmt_execute($sql);
mysqli_stmt_bind_result($sql, $ID, $coupon, $discount, $uses);
mysqli_stmt_fetch($sql);
$data = array(
'ID' => $ID,
'coupon' => $coupon,
'discount' => $discount,
'uses' => $uses
);
echo json_encode($data);
}else{
echo json_encode(FALSE);
}
You must decide if you're using procedural or OOP approach. From your code, it seems you call the procedural version of mysqli extension and afterwards you try using objects. See the documentation examples, both object oriented and procedural and decide on a single one.