我可以使用这种方法很好地处理mysql数据:
$con = mysqli_connect('127.0.0.1', 'root', 'root', 'root');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$select1 = mysqli_query($con,"SELECT * from review_words");
$record = @mysqli_fetch_assoc($select1);
echo $record['noun'];
我希望这是标准方式。
目前,我采用了一种新方法:
$this->db = new Database($config->getDbHost(), $config->getDbUsername(), $config->getDbPassword(), $config->getDbName());
$this->table = array
(
'users'=>$this->table_prefix.'user_t',
'accounts' => $this->table_prefix.'accounts_t'
)
function getT($name)
{
return $this->table[$name];
}
$this->db->select("SELECT * FROM ".$this->getT('accounts'));
如果表格accounts
的值为name
,id
。如何获取它?
更新
function validateRequest($key)
{
$this->db->select("SELECT user_id FROM ".$this->getT('accounts')."where account_key = '".$key."'");
$data = $this->db->execute();
$userid = $data['user_id'];
$this->db->select("SELECT user_status FROM ".$this->getT('users')."where user_id = '".$userid."'");
$data = $this->db->execute();
$userstatus = $data['user_status'];
}
答案 0 :(得分:1)
以下是将代码放入小类包装器的简短示例。为简单起见,我没有检查错误的用户输入,但通常应该总是这样做。
此示例用于测试目的,当然可以做得更好; - )。
我还没有机会测试这段代码,所以如果有任何错误,请原谅。 这段代码是期待你的数据库有两个表" tb_users"和" tb_accounts"。
数据库包装器:
class Database {
public $db;
private $sql;
public function __construct($host, $user, $password, $database) {
$this->db = new mysqli($host, $user, $password, $database);
/* check connection */
if ($this->db->connect_errno) {
throw new Exception("Failed to connect to MySQL: (" . $this->db->connect_errno . ") " . $this->db->connect_error, 1);
}
}
public function select($table, $cols) {
$colsearch = (is_array($cols)) ? implode(", ", $cols) : $cols;
$sql = "SELECT " . $colsearch . " from " . $table;
}
public function execute() {
if (! is_null($this->sql)) {
$rs = $this->db->query($this->sql);
if($rs === false) {
throw new Exception('Problematic SQL: ' . $this->sql . ' Error: ' . $this->db->error, 1);
} else {
return $rs->fetch_all(MYSQLI_ASSOC);
}
} else {
return null;
}
}
}
模型包装器:
class MyModel {
private $tbl_prefix = "tb_";
private $tables;
public function __construct() {
$this->tables = array(
"users" => $this->tbl_prefix . "users",
"accounts" => $this->tbl_prefix . "accounts"
);
}
public function getTableByName($name) {
if (array_key_exists($name, $this->tables)) {
return $this->tables[$name];
} else {
return null;
}
}
}
执行代码:
$myDatabase = new Database('127.0.0.1', 'root', 'root', 'root');
$myModel = new MyModel();
$myDatabase->select($myModel->getTableByName("users"), array(
"name",
"id"
));
$data = $myDatabase->execute();
foreach ($data as $item) {
print_r($item);
}
希望这对你有所帮助。