[英]MySQL & PHP: auto connect to DB or to properly way to pass host/db to MySQL methods
有谁知道PHP中已知的方法来自动连接到MySQL数据库/表,以防应用程序在多个主机上使用多个数据库?
问题1:是否有脚本可以根据查询自动连接到必要的主机/数据库?
问题2:如果无法进行上述操作,是否存在已知方法来正确传递主机/数据库信息,以确保在执行查询之前正确连接应用程序?
您应该编写一个包装器类。 此类将具有一个函数query
。 在这里,您有一些选择:
如果使用选项1或2,则可能需要将查询的组成部分拆分为多个参数,因此query
功能看起来更像query($operation, $columns, $tableName, $whereClause, $orderBy)
。 您还可以添加其他参数,但这只是如何执行此操作的示例。
包装器类(我更喜欢的方法)的另一种可能性是创建该类的实例,每个实例都有自己的MySQL连接。 只需为将要使用的每个连接创建该类的一个实例,在脚本的开头连接到该实例,然后对查询使用正确的实例即可。 例如:
<?php
require_once("MYSQL.php");
$db1 = new MYSQL("database1", "username1", "password1", "hostName1");
$db2 = new MYSQL("database2", "username2", "password2", "hostName2");
$index = $db1->query("SELECT * FROM tableOnDB1") or die($db1->error());
while ($result = $db1->fetch($index))
echo $result["column1"];
$index = $db2->query("SELECT * FROM tableOnDB2") or die($db2->error());
list($value) = $db2->fetch($index, "ROW");
echo $value;
?>
这是MYSQL.php:
<?php
class MYSQL_fetch extends MYSQL
{
protected static function fetch($index, $flag = "", $mysql = "")
{
if (empty($mysql))
$mysql = $flag;
if (!$mysql->ivalid($index))
return false;
if ($flag == self::ROW)
$return = mysql_fetch_row($mysql->results[$index][1]);
else if ($flag == self::ARR)
$return = mysql_fetch_array($mysql->results[$index][1]);
else if ($flag == self::OBJ)
$return = mysql_fetch_object($mysql->results[$index][1]);
else
$return = mysql_fetch_assoc($mysql->results[$index][1]);
if ($return === false)
mysql_free_result($mysql->results[$index][1]);
return $return;
}
protected static function querystr($index, $mysql)
{
return $mysql->results[$index][0];
}
}
class MYSQL
{
protected $connection;
protected $db;
protected $type;
protected $results;
protected $errormsg;
protected $valid_instance;
const E_INDEF_METHOD = "Undefined method: ";
const E_INVALID = "Invalid instance of MYSQL";
const E_BOUNDS = "Invalid MYSQL index identifier: ";
const E_FAIL_PROG_MOVE = "Cannot move progression, result is either invalid or out of bounds";
const E_FAIL_PROG_SET = "Cannot set progression, result is either invalid or out of bounds";
const ASSOC = "ASSOC";
const ROW = "ROW";
const ARR = "ARRAY";
const OBJ = "OBJECT";
function __construct($db, $server = "", $username = "", $password = "")
{
if (get_class($this) != "MYSQL")
{
$this->valid_instance = false;
$this->errormsg = self::E_INVALID;
return;
}
$this->valid_instance = true;
$this->errormsg = false;
$this->db = $db;
$this->results = array();
$this->type = "MYSQL_fetch";
$this->connection = @mysql_connect($server, $username, $password, true);
if ($this->connection)
{
if (mysql_select_db($db, $this->connection))
register_shutdown_function(array(&$this, "close"));
else
$this->errormsg = mysql_error();
}
else
$this->errormsg = mysql_error();
}
function __destruct()
{
$this->close();
}
private function valid()
{
return ($this->valid_instance && isset($this->connection));
}
protected function ivalid($index)
{
if (!$this->valid())
return false;
if (is_numeric($index) && $index < count($this->results))
return true;
else
die("error: ". count($this->results));
$this->errormsg = self::E_BOUNDS . $index;
return false;
}
public function query()
{
if (!$this->valid())
return false;
$args = func_get_args();
$sql = trim(array_shift($args));
if (func_num_args() > 1)
{
foreach ($args as $value)
{
$pos = strpos($sql, "?");
if ($pos !== false)
{
if (is_array($value))
{
$new = "(";
foreach ($value as $val)
$new .= "'". mysql_real_escape_string($val) ."', ";
$sql = substr_replace($sql, trim($new, ", ") .")", $pos, 1);
}
else
$sql = substr_replace($sql, "'". mysql_real_escape_string($value) ."'", $pos, 1);
}
}
}
if (!$resource = @mysql_query($sql, $this->connection))
{
$backtrace = debug_backtrace();
if ($this->errormsg == "")
$this->errormsg = "<b>SQL Error at Line ". $backtrace[0]["line"] ." in ". $backtrace[0]["file"] .":</b><br />". mysql_error($this->connection) ."<pre>$sql</pre>";
return false;
}
$this->results[] = array($sql, $resource);
return count($this->results);
}
public function close()
{
if (isset($this->connection))
{
@mysql_close($this->connection);
unset($this->connection);
}
}
public function __call($method, $args)
{
if (!$this->valid())
return false;
if (!method_exists($this->type, $method))
{
$this->errormsg = self::E_INDEF_METHOD . $method;
return false;
}
--$args[0];
$args[] = &$this;
return call_user_func_array($this->type ."::". $method, $args);
}
public function error()
{
if (is_array($this->errormsg))
return htmlentities($this->errormsg["message"]);
return $this->errormsg;
}
public function clearError()
{
$this->errormsg = "";
}
public function affected_rows()
{
return mysql_affected_rows($this->connection);
}
public function insert_id()
{
return mysql_insert_id($this->connection);
}
public function escape($value)
{
return mysql_real_escape_string($value);
}
}
?>
如果使用得当,它还会为您清理输入。 另一个示例:
$mysql->query("SELECT * FROM table WHERE value = ?", $value) or die($mysql->error());
$mysql->query("SELECT * FROM table WHERE value IN ?", array($value1, $value2, $value3)) or die($mysql->error());
$mysql->query("INSERT INTO table (column1, column2) VALUES ?", array($value1, $value2)) or die($mysql->error());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.