Pregunta

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.

¿Fue útil?

Solución

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;

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top