在mysql中插入逗号分隔的数组

时间:2014-03-06 13:32:41

标签: mysql arrays insert comma

我正在编写一个脚本,我想为新用户选择父ID,并在mysql表中保存父ID和父父id。

$last_id = mysql_insert_id(); 

//select parent id of last inserted user 
$sel = mysql_query("SELECT * FROM tbl_new_agent WHERE new_agnt_id = '".$last_id."'"); 
$row = mysql_fetch_array($sel); 
$a = $row['new_agnt_ParentId']; 

//select parents of parent which are supposed to be stored at parent_arr field in db as comma separated values                                      
$sel1 = mysql_query("SELECT * FROM tbl_new_agent WHERE new_agnt_id = '".$a."'"); 
$row1 = mysql_fetch_array($sel1); 

//here i want to add element in array.though its not working obviously 
$b = array_push($row1['parent_arr'],$a); 

$update = mysql_query("UPDATE tbl_new_agent SET parent_arr = '".$b."' WHERE new_agnt_id = '".$last_id."'");  

我不知道如何存储逗号分隔值或最初存储单个值然后添加更多元素。任何人都可以在这方面给我一些想法吗?

2 个答案:

答案 0 :(得分:0)

以下是如何获得以逗号分隔的用户列表"父母",无需额外的列:

SELECT GROUP_CONCAT(t2.new_agnt_id)
FROM tbl_new_agent t1
JOIN tbl_new_agent t2
ON t2.new_agnt_id = t1.new_agnt_ParentId
WHERE t1.new_agnt_id = :last_id

出于性能考虑,请考虑仅命名所需的列,而不是一般地使用SELECT *。例如。 SELECT new_agnt_ParentId FROM tbl_new_agent WHERE ...

答案 1 :(得分:0)

现在我找到了这个解决方案:

$update = mysql_query("UPDATE tbl_new_agent SET parent_arr = CONCAT('".$b."','".$a."',',') WHERE new_agnt_id = '".$last_id."'");

并以这种方式在另一页中使用:

     $agent_id = $_POST['comm_Agent'];  
    $query = mysql_query("SELECT * FROM tbl_new_agent");

    while($row = mysql_fetch_array($query)){
             $parent_arr = explode(',',$row['parent_arr']);
                   if (in_array($agent_id, $parent_arr)) {
                                echo $row['new_agnt_id'];
                   }

}

我相信还有其他的整洁'实现这一目标的方法。但到目前为止,代码正在按预期工作。感谢您的回复Marcus Adams