I'm trying to swap place-holders with real values from an sql server by querying database and using the execute() function. I know the PDO syntax, but I'm having trouble with the mysqli equivalent.
I've set up, what I think appear to be correct, the mysqli equivalent of preparing the sql query, and executing it, but I receive an error.
Here is the PDO way of doing what I want:
$pdo = new PDO($dsn);
$stmt = $pdo->prepare(
'SELECT
title, created_at, body
FROM
post
WHERE
id = :id'
);
if ($stmt === false)
{
throw new Exception('There was a problem preparing this query');
}
$result = $stmt->execute(
array('id' => 1, )
);
if ($result === false)
{
throw new Exception('There was a problem running this query');
}
// Let's get a row
$row = $stmt->fetch(PDO::FETCH_ASSOC);
Below is the code that I have created for the MySQLi way:
$servername = 'localhost';
$username = 'root';
$password = 'cassie123';
$database = 'blogdb';
//create connection
$conn = new mysqli($servername, $username, $password, $database);
//check connection
if($conn->connect_error){
die('Connection failed: ' . $conn->connect_error);
}
$sql = 'SELECT title, created_at, body FROM post WHERE id = :id';
$stmt = $conn->prepare($sql);
if($sql === false){
throw new Exception('There was a problem preparing this query');
}
$stmt->execute(array('id' => 1, ));
if($stmt === false){
throw new Exception('There was a problem running this query');
}
$row = mysqli_fetch_array($sql, MYSQLI_BOTH);
So what I'm doing is swapping the placeholder which is the ':id') with the int 1 for the id, I know this is static, but I'm basically going to change this later for a variable, but for now I'm trying to assign 1 for the ':id'
I expect the output to print out the title, body, created_at for id = 1 in the mysql database.
The output is:
Uncaught error: Call to a member function execute() on boolean on line 24
I believe the problem has to do with the execute statement, but it looks pretty much identical to the PDO way, so Im trying to figure out the equivalent for MySQLi.