Hi, I am chaging from mysql_* to PDO and I found this tutorial in Here
And, so far let's say I chose this query to update a database.
$id = 5;
$name = "Joe the Plumber";
try {
$pdo = new PDO('mysql:host=localhost;dbname=someDatabase', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('UPDATE someTable SET name = :name WHERE id = :id');
$stmt->execute(array(
':id' => $id,
':name' => $name
));
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
But the above code is composed of:
The connection, The query, and The exception.
My problem now, is that I am trying to seperate the connection and expetion and put in external file, and include them just once, like I used to include the mysql connection files in my page ex: database.php
I can't create external file to store the connection & exception because the query needs to be in the middle.
All I want is just somehow include the database connection externally and only run the statement like the below:
to update database.
Now the problem I need to separet the connection from the actuall code Since I have many queries.
include('pdo_connection_file.php');
$stmt = $pdo->prepare('UPDATE someTable SET name = :name WHERE id = :id');
$stmt->execute(array(
':id' => $id,
':name' => $name
));
echo $stmt->rowCount(); // 1
How can I do this?
It used to be easier in mysql as all I had to do was just
include('db.php');
$query = "SELECT * FROM TABLE";
$result = mysql_query....
while(...) {
//..echo data
}