Asked 7 years ago
8 Feb 2017
Views 6125
jaydeep

jaydeep posted

Fatal error: Call to undefined method PDOStatement::exec() in PHP

using PHP / PDO , i made code to use MySQL


$query = $db->prepare($query);
 $query->exec();


and i got error


Fatal error: Call to undefined method PDOStatement::exec() 


Rasi

Rasi
answered Nov 30 '-1 00:00


$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
$PDOstmt= $db->prepare($query);


PDO :: prepare return PDOStatement object.

prepared statement only executed by PDOStatement::execute() method.

mostly prepare statement contain ":name" or "?" (question mark) to replace with real value at execution time. PDOStatement::execute() method do all replacement and execute the SQL query .

so use execute() function instead of exec() function


$PDOstmt->execute();


if you are running create or insert or update query than execute will do run it . but if you want to fetch data from database for select query . execute only create resultset and you need to fetch the data by another function

fetch() and fetchall() function will used to fetch the data


$PDOstmt->execute();
$PDOstmt->fetch();


PDOStatement::fetch() function will fetch data from resulset , it return one row at at time


$PDOstmt->execute();
$PDOstmt->fetchall();


PDOStatement::fetchall() function will fetch data from resulset , it return all data for given SQL query.


Post Answer