Mat
Mat

Reputation: 6324

Insert multiple values sent from AJAX into sql database

hi have this code which works perfectly with just value:

    <script type="text/javascript">
    $(document).ready(function() {
    $("input[type=button]").click(function () {
    var textarea_content = $('textarea#wall').val(); // get the content of what user typed    (in textarea) 
    if (textarea_content != '') { // if textarea is not empty 
    var sender =  "<?php echo $_SESSION['user_id'];?>";

     $.ajax({
            type: "POST",
            url: "send_message_function.php",
            data : "action=send&from_id="+sender+"&to_user="+$(this).siblings("input[type=text]").val()+"&message="+textarea_content,
            dataType: "json",
            success: function (data) {
               var  LastID = data["cid"];
               alert("toUser: " + $(this).siblings("input[type=text]").val()+"and text area " + textarea_content + " message id: " + LastID);
                                     }
        });//end success function

        //do something else

        } else {
        alert('Enter some text ! '); // just in case somebody click on share witout writing anything :)
    }
    });//end click function
    });//end ready function
    </script>

and send_message_function.php :

<?php
 require 'core/functions/init.php';

 $action  = $_POST['action'];
 if($action=="send"){
 $from_id = mysql_real_escape_string($_POST['from_id']);
 $to_id = mysql_real_escape_string($_POST['to_user']);
 $message = strip_tags($_POST['message']);

 $sql = mysql_query("INSERT INTO chat (from_id, to_id, message,   dt)VALUES('$from_id','$to_id','$message',NOW())") or die("0");

 echo json_encode(array("cid"=>(mysql_insert_id()),
                               "from_id"=>''.$message_id.''));
}
    ?>

the problem is when I try to send the message to multiple users. The sql query try to insert all the users IDs in the same row. I know I should do some loop but I can't think how run the query for every users I want to send the message to.

$(this).siblings("input[type=text]").val()      

returns multiple users id like this: 113,143,234

Upvotes: 1

Views: 2454

Answers (4)

Paul Tregoing
Paul Tregoing

Reputation: 111

To insert multiple rows in one SQL query, do this

INSERT INTO foo(a, b) VALUES('c', 'd'), ('e', 'f'), ('h', 'i');

You'll need to loop to build each VALUES set, but you can do the insert in a single query.

So something like

<?php
    $to_id = explode(',', mysql_real_escape_string($_POST['to_user']));

    $sql = 'INSERT INTO chat (from_id, to_id, message) VALUES';
    foreach ($to_id as $id)
    {
        $sql .="('$from_id', '$id', '$message'),";
    }
    rtrim($sql, ','); //strip the final comma
?>

That should form a query along the lines of

INSERT INTO chat(from_id, to_id, message) VALUES('1', '2', 'hello from php'), ('1', '3', 'hello from php'), ('1', '4', 'hello from php')

Doing it this way means only a single query is sent: therefore there's less overhead on communicating with the database which will speed up your script.

Upvotes: 1

Teena Thomas
Teena Thomas

Reputation: 5239

you do not need a loop, you can do multiple inserts with just one query, like this:

 $to_id = explode(',', mysql_real_escape_string($_POST['to_user'])); //split the string to an array containing each id

 $sql = mysql_query("INSERT INTO chat (from_id, to_id, message, dt) VALUES('$from_id','$to_id[0]','$message',NOW()), ('$from_id','$to_id[1]','$message',NOW()), ('$from_id','$to_id[2]','$message',NOW()) ") or die("0");

Note: $from_id shouldn't be a primary key, else you would get a duplicate key error.

Edit: If you do not know the no. of users,

   $to_id = explode(',', mysql_real_escape_string($_POST['to_user']));

   foreach ($to_id as $v)
     $sql = mysql_query("INSERT INTO chat (from_id, to_id, message, dt) VALUES('$from_id','$v','$message',NOW()) ") or die("0");

Upvotes: 1

Alaa Gamal
Alaa Gamal

Reputation: 1135

$toIDS = explode(',', mysql_real_escape_string($_POST['to_user']));
foreach($toIDS as $ID){
    $query=mysql_query("INSERT INTO foo(a, b) VALUES('c', 'd')");
    echo (mysql_affected_rows()>0)?$ID .'INSERTED':$ID.' NOT INSERTED';
}

Upvotes: 0

Renan Cunha
Renan Cunha

Reputation: 199

You need to split the users ids string in the comma character, then execute a query for each value founded.

Upvotes: 1

Related Questions