0

我正在创建一个自定义数据库类以满足我正在开发的公司的要求。我目前有这个:

class DBC {

    protected $Link;
    protected $Results;

    public function __construct($Host = null,$User = null ,$Pass = null,$Database = null){
        if ($Host === null OR $User === null OR $Pass === null OR $Database === null){
            trigger_error("Incorrect Parameters Passed In The Database Link", E_USER_WARNING);
        }
        if (is_string($Host) AND is_string($User) AND is_string($Pass) AND is_string($Database)){
            $this->Link = new mysqli($Host,$User,$Pass,$Database);
        }else{
            trigger_error("Expecting String(s), Array passed in one or more connection parameters",E_USER_ERROR);
        }
    }
    public function Query ($Query,$Params){
        $Query = $this->Link->prepare($Query);
        $Query->bind_param();
    }


}

现在..我遇到了如何将参数成功绑定到准备好的语句的问题。例如,将提交一个查询:

$DB = new DBC("Host","User","pass","database");
$DB->Query("SELECT * FROM Test WHERE Col=?",array("SearchCriteria"));

我在弄清楚如何根据结果绑定参数和绑定结果时遇到了困难。一个更清晰的认识是 MySQLi 的正常过程:

$SearchCriteria = "String";
$Query = $Database->prepare("SELECT * FROM Test WHERE Col=?");
$Query->bind_param('s',$SearchCriteria);
$Query->execute(); 
$Query->bind_results(/* Variables to match the column set */);
$Query->fetch();
$Query->close();

如何将结果和参数绑定到准备好的语句?

4

1 回答 1

1

下面是我在扩展 mysqli 类的类中使用的函数的副本,这些函数可以满足您的要求。

function bind_placeholder_vars(&$stmt,$params,$debug=0) {
    // Credit to: Dave Morgan
    // Code ripped from: http://www.devmorgan.com/blog/2009/03/27/dydl-part-3-dynamic-binding-with-mysqli-php/
    if ($params != null) {
        $types = '';                        //initial sting with types
        foreach ($params as $param) {        //for each element, determine type and add
            if (is_int($param)) {
                $types .= 'i';              //integer
            } elseif (is_float($param)) {
                $types .= 'd';              //double
            } elseif (is_string($param)) {
                $types .= 's';              //string
            } else {
                $types .= 'b';              //blob and unknown
            }
        }

        $bind_names = array();
        $bind_names[] = $types;             //first param needed is the type string
                                // eg:  'issss'

        for ($i=0; $i<count($params);$i++) {    //go through incoming params and added em to array
            $bind_name = 'bind' . $i;       //give them an arbitrary name
            $$bind_name = $params[$i];      //add the parameter to the variable variable
            $bind_names[] = &$$bind_name;   //now associate the variable as an element in an array
        }

        if ($debug) {
            echo "\$bind_names:<br />\n";
            var_dump($bind_names);
            echo "<br />\n";
        }
        //error_log("better_mysqli has params ".print_r($bind_names, 1));
        //call the function bind_param with dynamic params
        call_user_func_array(array($stmt,'bind_param'),$bind_names);
        return true;
    }else{
        return false;
    }
}



function bind_result_array($stmt, &$row) {
    // Credit to: Dave Morgan
    // Code ripped from: http://www.devmorgan.com/blog/2009/03/27/dydl-part-3-dynamic-binding-with-mysqli-php/
    $meta = $stmt->result_metadata();
    while ($field = $meta->fetch_field()) {
        $params[] = &$row[$field->name];
    }
    call_user_func_array(array($stmt, 'bind_result'), $params);
    return true;
}

但是,听起来您正在做的事情类似于我已经做过的事情,并且已经在许多项目中使用了一段时间。将此 pastebin ( better_mysqli.php ) 的内容复制到一个新文件中并将其命名为“better_mysqli.php”

然后在你的 php 程序中使用它,如下所示:

// include the class
include_once('better_mysqli.php');


// instantiate the object and open the database connection
$mysqli = new better_mysqli('yourserver.com', 'username', 'password', 'db_name');
if (mysqli_connect_errno()) {
      die("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()), 'error');

}

// do a select query
$sth = $mysqli->select('select somecol, othercol from sometable where col1=? and col2=?', $row, array('col1_placeholder_value', 'col2_placeholder_value'));

while ($sth->fetch()) {
    echo "somecol: ". $row['somecol'] ."<br />\n";
    echo "othercol: ". $row['othercol'] ."<br />\n";
}

// the nice thing about this class is that the statement is only prepared once so if you use it again the already prepared statement is automatically used:

// do another select query with different placeholder values
$sth = $mysqli->select('select somecol, othercol from sometable where col1=? and col2=?', $row, array('other_col1_placeholder_value', 'other_col2_placeholder_value'));

while ($sth->fetch()) {
    echo "somecol: ". $row['somecol'] ."<br />\n";
    echo "othercol: ". $row['othercol'] ."<br />\n";
}

// the class supports the following methods:  select, update, insert, and delete


// example delete:
$mysqli->delete('delete from sometable where col1=?', array('placeholder_val1'));
于 2013-06-20T17:16:02.260 回答