您应该做的第一件事是创建一个 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();
}
?>