0

我想了解 PDO,人们说它很简单,也是与数据库交互的最佳方式,但我发现它并不容易。有什么帮助吗?

连接.php

<?php

class Connection {
    public function dbConnect() {
        return new PDO("mysql:host=localhost; dbname=lr", "root", "");
    }
}

?>

索引.php

<?php
require_once('pdo.php');
$obj = new Connection();

$obj->dbConnect();
echo 'hello';
?>

这行得通,但它太简单了。什么是最好的方法?

我应该在自己的类中建立连接并将其扩展到我的其他类还是应该使用全局变量来连接?还是有其他更好的方法?谢谢

4

3 回答 3

1

在某种程度上,这确实很容易。
使用全局变量会更容易。当然,您需要使用正确的文件名来包含。

直接来自PDO 标签维基:

pdo.php

<?php
$dsn = "mysql:host=localhost;dbname=lr;charset=utf8";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);

索引.php

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

require_once('pdo.php');

$stm = $pdo->prepare("SELECT name FROM table WHERE id=?");
$stm->execute(array($_GET['id']));
$name = $stm->fetchColumn();
echo "Hello $name";
于 2013-04-07T16:57:28.840 回答
0

您只是在建立联系,而不是告诉我们您要达到的目标。您想发布、更新、删除数据库中的某些内容还是什么?

既然您什么都不问,我能做的最好的事情就是将您链接到一个网站,该网站将尝试教您基础知识。我希望你以前用过数据库。

http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/

于 2013-04-07T17:07:01.680 回答
-5

看看这个(https://gist.github.com/dirte/5331258):

<?php
/*
 * PDO Database class
 *
 * Usage:
 * $db = Database::getInstance();
 * Return array of query results, normal statement: $results = $db->query("SELECT * FROM test WHERE name = 'Bob'");
 * Return array of query results, prepared statement (named params): $results = $db->query("SELECT * FROM test WHERE name = :name", array(":name" => "matthew"));
 * Return int of last insert result row id: $db->lastInsertId()
 * Return int of last query result row count: $db->lastQueryRowCount()
 */
class Database {

    /*
     * Instance of the database class
     *
     * @static Database $instance
     */
    private static $instance;

    /*
     * Database connection
     *
     * @access private
     * @var PDO $connection
     */
    private $connection;

    /*
     * Constructor
     *
     * @param $dsn The Data Source Name. eg, "mysql:dbname=testdb;host=127.0.0.1;port=3306"
     * @param $username
     * @param $password
     */
    private function __construct() {
        $this->connection = new PDO("mysql:dbname=".DBNAME.";host=".HOST.";port=".PORT, USER, PASS, array(
                                    PDO::ATTR_PERSISTENT => true,
                                    PDO::ATTR_TIMEOUT => DBTIMEOUT));
        if (empty($this->connection)) {
            trigger_error("Error #D001:", E_USER_ERROR);
            return false;
        }
        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    /*
     * Gets an instance of the Database class
     *
     * @static $instance
     * @return Database An instance of the database singleton class
     */
    public static function getInstance() {
        if (empty(self::$instance)) {
            try {
                self::$instance = new Database();
            } catch (\PDOException $e) {
                trigger_error("Error #D002: ".$e->getMessage(), E_USER_ERROR);
            }
        }
        return self::$instance;
    }

    /*
     * Runs a query using the current connection to the database
     *
     * @param string query
     * @param array $args An array of arguments for the sanitization such as array(":name" => "foo")
     * @return array Containing all the remaining rows in the result set.
     */
    public function query($query, $args = false) {
        $tokens = array_map('trim',explode(" ",trim($query)));
        $query = str_replace(array("\r\n", "\r", "\t"), " ", $query);
        $query = str_replace('    ', ' ', $query);
        try {
            // Prepare results
            $results=false;

            // Allow for rollback if query fails
            $this->connection->beginTransaction();

            // Prepared statements
            $sth = $this->connection->prepare($query);

            // Execute prepared statement, with or without arguments
            if (empty($args)) {
                $sth->execute();
            } else {
                $multiple = false;
                foreach ($args as $arg) {
                    if (!is_array($arg)) { continue; }
                    $multiple = true;
                    break;
                }
                if ($multiple) {
                    $i=0;$j=count($args);
                    foreach ($args as $arg) {
                        foreach ($arg as $k=>$v) {
                            if ($v === "NULL") { $arg[$k] = NULL; }
                        }
                        $sth->execute($arg);
                        $i++;
                    }
                } else {
                    $i=0;$j=count($args);
                    foreach ($args as $a=>$arg) {
                        if ($arg === "NULL") {$args[$a] = NULL;}
                        $i++;
                    }
                    $sth->execute($args);
                }
            }
            // SELECT: Return array of data or false if 0 rows
            if ($tokens[0] == "SELECT") {
                $sth->setFetchMode(PDO::FETCH_ASSOC);
                $results = $sth->fetchAll();
            }
            // INSERT/UPDATE/REPLACE: Return number of affected rows / array of affected ids ?
            // Note: lastInsertId only works if ID col on table is auto_incremented
            elseif ($tokens[0] == "INSERT"
                    || $tokens[0] == "UPDATE"
                    || $tokens[0] == "REPLACE") {

                // If sessions table, assume key = return id
                $results = $this->connection->lastInsertId();
            }
            // Else: Return number of affected rows
            else {
                $results = $sth->rowCount();
            }
            // Attempt to commit changes, triggers exception if fails
            $this->connection->commit();

        // Rollback changes on failure
        } catch (\PDOException $e) {
            $msg = 'query(): ***** Caught Exception! Rolling back changes *****'.PHP_EOL.'<hr />Query:<pre>'.$query.'</pre>'.PHP_EOL.'<hr />Exception Message:<pre>'.$e->getMessage().'</pre><hr />'.PHP_EOL;
            $this->connection->rollBack();
            trigger_error($msg, E_USER_ERROR);
            return false;
        }

        return $results;
    }

    /*
     * Returns the last insert result row id
     *
     * @return int of last insert result row id
     */
    public function lastInsertId() {
        return $this->connection->lastInsertId();
    }

    /*
     * Returns the last query result row count
     *
     * @return int of last query result row count
     */
    public function lastQueryRowCount() {
        return $this->connection->lastQueryRowCount();
    }

}
?>
于 2013-04-07T16:47:43.040 回答