php - MySQL 中使用 PHP undefined variable 的 CONCAT 函数

标签 php mysql wamp wampserver

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

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

该语法适用于 MySQL 控制台。然而,我在 php 上实现它时遇到了麻烦。我总是得到 “未定义索引:分支名称” “未定义索引:项目类型” “未定义索引:数量”

使用此代码:

$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>";

我很困惑,因为我基本上运行了相同的代码,可以让我看到表中的项目类型:

$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) from monitoring order by itemtype";

应该是

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

我已经发布了这个答案,以引用您如何在 while 循环中调用字段

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

如果您需要在一个字段内显示串联值,那么它应该类似于

$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";
}

关于php - MySQL 中使用 PHP undefined variable 的 CONCAT 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30092351/

相关文章:

php - 如何在 WAMP 上安装 YAML 扩展?

php - 从 PHP 中的 SoapClient 返回中检索特定值

php_mongo 扩展已经安装了,但是为什么 rockmongo 仍然没有连接?

php - php 函数 dl() 的任何替代方法

javascript - 带按钮的模态缩略图

php - 使用 PHP 查询 MySQL

php - Windows 8 : . phar文件,你想怎么打开

javascript - 输入正确值后重新加载网页

php - PHP 中 Cookie 与 Session 的页面加载时间

mysql获取分组的最后一个值