Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class st4t
- {
- private $prepared = false;
- private $con;
- private $statement;
- private $query;
- private $bind;
- private $params;
- # Takes a mysqli object, an SQL-Query and an (optional) string specifying the types of data to be send (see mysqli_stmt::bind_param)
- function __construct(&$con,$query,$bind = NULL)
- {
- $this->query = $query;
- $this->bind = $bind;
- $this->con = &$con;
- }
- # Prepares and executes query with the values supplied to the function (read out by func_get_args() to allow for dynamic number of arguments)
- public function execute()
- {
- # Prepare Statement if needed
- if(!$this->prepared)
- {
- if(!($this->statement = $this->con->prepare($this->query)))
- {
- throw new Exception('Failed to prepare query: '.$this->con->error);
- }
- # Bind values if needed
- if(isset($this->bind))
- {
- # create $temp_binds array to pass to bind_param later on
- $temp_binds = array();
- $temp_binds[0]=$this->bind;
- # Assign the parameters by reference to the $this->params array, so we can change them easily later on.
- for($i = 0; $i < strlen($this->bind); $i++)
- {
- $temp_binds[]=&$this->params[$i];
- }
- # Allow variable amounts of parameters
- call_user_func_array(array($this->statement, 'bind_param'),$temp_binds);
- }
- $this->prepared = true;
- }
- # Set values
- if(isset($this->bind))
- {
- # Check if the correct amount of arguments are supplied to the function
- if(strlen($this->bind)==func_num_args())
- {
- # Assign the arguments to the $this->params array so they get sent later
- foreach(func_get_args() as $key => $param)
- {
- $this->params[$key]=$param;
- }
- }
- else
- {
- throw new Exception('Failed to bind as number of params is not enough.');
- }
- }
- # Actually execute the function and fetch/return results or true if nothing is to be fetched
- if(!$this->statement->execute())
- {
- throw new Exception('Failed to execute query: '.$this->statement->error);
- }
- else
- {
- $result = array();
- $variables = array();
- $data = array();
- # Fetch metadata to format our output properly
- $this->statement->store_result();
- $meta = $this->statement->result_metadata();
- # Do we have returned data?
- if($meta)
- {
- # Bind result to $variables so we can read it out step by step
- while($field = $meta->fetch_field())
- {
- $variables[] = &$data[$field->name];
- }
- call_user_func_array(array($this->statement, 'bind_result'), $variables);
- $i = 0;
- # Fetch statements and construct a new associative array for each in the form of [column-name=>column-value]
- while($this->statement->fetch())
- {
- $result[$i] = array();
- foreach($data as $k=>$v)
- {
- $result[$i][$k] = $v;
- }
- $i++;
- }
- # Return array of all entries
- return $result;
- }
- else
- {
- return true;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement