dongmu2026 2014-03-19 16: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 16: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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图