I'm new to PHP and I've followed a few tutorials on PDO after learning the basics of the language and I was just wondering if my code here is correct and what you guys'd suggest I can change to make it more secure, faster, more efficient, you name it...
I've followed numerous tutorials to achieve this result and therefore I thought I'd ask you guys as not every tutorial on the web on PHP (there are so many) are reliable sources to learn best practices and writing good code.
Here's the code I have. It only inserts the string 'Bill Gates' to the database, called 'pdotest', table 'tableOne' and row 'rowOne'. I've used persistent db connection because that's supposed to make the web application faster. I'm sure you guys can enlighten me on how to use this persistent connection thing correctly, I may have not fully understood how to use this in my code.
<?php
// DB connect configuration
$user = 'user';
$pass = 'password';
// Database connection
try {
$conn = new PDO('mysql:host=localhost;dbname=pdotest', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
$conn = null;
die();
}
// Data to insert (Bill Gates = Hero #1)
$data = 'Bill Gates';
try {
// The insert query
$sql = "INSERT INTO tableone (rowOne) VALUES (:rowOne)";
$q = $conn->prepare($sql);
$q->execute(array(':rowOne'=>$data));
// Example INSERT query with multiple VALUES
// $q->execute(array(':rowOne'=>$data, ':rowTwo'=>$dataTwo));
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
$conn = null;
die();
}
?>