如何使用循环在mysql中插入数组值

时间:2016-10-21 08:00:30

标签: php jquery mysql ajax

用jquery读取Textarea,在Array中分割每一行然后用ajax通过php在mysql中发布该数组,但结果只插入第一个值。

表:

CREATE TABLE IF NOT EXISTS addresses ( 
    id int(8) NOT NULL PRIMARY KEY, 
    user_id int(8) DEFAULT NULL, 
    address_value varchar(100) NOT NULL 
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

这是Jquery代码:

$('#insertad').click(function(){
    var lines = $('#txtArea').val().split('\n');

    var phparray = new Object();

    for(var i = 0;i < lines.length;i++){
        phparray[i] = lines[i]; //store value in object
    }
    $.post('functions.php?action=insertad', {array1:$.param(phparray)}, function(resp){
        $('.text-success').html(resp);  
        if(resp == 'Added'){

        $('.text-success').html('Added Address :');

    }   
    }); 

});

这是PHP代码:

if ($action == 'insertad') {
    $pieces   = explode('&', $_POST['array1']); //explode passed serialized object
    $phparray = array();
    foreach ($pieces as $piece) {
        list($key, $value) = explode('=', $piece);
        $phparray[$key] = $value; //make php array
    }

    $length = count($phparray);

    for ($i = 0; $i < 7; $i++) {

        $sql     = "select address_value from addresses where address_value = '$phparray[$i]'";
        $qry     = mysql_query($sql);
        $numrows = mysql_num_rows($qry);
        if ($numrows > 0) {
            echo "One Found !!" ;
        } else {
            $sql = "insert into addresses (address_value) values ('$phparray[$i]')";
            $qry = mysql_query($sql);
            if ($qry) {
                echo "Added";
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

请试试这个......

<强> JS:

var $textarea = $('textarea'); // maybe you have to specific your selector!
var textArray = $textarea.val().split("\n"); // this array is already done, your have not todo next for() loop

$.post('functions.php', {
    action: 'insertad', 
    array1: textArray
}, function(results) {
  $.each(results, function(reslt) {
    if(result === 'Added') {
      $('.status').append(result);
    }
    else {
        $('.status').append(result);
    }
  });       
});

<强> PHP:

if($action === 'insertad') {
    $results = [];
    $input = $_POST['array1'];

    foreach($input AS $textLine) {

        $escapedTextLine = mysqli_real_escape_string($resource, $textLine);

        $result = mysqli_query($resource, 'select address_value from addresses where address_value = "'.$escapedTextLine.'"');
        $affectedRows = mysqli_num_rows($result);

        if($affectedRows > 0) {
            $results[] = 'One Found !!';
        }
        else {
            $result = mysqli_query($resource, 'INSERT INTO `adresses` (`address_value`) VALUES("'.$escapedTextLine .'");

            if($result) {
                results[] = 'Added!';
            }

        }
    }

   return $results; // we return all done results to check this array in ajax response
}

注意:我写了代码盲,所以也许你必须做一些小改动,例如:你的变量或类似的东西。

注意2:我用mysqli编写代码,因此您必须重写数据库连接设置代码。

请永远不要忘记使用mysqli_real_escape_string对用户内容执行某些操作。