PHP mysqli 插入与逗号而不是一个接一个

标签: MySQL PHP
发布时间: 2017/1/9 21:38:42
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想在这里要实现是,要在行用逗号分隔,并不使每个数据的另一列中插入的所有信息。

我想要这个

john,mark,mary,luke,james

这不

john
mark
mary
luke
james

我的代码

// Get all the users
$query = "SELECT SAL.mentor AS mentor, ACC.username AS username ";
$query .= "FROM ec_accounts ACC ";
$query .= "LEFT JOIN ec_info INF ON ACC.user_id = INF.iuid ";
$query .= "LEFT JOIN ec_sales SAL ON ACC.user_id = SAL.suid ";
$query .= "ORDER BY SAL.mentor";

$s = $sqlConnection->query($query);

if (!$s) {
    die($sqlConnection->error);
} else {
    while ($row = $s->fetch_assoc()) {
        $exarr = explode(',', $row['username']);

        $sqlConnection->query("INSERT INTO mytable (exceptions) VALUES('$exarr')");
    }
}

解决方法 1:

你需要写你插入查询以外,而循环并连接你的用户名,

while ($row = $s->fetch_assoc()) {
    $username .= $row['username'] . ",";// create string like john,mark,mary,luke,james,

}
// outside while loop
$username = rtrim($username, ",");// remove last comma

$sqlConnection->query("INSERT INTO mytable (exceptions) VALUES('$username')");
官方微信
官方QQ群
31647020