I have been working on a database management page using PHP. Recently I finished the page, and was working on the security aspect, when I ran into a problem with my first SQL query. It was not prepared, and could have empty input. When I tried using the following code to prepare it, it gave an error.
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode='?';";
$stmt1 = $conn->prepare($id_query);
$stmt1->bind_param("s", $barcode);
$stmt1->execute();
$result1 = $stmt1->get_result();
$stmt1->close();
As I understand, it was because it was not recognising the '?'
as a place for parameter binding.
I then tried the following code:
if(isset($_GET["barcode"])) {
$barcode = $_GET["barcode"];
}else{
$barcode = "";
}
# array definition using $barcode
if(isset($_GET["barcode"])) {
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode=?;";
$stmt1 = $conn->prepare($id_query);
$stmt1->bind_param("s", $barcode);
}else{
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode='';";
$stmt1 = $conn->prepare($id_query);
}
$stmt1->execute();
$result1 = $stmt1->get_result();
$stmt1->close();
$result1 = mysqli_fetch_assoc($result1);
And the page just doesn't load.
I am using a Xampp localhost Apache and MySQL server.
If I don't use the last line, $result1 = mysqli_fetch_assoc($result1);
, it fails on the line after, as it can't interpret a mysqli_result
as an array. (The next line is a while loop, not shown here, as it's irrelevant)
I have thought about just adding some checks (the only thing that is passed in is an EAN13 barcode, and using normal
$result1 = mysqli_query($conn, $id_query);
$result1 = mysqli_fetch_assoc($result1);
but would prefer to use prepared statements.
Note: If I print_r()
the $result1
before using the mysqli_fetch_assoc()
on it, I get ~960 rows. It worked fine and fast before I tried preparing the statement.
Minimal reproducible example as requested:
<form action="dash.php" method="get">
Barcode: <input type="text" name="barcode">
<input type="submit">
</form>
<?php # Gets info about the product
$conn = mysqli_connect($hostname, $username, $password, $database);
if(isset($_GET["barcode"])) {
$barcode = $_GET["barcode"];
}else{
$barcode = "";
}
if(isset($_GET["barcode"])) {
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode=?;";
$stmt1 = $conn->prepare($id_query);
$stmt1->bind_param("s", $barcode);
}else{
$id_query = "SELECT sp.name as name, sp.sku_id as sku_id, sp.id as prod_id FROM shop_product as sp WHERE scanbarcode_barcode='';";
$stmt1 = $conn->prepare($id_query);
}
$stmt1->execute();
$result1 = $stmt1->get_result();
$result1 = mysqli_fetch_assoc($result1);
var_dump($result1);
$stmt1->close();