0

我真的是使用 mysqli 实现 OOP 的新手,我有这个名为 Database 的 Object(Class),我真正的问题是如何在 index.php 中调用我的 select 方法以及如何使用它

数据库 Class.php 如下:

Class Database{
private $host = null;
private $user = null;
private $pass = null;
private $db = null;
public $error = "Error Po Sir!";
public $con;


public function connect($host, $user, $pass, $db){

    $this->host = $host;
    $this->user = $user;
    $this->pass = $pass;
    $this->db = $db;

    $this->con = mysqli_connect($this->host, $this->user, $this->pass);
        if(mysqli_connect_errno()){
            echo "Connection Failed %s\n!", mysqli_connect_error();
            exit();
        }

}

public function select($condition){
    $query = "select os_user from users WHERE os_user = {$condition}";
    $result = mysqli_query($this->con,$query);
    return $result;
}
} 

这就是我如何实现它:

    require 'templates/dbclass.php'; 
$db = new Database();
$db->connect("localhost", "root", "", "os_db");
$username = $_POST['username'];
if($result = $db->select($username)){
    echo $username;
    if($result->num_rows > 0){
        while($row = $result->fetch_object()){
            echo $row->os_id;
        }
    }
}

但它没有显示任何结果。当var_dump($result)我得到bool(false).

我启用了错误报告,但没有显示错误。

4

1 回答 1

0

select您的功能存在 3 个问题

  • is 易受 SQL 注入攻击
  • 它没有错误检查
  • 这是没用的

这是必须的

public function query($sql, $bind)
{
    $db = $this->con;
    $stm = $db->prepare($sql) or trigger_error($db->error." [$sql]");
    $types = str_repeat("s", count($values));
    array_unshift($bind, $types);
    call_user_func_array(array($stm, 'bind_param'), $bind);
    $stm->execute() or trigger_error($db->error." [$sql]");
    $stm->store_result();
    return $stm->get_result();
}

像这样使用

$sql = "select os_user from users WHERE os_user = ?";
$res = $db->select($sql, $_POST['username']));
while($row = $result->fetch_object()){
    echo $row->os_id;
}
于 2013-08-10T13:31:56.427 回答