将MySQL查询返回的单列值传递给PHP脚本


Passing a single column value returned by a MySQL query to PHP script

我正在尝试为下面的MySQL查询调整以下代码,但无法解决如何做到这一点。查询应该只返回一行,我想从这行的"code"列中提取数据,并将其作为变量传递给我的PHP脚本。

/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code from Clients where Name='Jane'")) {
    $stmt->execute();
    /* bind variables to prepared statement */
    $stmt->bind_result($code);
    /* fetch values */
    while ($stmt->fetch()) {
        printf($code);
    }
    /* close statement */
    $stmt->close();
}

我认为您一直在基于http://php.net/manual/en/mysqli.prepare.php.然而,你也应该跟进绑定参数:

/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code from Clients where Name=?")) {
    /* bind query parameters to prepared statement */
    $stmt->bind_param("s", 'Jane');
    $stmt->execute();
    /* bind result variables to prepared statement */
    $stmt->bind_result($code);
    /* fetch values */
    if ($stmt->fetch()) {
        printf('Code: %s', $code);
    } else {
        print("Client code was not found");
    }
    /* close statement */
    $stmt->close();
}

你在这里准备对账单,所以你应该单独绑定你的参数。

您可以将代码更改为以下内容:

$value = $stmt->fetch();

此外,如果您知道您想要数据库中的单个值,那么可以通过在sql语句末尾执行'limit 1'来稍微加快速度。

使用:

if ($stmt = $mysqli->prepare("SELECT Code from `Clients` where Name = 'Jane' LIMIT 1")) {
    $stmt->execute();
    $stmt->bind_result($code);
    $stmt->fetch();
    $stmt->close();
}

在脚本的末尾,$code将包含来自列Code的数据。

不要为这样一个琐碎的操作浪费太多代码。看,它几乎有一整屏长
如果在整个代码中需要十几个变量,该怎么办
将所有代码封装到辅助函数中,然后在一行中调用它:

$code = $db->getOne("SELECT Code from Clients where Name='Jane'");