MySQL 中的 CONCAT 函数使用 PHP 未定义变量

CONCAT function in MySQL using PHP Undefined Variable

我需要有关如何正确执行此操作的帮助。我需要执行这个命令:

SELECT concat(branchname, -->, itemtype, '(, quantity, ')') from monitoring
order by itemtype;

语法在 MySQL 控制台中有效。但是,我在 php 上实施它时遇到了麻烦。我总是得到 "Undefined index: branchname" "Undefined index: itemtype" "Undefined index: quantity"

使用此代码:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dex_test";

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

$sql = "SELECT concat(branchname,itemtype,quantity) from monitoring order by itemtype";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);

错误说在这一行

echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";

我很困惑,因为我基本上 运行 使用相同的代码让我在 table 中看到项目类型:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dex_test";

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

$sql = "SELECT itemtype FROM monitoring";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "itemtype: " . $row["itemtype"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);

帮助任何人?

只需定义串联列的别名。使用这个 -

SELECT concat(branchname,itemtype,quantity) as branchname from monitoring order by itemtype

或者,如果您希望它们分开,那么 -

SELECT branchname, itemtype, quantityfrom monitoring order by itemtype

您的查询似乎需要更新

"SELECT concat(branchname,itemtype,quantity) from monitoring order by itemtype";

应该是

"SELECT branchname,itemtype,quantity from monitoring order by itemtype";

我已发布此答案以参考您如何在 while 循环中调用字段

echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";

如果您需要在一个字段中显示 concat 值,它应该类似于

$sql = "SELECT concat(branchname,' ',itemtype,' ',quantity) as branch from monitoring order by itemtype";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo $row["branch"]."<br>";
    }
} else {
    echo "0 results";
}