dongmu2026 2014-03-19 08:13 采纳率: 100%
浏览 48
已采纳

这个代码与PDO好(PHP)? [关闭]

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();
}

?> 

展开全部

  • 写回答

1条回答 默认 最新

  • duandao2306 2014-03-19 08:18
    关注

    this is apparently inefficient as your PHP have to run twice more code than needed.
    the below code is enough

     <?php
    
    // DB connect configuration
    $user = 'user';
    $pass = 'password';
    // Database connection
    $dsn = "mysql:host=localhost;dbname=pdotest;charset=utf8";
    $opt = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    $conn = new PDO($dsn, $user, $pass, $opt);
    
    $data = 'Bill Gates';
    
    $sql = "INSERT INTO tableone (rowOne) VALUES (?)";
    $q = $conn->prepare($sql);
    $q->execute(array($data));   
    

    some highlights

    • use persistent connection only if you certainly know what are you doing
    • set exception mode if you are expecting exceptions
    • DO NOT catch them only to die. PHP can die all right by itself.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部