本文介绍了调整选择方法以接受多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要实现一个方法 select() 可以绑定一个或多个参数和另一个将结果返回到 index.php 的方法.
I need to implement a method select() that can bind one or more parameters and another method which will return the result to index.php.
从 index.php 调用的所需代码:
Desired code called from index.php:
echo $this->_results -> korisnik_id;这是需要实现select()的数据库类.当前 Select() 函数接受一个参数...
this is the database class which need to implement select(). the present Select() function accepts one parameter...
DB::getInstance() -> Select('SELECT korisnik_id FROM korisnici WHERE korisnik_ime= ?', 's', 'Alex');...但不多:
DB::getInstance() -> Select('SELECT korisnik_id FROM korisnici WHERE korisnik_ime= ? AND korisnik_grupa= ?','si', 'Alex', '1');全班:
<?php class DB{ private static $_instance = null; private $_stmt,$_query,$_error=false,$_results,$count=0; public function __construct() { try{ $this-> _stmt = new mysqli(Config::get('mysql/host'),Config::get('mysql/username'),Config::get('mysql/password'),Config::get('mysql/db')); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } } catch (Exception $ex) { } } public static function getInstance(){ if(!isset(self::$_instance)){ self::$_instance = new DB(); } return self::$_instance; } public function Select($query, $paramString = ''){ $stmt = $this->_stmt->prepare($query); if (func_num_args() > 2){ $parameters = func_get_args(); array_shift($parameters); // remove the query from the list // Array needs to be bound by reference foreach ($parameters as $key=>&$value) { $parameters[$key] = &$value; } call_user_func_array(array($stmt, "bind_param"), $parameters); } $stmt->execute(); $this->_results = $stmt->get_result(); $stmt->close(); $this->_results = $this->_results -> fetch_object(); echo $this->_results -> korisnik_id; } } ?> 推荐答案我觉得你已经很接近了.
I think you're pretty close.
用这样的东西代替你当前的 forach 循环怎么样:
How about something like this in the place of your current forach loop:
foreach ($parameters as $key=>&$value) { $this->_stmt->bindParam ($key, $value, PDO::PARAM_STR); }更多推荐
调整选择方法以接受多个参数
发布评论