1

I ran across something I'm not sure on why it is working. Below I use bind_param and I forgot to set the proper parameter types but somehow it works. By working I mean that the results I get are that the data retrieved is correct. Look at returned values below.

Why is this working and is there any problem with doing it this way ?

Should I remove the bind_param?

I want to keep this as a prepared statement. Would removing the bind_param cause that to stop being a prepared statement?

function getDeviceTypes($conn)
{
    $stmt = $conn->prepare("SELECT deviceTypes_id, deviceTypes_name FROM deviceTypes");
    if (!$stmt)
    {
        header("location: ../index.php?error=cannot_get_device_types");
        exit();
    }
    $types = "";
    $stmt->bind_param("s", $types); // Question about this.
    $stmt->execute();

    $result = $stmt->get_result(); // get the mysqli result
    $data = $result->fetch_all(MYSQLI_ASSOC);
    
    $stmt->close();
    return $data;
}

Returned values

foreach ($data as $d)
{
    // The value is set to the correct id and the name is correct. But I only bind one param ?
    echo "<option value='" . $d['deviceTypes_id'] . "'>" . $d['deviceTypes_name'] . "</option>";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
deathismyfriend
  • 2,182
  • 2
  • 18
  • 25
  • 1
    You appear to be binding a value but not setting anything to bind to in the SQL; the SQL always runs the same and always applies to the whole table so the result will never change as there's no relationship between the bound value (`$types`) and the SQL . you might as well simply use a `query` instead of a prepare becaue you're not actually inserting any variables into the SQL. – Martin Aug 18 '21 at 18:54
  • 1
    You look like you are missing a `WHERE ...` syntax in your SQL – Martin Aug 18 '21 at 18:55
  • @Martin Isn't WHERE only needed when trying to distinguish a value to look for ? I'm trying to grab all rows with all columns of data. Also I'll switch to a query. I'm more interested in knowing why this works. As I don't think that it should. – deathismyfriend Aug 18 '21 at 19:27
  • 1
    Which PHP version are you using? Maybe you are using an older version that doesn't report an error? When I tried with PHP 8 I got a Fatal error – Dharman Aug 18 '21 at 19:45
  • @Dharman 7.3.29-1. Looks like that is most likely the reason then ? – deathismyfriend Aug 18 '21 at 20:07
  • Even on that version it should at least throw a warning. Did you check if you have warnings enabled? – Dharman Aug 18 '21 at 20:08
  • @Dharman Just updated to version 8 it now shows error. – deathismyfriend Aug 18 '21 at 20:14
  • Maybe you have errors supressed or you're not looking in the right place for your error logs? – Martin Aug 18 '21 at 20:17

0 Answers0