dotif64826 2013-08-10 11:59
浏览 50
已采纳

Mysqli oop方法调用

I'm really new to implementing OOP using mysqli things, I have this Object(Class) named Database, my real problem is how would I call my select method in my index.php and how can I use it

Database Class.php is below:

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
!", 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;
}
} 

this is how did I implement it:

    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;
        }
    }
}

But it does not show any results. When I var_dump($result) I get bool(false).

I've enabled error reporting, but there is no errors displayed.

  • 写回答

1条回答 默认 最新

  • dpzff20644 2013-08-10 13:31
    关注

    There are 3 issues with your select function

    • is is vulnerable to SQL injection
    • it does no error checking
    • it is useless

    Here is how it have to be

    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();
    }
    

    used like this

    $sql = "select os_user from users WHERE os_user = ?";
    $res = $db->select($sql, $_POST['username']));
    while($row = $result->fetch_object()){
        echo $row->os_id;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。