English 中文(简体)
Mysqli 获得替代结果
原标题:Mysqli get_result alternative
  • 时间:2012-05-25 10:30:49
  •  标签:
  • php
  • mysqli

我刚刚将所有的 sql 查询修改为使用 Mysqli 准备的语句。 为了加快此进程, 我创建了一个函数( 称为 < code> perperformQuery ), 取代 < code> mysql_query 。 它需要查询、 绑定( 如“ sds” ) 和变量才能通过, 然后将所有渗透的语句内容都传送进来。 这意味着更改我所有的旧语句很容易。 我的函数使用 Mysqli < code> get_ begres () 返回一个 < code> 对象 。

这意味着我可以改变我的旧代码 从:

$query = "SELECT x FROM y WHERE z = $var";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
    echo $row[ x ];
}

$query = "SELECT x FROM y WHERE z = ?";
$result = performQuery($query,"s",$var);
while ($row = mysql_fetch_assoc($result)){
    echo $row[ x ];
}

此功能对本地主机有效, 但我的网络主机服务器没有 Mysqlnd 可用, 因此 < code> get_ result () 无法工作 。 安装 Mysqlnd 不是一个选项 。

What is the best way 至 go from here? Can I create a function which replaces get_result(), and how?

最佳回答

com/ questions/10752815/mysqli-get-result-option/13948854#1394854":

function get_result(mysqli_stmt $Statement): array
{
    $RESULT = array();
    $Statement->store_result();
    $Metadata = $Statement->result_metadata();
    for ($i = 0; $i < $Statement->num_rows; $i++) {
        $PARAMS = array();
        while ($Field = $Metadata->fetch_field()) {
            $PARAMS[] = &$RESULT[$i][$Field->name];
        }
        $Statement->bind_result(...$PARAMS);
        $Statement->fetch();
    }
    return $RESULT;
}

以 Mysqlnd ,您通常会做 :

$Statement = $Database->prepare(  SELECT x FROM y WHERE z = ?  );
$Statement->bind_param(  s , $z );
$Statement->execute();
$Result = $Statement->get_result();
while ( $DATA = $Result->fetch_array() ) {
    // Do stuff with the data
}

且无我的坚固,无我的坚固:

$Statement = $Database->prepare(  SELECT x FROM y WHERE z = ?  );
$Statement->bind_param(  s , $z );
$Statement->execute();
$RESULT = get_result( $Statement );
while ( $DATA = array_shift( $RESULT ) ) {
    // Do stuff with the data
}

因此使用和语法几乎相同。 主要的区别在于替换函数返回结果数组, 而不是结果对象 。

问题回答

I encountered the same problem and solved it using the code provided in the answer of What s wrong with mysqli::get_result?

我的功能现在看起来是这样的(为清楚起见, 错误的处理被剥去) :

  function db_bind_array($stmt, &$row)
  {
    $md = $stmt->result_metadata();
    $params = array();
    while($field = $md->fetch_field()) {
        $params[] = &$row[$field->name];
    }
    return call_user_func_array(array($stmt,  bind_result ), $params);
  }

  function db_query($db, $query, $types, $params)
  {
    $ret = FALSE;
    $stmt = $db->prepare($query);
    call_user_func_array(array($stmt, bind_param ),
                         array_merge(array($types), $params));
    $stmt->execute();

    $result = array();
    if (db_bind_array($stmt, $result) !== FALSE) {
      $ret = array($stmt, $result);
    }

    $stmt->close();
    return $ret;
  }

像这样的用法 :

  $userId = $_GET[ uid ];
  $sql =  SELECT name, mail FROM users WHERE user_id = ? ;
  if (($qryRes = db_query($db, $sql,  d , array(&$userId))) !== FALSE) {
    $stmt = $qryRes[0];
    $row  = $qryRes[1];

    while ($stmt->fetch()) {
      echo  <p>Name:  .$row[ name ]. <br> 
             . Mail:  .$row[ mail ]. </p> ;
    }
    $stmt->close();
  }

我发现匿名建议 rel=“nofollow” 贴在API文件页面上的注 < a href=>>mysqli_stmt:::get_legate 非常有用(我想不出比eval trick更好的方法),因为我们经常想在结果上获取_array()。然而,由于我想满足一个通用的数据库对象,我发现一个问题,即密码假定的数字阵列对所有呼叫者来说都很好,我需要满足所有呼叫者,只使用asoc阵列。

class IImysqli_result {
        public $stmt, $ncols;
}   

class DBObject {

    function iimysqli_get_result($stmt) {
      $metadata = $stmt->result_metadata();
      $ret = new IImysqli_result;
      if (!$ret || !$metadata) return NULL; //the latter because this gets called whether we are adding/updating as well as returning
      $ret->ncols = $metadata->field_count;
      $ret->stmt = $stmt;
      $metadata->free_result();
      return $ret;
   }

   //this mimics mysqli_fetch_array by returning a new row each time until exhausted
    function iimysqli_result_fetch_array(&$result) {
      $stmt = $result->stmt;
      $stmt->store_result();
      $resultkeys = array();
      $thisName = "";
      for ( $i = 0; $i < $stmt->num_rows; $i++ ) {
            $metadata = $stmt->result_metadata();
            while ( $field = $metadata->fetch_field() ) {
                $thisName = $field->name;
                $resultkeys[] = $thisName;
            }
      }

      $ret = array();
      $code = "return mysqli_stmt_bind_result($result->stmt ";
      for ($i=0; $i<$result->ncols; $i++) {
          $ret[$i] = NULL;
          $theValue = $resultkeys[$i];
          $code .= ", $ret[ $theValue ]";
      }

      $code .= ");";
      if (!eval($code)) { 
        return NULL; 
      }

      // This should advance the "$stmt" cursor.
      if (!mysqli_stmt_fetch($result->stmt)) { 
        return NULL; 
      }

      // Return the array we built.
      return $ret;
    }
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签