A Function to Do All My SQL Statements Based On All The Others Comments

Hi, I just write a function to do all my sql statements based on all the others comments in this page, maybe it can be useful for someone else :)

Usage:

execSQL($sql, $parameters, $close);

$sql = Statement to execute;
$parameters = array of type and values of the parameters (if any)
$close = true to close $stmt (in inserts) false to return an array with the values;

Examples:

execSQL("SELECT * FROM table WHERE id = ?", array('i', $id), false);

execSQL("SELECT * FROM table", array(), false);

execSQL("INSERT INTO table(id, name) VALUES (?,?)", array('ss', $id, $name), true);



<?php

function execSQL($sql, $params, $close){
           $mysqli = new mysqli("localhost", "user", "pass", "db");
          
           $stmt = $mysqli->prepare($sql) or die ("Failed to prepared the statement!");
          
           call_user_func_array(array($stmt, 'bind_param'), refValues($params));
          
           $stmt->execute();
          
           if($close){
               $result = $mysqli->affected_rows;
           } else {
               $meta = $stmt->result_metadata();
           
               while ( $field = $meta->fetch_field() ) {
                   $parameters[] = &$row[$field->name];
               } 
       
            call_user_func_array(array($stmt, 'bind_result'), refValues($parameters));
              
            while ( $stmt->fetch() ) { 
               $x = array(); 
               foreach( $row as $key => $val ) { 
                  $x[$key] = $val; 
               } 
               $results[] = $x; 
            }

            $result = $results;
           }
          
           $stmt->close();
           $mysqli->close();
          
           return  $result;
   }
  
    function refValues($arr){
        if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
        {
            $refs = array();
            foreach($arr as $key => $value)
                $refs[$key] = &$arr[$key];
            return $refs;
        }
        return $arr;
    }
?>

http://php.net/manual/en/mysqli-stmt.bind-param.php点击打开链接


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值