不要在表中的数组

时间:2014-11-20 10:37:14

标签: php mysql

我的代码

$insert2 = "INSERT INTO numbers(ContactID, numbers) VALUES('$insertID','" . $capture_field_vals . "')";
    mysql_query($insert2);

我得到了

ContactID       numbers  
1               421312, 123123, 3434543, 123423, 98797

我想要什么

ContactID     numbers
1             421312
1             123123
1             3434543
1             123423
1             98797

请帮助我,我不明白该怎么做

6 个答案:

答案 0 :(得分:1)

String转换为Array并循环执行insert操作

$string2Array = explode(",", $capture_field_vals);
foreach($string2Array as $key=>$value){
 $insert2 = "INSERT INTO numbers(ContactID, numbers) VALUES('$insertID','" . $value. "')";
 mysql_query($insert2);
}

注意:不要使用mysql_*,因为它已被弃用。尝试使用PDO

根据您的评论,值$_POST["mytext"]Array。所以你不需要转换成字符串。请检查以下代码。

if($_POST["mytext"]){
 foreach($_POST["mytext"] as $key=>$value){
  $insert2 = "INSERT INTO numbers(ContactID, numbers) VALUES('$insertID','" . $value. "')";
  mysql_query($insert2);
 }
}

答案 1 :(得分:1)

使用explode()将字符串拆分为数组,然后循环它们并将它们插入表中。

$numbers = explode(',', $capture_field_vals);
foreach ($numbers as $n) {
    $n = trim($n);
    if (strlen($n) > 0) {
        $insert2 = "INSERT INTO numbers (contactID, numbers) VALUES ('$insertID', '$n')";
        mysql_query($insert2);
    }
}

答案 2 :(得分:0)

尝试PHP的爆炸功能。

当您在数组中打印值时: $ tempNam = explode(','$ resultset ['numbers']);

并循环$tempNum

答案 3 :(得分:0)

首先爆炸它们。然后生成一个查询。无需在foreach循环内部运行。请尝试使用 -

$insert2 = "INSERT INTO numbers(ContactID, numbers) VALUES ";
$fields = explode(',', $capture_field_vals);
$values = array();
foreach ($fields as $field) {
    $values[] ="('$insertID', '".$field."')"; 
}
$insert2 .= implode(',', $values);
mysql_query($insert2);

避免使用mysql函数,因为它们已被弃用,请改用mysqliPDO

答案 4 :(得分:0)

$values = explode(",", $capture_field_vals);
foreach ($values as $value) {
    $insert2 = "INSERT INTO numbers(ContactID, numbers) "
        . "VALUES('" . $insertID . "','" . trim($value) . "')";
    mysql_query($insert2);
}

注意:

  • 不要使用mysql函数,因为它们已被弃用。请改用mysqliPDO

  • 通过转义变量来避免sql注入。

答案 5 :(得分:0)

可能是个好主意: 1.切换到mysqli, 2.使用准备好的声明以确保安全性和清晰度 3.在插入表示单一关系的几行时使用事务来维护数据库完整性

$db = new mysqli('localhost', 'user', 'pass', 'demo');

...
$db->autocommit(FALSE);
$statment = $db->prepare("INSERT INTO numbers(ContactID, numbers) VALUES(?,?)");
foreach (explode(',', $capture_field_vals) as $field_val){
    try{
        $statement->bind_param('ss', $insertID, $field_val);
    } catch (Exception $e){
        $db->rollback();
    }
}
$db->commit();
相关问题