我想要实现的目的是将所有信息插入到以逗号分隔的行中,而不是为每个数据创建另一列。
我想要这个
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')");
}
}
答案 0 :(得分:1)
您需要在while循环外写入插入查询,并将用户名与,
连接起来
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')");
答案 1 :(得分:0)
试试这个..
$s = $sqlConnection->query($query);
if (!$s) {
die($sqlConnection->error);
}
else {
$str = '';
while ($row = $s->fetch_assoc()) {
// concat comma with $str when $str is not empty. so it concate comma from second circle
if($str !=''){ $str .= ',';}
//concat username one by one to make complete string
$str .= $row['username'];
}
// Finally do insert the complete string into a table
$sqlConnection->query("INSERT INTO mytable (exceptions) VALUES('$str')");
答案 2 :(得分:0)
你可以在mysql中使用sql group_concat函数
$query = "SELECT SAL.mentor AS mentor, group_concat(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 .= "GROUP BY mentor ";
$query .= "ORDER BY SAL.mentor";