这段带有PDO的代码是否不错(PHP)? [英] Is this code with PDO good (PHP)?

查看:68
本文介绍了这段带有PDO的代码是否不错(PHP)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP的新手,在学习了该语言的基础知识之后,我遵循了一些有关PDO的教程,我只是想知道这里的代码是否正确以及你们会建议我做些什么来改变它您可以更安全,更快,更高效地命名它...

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...

我已经遵循了许多教程来达到这个结果,因此我想问你们,因为并不是Web上的每个PHP教程(数量如此之多)都是学习最佳实践和编写良好代码的可靠来源.

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.

这是我的代码.它仅将字符串"Bill Gates"插入名为"pdotest",表"tableOne"和行"rowOne"的数据库.我使用了持久的数据库连接,因为这可以使Web应用程序更快.我敢肯定,你们可以启发我如何正确使用这种持久连接,我可能还没有完全理解如何在我的代码中使用它.

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

?> 

推荐答案

这显然效率低下,因为您的PHP必须运行比所需次数多两倍的代码.
下面的代码就足够了

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

一些亮点

  • 仅当您肯定知道自己在做什么时才使用持久连接
  • 如果需要例外,请设置例外模式
  • 不要只抓住他们而死. PHP可以自行消亡.

这篇关于这段带有PDO的代码是否不错(PHP)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆