什么是mysqli准备的声明等同于此?

时间:2015-12-24 12:22:28

标签: php mysqli

我有这段代码

$query = mysql_query("SELECT * FROM users ORDER BY exp DESC LIMIT ".$lim.", 10");

while($row = mysql_fetch_array($query))

但是mysqli与此相当的是什么(具有准备好的陈述)。我无法相处。

3 个答案:

答案 0 :(得分:0)

未经测试,但它应该是这样的。 什么是$ lim变量?是自定义方式来显示LIMIT是什么?

     $query = $mysqli->query("SELECT * FROM users ORDER BY exp DESC LIMIT ".$lim.", 10");

if ($stmt = $mysqli->prepare($query)) {


        $stmt->execute();

        //NOTE: depends on your SQL statement, you bind your columns here, and store into var. I don't know how many columns you need to bind with your select statement, but idea is like this.

        $stmt->bind_result($var1, $var2, var3, *(and so on)*);

        while ($stmt->fetch()) {
            printf ("%s (%s)\n", $name, $code);
        }

        $stmt->close();
    }

答案 1 :(得分:0)

预准备语句占位符只能在SQL允许表达式的位置使用,但LIMIT要求其参数为文字。由于您无法在那里使用占位符,因此mysqli等效版基本上与mysql版本相同,使用预准备语句并没有任何好处。唯一的区别是mysqli_query需要连接对象作为其第一个参数。

$query = mysqli_query($conn, "SELECT * FROM users ORDER BY exp DESC LIMIT ".$lim.", 10");
while($row = mysqli_fetch_array($query)) {
    ...
}

答案 2 :(得分:0)

以下是一个例子:

$limit = 10;
$user = "john";
$sql="SELECT * FROM users WHERE first_name = ? ORDER BY exp DESC LIMIT ?";
$stmt = $db->stmt_init(); // Initiate prepared statement

if(!$stmt->prepare($sql)){// prepare query, but if it fails get store the error in $error. echo error if you are debugging
   $error = $stmt->error;
 }else{
    $stmt->bind_param("si", $user, $limit);//bind values -- Must be variable --list them by order. First parameter is the data type, and the rest are values to bind
// Data types include "i" - for integer, "d" - for decimal integer, "s" - for string and "b" - for BLOB
    $stmt->execute();//execute the prepared statement
    $result = $stmt->get_result(); //store mysql object so that you can use it later to fetch_array or num_row
  }

//Using the $result mysqli object we stored
$numrows=$result->num_rows;// Get total number of rows
if(!numrows){
    echo "No results found";
    }else{
      while($row = $result->fetch_assoc()){
      echo $row['first_name'];
    }
}