0

Im trying to insert multiple mysql rows in an external database using a php script and Android. I pass a JSONObject to the PHP script from Android and Im trying to use this data to update multiple rows of a mysql database at once. The problem is in the PHP script

PHP

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 

mysql_select_db("$db_name")or die("cannot select DB");

$json = $_POST['json'];
$array = json_decode($json, true);


for ($i = 0; $i < 3; $i++) {
     $name = $array['person'][0]['name'];
     $password = $array['person'][0]['password'];

     $sql = "insert into Test4Upload(name,password) values('$name','$password')";

    if(mysql_query($sql)){
    return 1; // Return 1 for success;
    }else{
    return 2;// Return 2 for database error;
}
}


?>

This is the JSONObject passed in {"person":[{"age":0,"name":"Jim"},{"age":1,"name":"Harry"},{"age":2,"name":"bill"}]}

This only updates the database once rather than three times..Im wondering why this is so, and also If I change [0] to [i] then the database does not update at all?

Sorry Im used to coding in java so I have no idea why the loop iterations dont work the same,

Thank you.

2 Answers 2

0

Try this

$json = $_POST['json'];
$count=0;
$array = json_decode($json, true);
foreach ($array['person'] as $item){
     $age= $item['age'];
     $name= $item['name'];
     $sql = "insert into Test4Upload(age,name) values('$age','$name')";
     if(mysql_query($sql))
     {
       $count++;
     }
}
return $count;
Sign up to request clarification or add additional context in comments.

4 Comments

Invalid argument for foreach.. Actually I always seem to get this error whenever I run foreach loops
No it works fine, firstly check the code in my project
Solved this by casting $array['person'] to array.. And now it works.
Just one thing Sushant, If my @array is very large, with hundreds and potentially thousands of elements. Is there any way to make this more efficient by limiting the number of insert queries made?
0

Problem is thas you call return after first loop:

 if(mysql_query($sql)){
    return 1; // Return 1 for success;
    }else{
    return 2;// Return 2 for database error;

and that return breaks your loop. http://www.php.net/manual/en/function.return.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.