2016-06-09 73 views
0

我想在這裏實現的是在逗號分隔的行中插入所有信息,而不是爲每個數據創建另一列。PHP mysqli用逗號代替一個一個地插入

我想這

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

怎麼啦??? –

+0

那麼你爲什麼使用爆炸? :),爲什麼你需要在PHP中做到這一點。它看起來像它可以直接在數據庫中完成,反正看起來不像循環是必要的 – Robert

+0

'print_r($ row)'的值是什麼;'' – Saty

回答

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')"); 
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')"); 
0

您可以簡單地使用SQL GROUP_CONCAT函數在MySQL

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