基本上我知道如何使用android向外部mysql数据库添加一行。现在我想一次添加多行。到目前为止,这是我的代码。
PHP脚本
<?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方法
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());
}
}
所以我认为我的Android大小或多或少排序,但我不是100%。如果你们能想出一个解决方案来解决我的工作方式会很棒。我没有使用php的经验,所以当添加超过1行时,不知道从哪里开始。 谢谢
答案 0 :(得分:1)
这样的事可能吗?
INSERT INTO table (name, password ) VALUES ('Name1', 'Password1'), ('Name2', 'Password2'),('Name3', 'Password3'), ('Name4', 'Password4')
答案 1 :(得分:0)
使用 mysqli ,您不仅可以避免使用已弃用的mysql函数,而且可以使用预准备语句轻松遍历插入值。
在下面的示例中,我们将以安全有效的方式将用户名和密码插入数据库。
$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
希望这会有所帮助。当谈到mysqli时,准备好的陈述是蜜蜂的膝盖。它将帮助您防止数据库注入并提高性能!