inserting multiple mysql rows php Android

时光总嘲笑我的痴心妄想 提交于 2019-12-25 02:24:32

问题


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.


回答1:


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;



回答2:


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



来源:https://stackoverflow.com/questions/22935242/inserting-multiple-mysql-rows-php-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!