0

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

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.

Community
  • 1
  • 1
eaponz
  • 574
  • 1
  • 16
  • 32

1 Answers1

0

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;
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345