0

My web service executes this code correctly without any errors:

    $db = mysqli_connect("localhost", $id, $pw, $dbName);
    $query = "INSERT INTO {$tableName} ";
    $query .= "(id, name, address, telephone) VALUES (";
    $query .= "{$id},'";
    $query .= trim($postData->name) ."','";
    $query .= trim($postData->address) ."','";
    $query .= trim($postData->telephone) ."')";                  
    $queryResult = mysqli_query($db, $query);

However, attempting the same with prepared statements throws an error:

    $db = mysqli_connect("localhost", $id, $pw, $dbName);
    $query = "INSERT INTO {$tableName} ";
    $query .= "(id, name, address, telephone) VALUES (?, ?, ?, ?)";
    $statement = mysqli_prepare($db, $query);

    if ($statement) {

        mysqli_stmt_bind_param($statement, 'isss', 
            $id, 
            trim($postData->name),
            trim($postData->address),
            trim($postData->telephone));

        mysqli_stmt_execute($statement);

        $queryResult = mysqli_stmt_get_result($statement);    

    }

    // error:
    // mysqli_stmt_get_result() expects parameter 1 to be mysqli_stmt, boolean given
    // mysqli_prepare fails and returns a false instead of the prepared object

Why is mysqli_prepare() failing here?

iSofia
  • 1,412
  • 2
  • 19
  • 36
  • 1
    you cannot use trim() in bind_param. only variables are allowed. I have a [helper function](https://phpdelusions.net/mysqli/simple) that would help though – Your Common Sense Dec 20 '19 at 10:07
  • @YourCommonSense That was the snag. Quite the temperamental function. Thank you. – iSofia Dec 20 '19 at 10:18

0 Answers0