简体   繁体   中英

Safe way of connecting to database using PHP PDO/MySQL?

I have currently created this code from various tutorials and the PHP Manual (changed personal settings to 123)

$username = "123"; 
$password = "123"; 
$host = "localhost"; 
$dbname = "123"; 

try {
$dbh = new PDO('mysql:host=localhost;dbname=123', $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected";

}
catch(PDOException $e) {
    echo "I'm sorry Charlie, I'm afraid i cant do that.";
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
    $dbh = null;
}

I was just wondering if this is the best/safest way to connect to the database? Other examples i have saw people have uses classes and private and public functions? I am new to PDO and my next steps are to insert, update, and delete data. I have built this before using mysql but thought it would be best to have a full understanding of PDO. Any hints, tips or advice would be great. Thanks!

This is safe but the main problems can occurs while inserting unquoted data (although PDO can be used to do it).

I suggest you to use another database layer (ORM) like Zend_Db or Doctrine , this will make your life really easier and your development safer since they handle some of the tough work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM