你应该做的第一件事是创建一个mysql.config.php文件。
<?php
define('MYSQL_HOST','');
define('MYSQL_USER','');
define('MYSQL_PASSWORD','');
define('MYSQL_DATABASE','');
?>
你应该做的第二件事是建立负责处理所有的数据库连接信息(模仿这种行为)一个mysql.class.php文件。只需添加新功能来扩展功能,如numRows功能。
<?php
require_once 'mysql.config.php';
class MySQL {
private $query;
private $result;
public function __construct($host = MYSQL_HOST, $user = MYSQL_USER, $password = MYSQL_PASSWORD, $database = MYSQL_DATABASE) {
if (!$con = mysql_connect($host,$user,$password)) {
throw new Exception('Error connecting to the server');
}
if (!mysql_select_db($database,$con)) {
throw new Exception('Error selecting database');
}
}
public function query($query) {
$this->query = $query;
if (!$this->result = mysql_query($query)) {
throw new Exception('Error performing query '.$query);
}
}
public function numRows() {
if ($this->result) return mysql_num_rows($this->result);
return false;
}
}
?>
您需要做的最后一件事就是在您的应用中使用这些文件。
<?php
require_once 'mysql.class.php';
try {
$db = new MySQL();
$db->query('SELECT username FROM login WHERE username = "'.$USERNAME.'" LIMIT 1');
if ($db->numRows() == 1) print_json(array('user'=>true),true);
else print_json(array('user'=>false),true);
} catch(Exception $e) {
echo $e->getMessage();
exit();
}
?>
你在做什么看起来很好。 – bumperbox
如果使用相同的证书进行连接,则重用连接,因此不需太担心;但是,是的,你鼓励尽快从mysql移动路线。 http://php.net/manual/en/mysqlinfo.api.choosing.php – 2012-06-11 03:56:04
@bumperbox它在手册中说,由于“它已被弃用到PHP 5.5.0,将来会被删除”,所以依赖你将来如何使用php你可能会遇到问题,如果它被删除,并且你的主机只有更新版本的php –