我想了解PDO人们已经说过简单而且最好的方式与数据库进行交互,但我发现它并不容易。可以帮忙吗?
Connection.php
<?php
class Connection {
public function dbConnect() {
return new PDO("mysql:host=localhost; dbname=lr", "root", "");
}
}
?>
的index.php
<?php
require_once('pdo.php');
$obj = new Connection();
$obj->dbConnect();
echo 'hello';
?>
这很有效,但太简单了。什么是最好的方式?
我应该在自己的类中连接并将其扩展到我的其他类,还是应该使用全局变量进行连接?还是有另一种更好的方法吗?感谢
答案 0 :(得分:1)
在某种程度上,这确实很容易 使用全局变量会更容易。当然,你需要为include包含正确的文件名。
直接来自PDO tag wiki:
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);
的index.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";
答案 1 :(得分:0)
您只是创建一个连接,而不是告诉我们您要实现的目标。您想发布,更新,删除数据库中的内容还是什么?
我能做的最好,因为你没有要求任何东西是链接到一个网站,将尝试教你基本知识。我希望你之前使用过数据库。
http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
答案 2 :(得分:-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();
}
}
?>