【问题标题】:Fetching one value from mysql using mysqli fails使用 mysqli 从 mysql 获取一个值失败
【发布时间】:2015-08-03 00:01:14
【问题描述】:

我想使用 mysqli 从 mysql 获取单个值,但我的代码没有为我获取值。这是我的代码

<?php
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "my_journals";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$stock_type = 'vehicle_certificates';

$old_amount = mysqli_fetch_assoc(mysqli_query($conn,'SELECT amount FROM stock WHERE stock_type='."$stock_type".' limit 1'));

$newer_amount = $old_amount['amount'];
echo $newer_amount;

mysqli_close($conn);
?>

我收到这个错误

警告:mysqli_fetch_assoc() 期望参数 1 为 mysqli_result, 第 16 行 C:\wamp\www\journals_debug.php 中给出的布尔值

是什么导致我的代码无法工作?

【问题讨论】:

  • 使用准备好的语句。你的很多错误都会自动修复。

标签: php mysqli


【解决方案1】:

当查询进入数据库时​​,您没有引号。

'SELECT amount FROM stock WHERE stock_type='."$stock_type".' limit 1'

应该是

'SELECT amount FROM stock WHERE stock_type="'.$stock_type.'" limit 1'

目前到达数据库时是:

SELECT amount FROM stock WHERE stock_type=vehicle_certificates limit 1

我认为会抛出 1064,但您没有看到,因为未检查返回。

您需要封装引号,否则 PHP 会处理它们。

如果该值不是静态的,这可能会使您面临 SQL 注入。您应该使用准备好的语句。

第三种方法可能是

"SELECT amount FROM stock WHERE stock_type='$stock_type' limit 1"

作为准备好的声明,http://php.net/manual/en/mysqli.quickstart.prepared-statements.php,可能是这样的:

$conn->prepare("SELECT amount FROM stock WHERE stock_type=? limit 1");
$stmt->bind_param("s", $stock_type);
$stmt->execute();

使用准备好的方法,您无需担心正确引用输入。这是自动处理的。

【讨论】:

    【解决方案2】:

    我会这样做:

    $results = mysqli_query..

    然后使用它来获取错误:

       if (!$result) {
         echo("Error description: " . mysqli_error($conn));
       }
    

    http://www.w3schools.com/php/func_mysqli_error.asp

    【讨论】:

    猜你喜欢
    • 2018-06-30
    • 2014-09-19
    • 2020-10-06
    • 2015-09-19
    • 1970-01-01
    • 2023-03-21
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多