Search code examples
phpsql-serverpdoprepared-statement

I am trying to execute it but it throws error of 'SQLSTATE[IMSSP]: This function is not implemented by this driver.'


I have tried calling the function but it gives me errors always. My code is below

$name = 'Devrishi Pandey';
$return_message = prepared_insert($pdo, 'my_table', ['name' => $name]);
function prepared_insert($pdo, $table, $data) {
    $keys = array_keys($data);
    $fields = implode(",", $keys);
    $placeholders = str_repeat('?,', count($keys) - 1) . '?';
    try{
        $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
        $pdo->prepare($sql);
        $pdo->execute($data);
        return $pdo->lastInsertId();
    } catch(PDOException $e){
        return $sql . "<br>" . $e->getMessage();
    }
}

Solution

  • The execute function is for a PDOStatement, not connection. You need to assign the prepared statement to a variable then execute on that.

    $name = 'Devrishi Pandey';
    $return_message = prepared_insert($pdo, 'my_table', ['name' => $name]);
    function prepared_insert($pdo, $table, $data) {
        $keys = array_keys($data);
        $fields = implode(",", $keys);
        $placeholders = str_repeat('?,', count($keys) - 1) . '?';
        try{
            $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($data);
            return $pdo->lastInsertId();
        } catch(PDOException $e){
            return $sql . "<br>" . $e->getMessage();
        }
    }