将 SQL 值存储为 PHP 变量(“类 mysqli_result 的对象无法转换为 int”)


Storing an SQL value as a PHP variable ("Object of class mysqli_result could not be converted to int")

目前,我正在尝试将MySQL表中的值存储为PHP中的变量,因此运行一些基本测试以确保我可以访问该变量。我已经设法存储了变量,它将是 1 或 0(1 = 服务器已启动并正在运行,0 = 服务器关闭(。

<?php
$servername = "localhost";
$username = "*****";
$password = "*****";
$dbname = "scicomservers";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT nccpm FROM web_servers WHERE time_checked='2016-02-16 11:44:17.212126'";
$nccpm = $conn->query($sql);
    if($nccpm==1){
      echo("NCCPM Server is running");
    }
$conn->close();
?>

当我运行此代码时,它读取$nccpm为 1,并且它回显该语句,但是,我收到错误:

注意:类 mysqli_result 的对象无法转换为 int /Applications/XAMPP/xamppfiles/htdocs/SciCom_admin_servers/files/connect2.php 在第 17 行

第 17 行是 if 语句:">if($nccpm==1({"。

我在这里看了一下,我认为这可能是因为它试图打印答案数组,但它只会是我将检索的一个值。数据库的列是一个整数。

我想知道,有什么更好的编码方法?这显然不是最佳实践!

谢谢。

$sql = "SELECT nccpm FROM web_servers WHERE time_checked='2016-02-16 11:44:17.212126'";
$ncc = $conn->query($sql);
$nccpm = $conn->fetch_array($ncc);
if ($nccpm['nccpm'] == 1)
{
 // Rest of  script
 }

您需要获取查询或查找返回的行数