MySQL从explode中插入多行

时间:2015-10-13 17:20:01

标签: php mysql vbulletin

我有一个变量

$allnames = 'John,Peter,Maya';

我正在尝试检查user表中是否存在每个名称,如果它存在,我想将每个名称插入另一个表中的一行。

$allnames = 'John,Peter,Maya';
$names = explode(",", $allnames);

foreach($names as $name)
{
    $checkusers = $db->query_read("SELECT username,userid FROM " . TABLE_PREFIX . " `user` WHERE username = '".$name."' "); 
    $results = $db->fetch_array($checkusers);

    $db->query_write("INSERT INTO " . TABLE_PREFIX . " `invite_users` (username)  VALUES ('".$results['userid']."') 
"); 

}

解决方案:

$string = mysql_real_escape_string($_POST['userstag']);
$arr = explode(",",$string);

$sql = $db->query_read("SELECT username FROM  " . TABLE_PREFIX . " `user` WHERE username IN ('".implode("', '", $arr) . "')");

while($r = $db->fetch_array($sql))
{    
    $sqli = $db->query_write("INSERT INTO " . TABLE_PREFIX . " invite_users (username) VALUES ('".$r['username']."') 
    ");     
}

1 个答案:

答案 0 :(得分:0)

如果问题是变量的吐出,可以尝试使用以下代码

$allnames = 'John,Peter,Maya';
$arr = explode(",",$allnames);
$name_1=$arr[0];
$name_2=$arr[1];
$name_3=$arr[3];