You need to create a PDO object to be able to use prepared statements. Instead you have opened a connection with mysql_connect()
. The two do not mix, and PDO is preferred between them as it is more easily secured through the use of prepared statements (among other reasons).
From the PDO docs:
// This establishes your connection using PDO.
// The PDO connection object is $db
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Pass an associative array to execute()
, rather than a list of arguments representing your placeholders. The
// Now that the PDO object is successfully created, prepare your statement
$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
// Arg to execute() should be an associative array
$stmt->execute(array(':first_name' => $first_name));
The following call to mysql_query()
is unnecessary, as you have already executed the prepared statement with PDO.
// Don't do this
// mysql_select_db("my_db", $con);
// Or this...
//if (!mysql_query($stmt,$con))
//{
// die('Error: ' . mysql_error());
//}
// Or this...
// mysql_close($con)