0

Basically I know how to add one row to an external mysql database using android. Now im looking to add multiple rows at once. Heres my code so far.

PHP Script

<?php
$host="db4free.net"; //replace with database hostname 
$username="xxxxxx"; //replace with database username 
$password="xxxxxxx"; //replace with database password 
$db_name="xxxxxxx"; //replace with database name

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
/*  Get the value in the whichfunction parameter
 sent from the android application which will
determine the fucntion to call.   */

$getFunctionToCall = $_POST['whichfunction'];


/*  Depending on the value of the whichfunction
 parameter switch to call different function */

switch ($getFunctionToCall){
    case "AddUser":
        echo AddUser($_POST['name'],$_POST['password']);
        break;
}

/* Function to add user to the user table */

function AddUser($name,$password){
    $sql = "insert into users(name,password) values('$name','$password')";
    if(mysql_query($sql)){
        return 1; // Return 1 for success;
    }else{
        return 2;// Return 2 for database error;
    }
}
?>

Android Method

protected void SendToPhpFile() {

   ArrayList<NameValuePair> pp = new ArrayList<NameValuePair>();


   pp.add(new BasicNameValuePair("whichfunction", "AddUser"));

    String[] names = {"David","Jimmy","Shane"};
    String[] passwords = {"mypass1","mypass2","mypass3"};



  for (int i=0;i<names.length;i++){
    pp.add(new BasicNameValuePair("names[]", String.valueOf(names[i])));
    pp.add(new BasicNameValuePair("passwords[]", String.valueOf(passwords[i])));
}


 try{
        status = "";
        status = CustomHttpClient.executeHttpPost(ConnectBase.link, pp);
        String res=status.toString();
        res= res.replaceAll("\\s+","");

        /* Depending on value you return if insert was successful */
            if(res.equals("1")){
                Toaster("Data successfully added.");
            }else{
                Toaster(status);
            }
        }catch(Exception e){
            Toaster("Data successfully added: " + e.toString());
        } 

}

So I think I have the android size more or less sorted but I'm not 100%. If you guys could come up with a solution to how I've started that would be great. I've got zero experience with php so don't really know where to start when adding more than 1 row. Thank you

1
  • 2
    1. To insert multiple rows run multiple INSERT queries. 2. mysql_* functions are deprecated, do not use these functions to write new code. Use PDO or MySQLi Commented Mar 17, 2014 at 22:32

2 Answers 2

1

Something like this maybe?

INSERT INTO table (name, password ) VALUES ('Name1', 'Password1'), ('Name2', 'Password2'),('Name3', 'Password3'), ('Name4', 'Password4')
Sign up to request clarification or add additional context in comments.

1 Comment

Only problem with this is that the array will be dynamicaly sized. The string array is just a tester, will be replaced by a dynamic String array
0

Using mysqli you can not only avoid deprecated mysql functions but you can easily loop over insert values using prepared statements.

Referencing

In the following example we will be inserting usernames and passwords into the database in a safe and efficient way.

$x = array(array('bob','mypasswordlol'),array('your_mother','knitting5000'));
$stmt = $mysqli->prepare("INSERT INTO table (`username`, `password`) VALUES (?, ?)");
foreach ( $x AS $k => $value) {
    $stmt->bind_param($stmt, "ss", $value[0], $value[1]);
    $stmt->execute();
}
// close your connection

Hopefully this helps. Prepared statements are the bees knees when it comes to mysqli. It will help you prevent database injection and increase performance as well!

3 Comments

Hey Calebj, Thanks for the response! I would have to define the array in the android code and it would have no defined size...Is this possible? Thanks
To be honest I don't really understand how you can reference the android array in the php
If you create a hashmap docs.oracle.com/javase/7/docs/api/java/util/HashMap.html of username/password combinations then json serialize them. you can json_decode() in php and get everything nice and cleanly. You may not even have to json serialize.

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.