SQLI编写的声明

时间:2014-03-26 10:24:09

标签: php mysqli

我已经修改了我的代码,并希望它更应该如何,并感谢大家的帮助,非常感谢

    <?php
$mysqli = new mysqli("localhost", "root", "", "project");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT * FROM users WHERE ? BETWEEN ? AND ?")){



$stmt->bind_param('iii',$weight, $weight1 ,$weight2);

$weight = "weight";
$weight1 = "weight + 1";
$weight2 = "weight - 1";

$stmt->execute();

echo "{$weight}";
echo "{$weight1}";
echo "{$weight2}";

$stmt->close();
}
else {

printf("Prepared Statement Error: %s\n", $mysqli->error);
}
?>

2 个答案:

答案 0 :(得分:2)

首先,帮自己一个忙,不要学习mysqli预备语句,而是考虑使用PDO编写的语句。

接下来,使用您选择的任一方法,您都可以先处理错误报告。

接下来,无论您选择哪种方法,都必须计算占位符。他们来匹配绑定的变量数量。在你的代码中,它们不是。

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "root", "", "project");
$stmt = $mysqli->prepare("SELECT * FROM users WHERE weight BETWEEN ? AND ?");

$stmt->bind_param('ii', $from, $to);
$from = -1;
$to = 1;
$stmt->execute();
$res = $stmt->get_result();
var_dump($res->fetch_assoc());
像这样的事情。但是你需要首先考虑你的逻辑。

答案 1 :(得分:0)

在绑定变量之前,是否需要分配变量?如下

<?php
$mysqli = new mysqli("localhost", "root", "", "project");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$weight = ???;
$betweenOne = ???;
$betweenTwo = ???;

if ($stmt = $mysqli->prepare("SELECT * FROM users WHERE ? BETWEEN ? AND ?")) {

    $stmt->bind_param('iii', $weight, $betweenOne, $betweenTwo);

    $stmt->execute();

    echo $weight;

    $stmt->close();
} else {
    printf("Prepared Statement Error: %s\n", $mysqli->error);
}

注意到您没有传递值,因此我已将它们添加到

修复了结束)感谢评论者:)

查看文档http://php.net/manual/en/mysqli.prepare.php

中的示例