0

I would like to write a database connection class and I dont understand how I have to write the select method with bind_param-s. Here is the full code. And here the part of the code where I need the help:

public function select($sql){
        $db = $this->connect(); //This methos connect to the DB
        $stmt = $db->prepare($sql); 
        if($stmt === false){ //If the prepare faild
            trigger_error("Wrong SQL", E_USER_ERROR);
        }
        $error = $stmt->bind_param("i", $id);
        if($error){
            return "Error: ".$stmt->error, $stmt->errno;
        }
        $err = $stmt->execute();
        if($error){
            return "Error: ".$stmt->error, $stmt->errno;
        }
        $result =  $stmt->bind_result($id);
        $stmt->close();
        $dbConnection->closeConnection($db);
        return $result;
    }

I need to got it parameters or how can I slove it?

PumpkinSeed
  • 2,945
  • 9
  • 36
  • 62

1 Answers1

0

You need to pass your values into this function too. And eventually bind them into prepared statement.
Optionally you can pass string with types, but by default all "s" will do.

Also remember that you should connect only ONCE per script execution. and then use one single connection all the way throughout your code.

And get rid of all these error checks. Set mysqli in exception mode instead.

public function q($sql, $values = array(), $types = NULL)
{
    $stm = $this->mysql->prepare($sql);
    if (!$types)
    {
        $types = str_repeat("s", count($values));
    }

    if (strnatcmp(phpversion(),'5.3') >= 0)
    {
        $bind = array();
        foreach($values as $key => $val)
        {
            $bind[$key] = &$values[$key];
        }

    } else {

        $bind = $values;
    }

    array_unshift($bind, $types);
    call_user_func_array(array($stm, 'bind_param'), $bind);
    $stm->execute();
    return $stm->get_result();
}

so it can be used like this

$res = $db->q("SELECT name FROM users WHERE id=?", [$id]);

or

$res = $db->q("SELECT name FROM users WHERE id=?", [$id], "i");

your other functions have to be changed as well.

class DB{

    public $con;

    function __construct()
    {
         $this->con = new mysqli("localhost", "root", "", "proba_fferenc");
    }

    public function select(...)
    {
        // as shown above
    }
}
Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • This is good thanx, but where i have storage It dont access the get_result() function. How can i use it with bind_result()? – PumpkinSeed Jul 10 '15 at 15:53