如何在Android连接PHP后,将值插入SQL表?
我想将Android post值用于PHP,然后PHP可以接收值并插入。
但是现在我有问题,我不知道为什么不能插入。
这是我的Android代码:
public class MainActivity extends Activity {
TextView t;
//
String url = "http://00.00.00.00/Insert.php";
//thread
Handler mHandle; //manager
HandlerThread mThread;//worker
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create table using CreateTable.php
mThread = new HandlerThread("CreateTable");//
mThread.start();//worker stand by
mHandle = new Handler (mThread.getLooper());//look for worker using Handle manager
mHandle.post(CreateTable);//give work for worker
}
//
private Runnable CreateTable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//connect php
HttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
//send value to
List< NameValuePair> vars=new ArrayList< NameValuePair>();
vars.add(new BasicNameValuePair("number","abc"));
try {
method.setEntity(new UrlEncodedFormEntity(vars,HTTP.UTF_8));
Log.e("TAG","Send to php");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
这是我的PHP代码
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'androidhive';
$number = $_POST['number'];//$number from android
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error with MySQL connection');
mysql_query("SET NAMES 'utf8'");
mysql_select_db($dbname);
$result = mysql_query("INSERT INTO table1(Username,Password,Role) VALUES('number', 'number', 'number')");
?>
答案 0 :(得分:0)
你应该在HttpClient上调用execute方法。
httpClient.execute(postRequest);
答案 1 :(得分:0)
我发现了我的错误,并纠正了php
<?php
header("Content-type: text/html; charset=utf-8");
$conn = new mysqli('localhost', 'user', 'password', 'databasename');
$conn->set_charset('utf8');
$number = $_POST['number'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table1(Username,Password,Role) VALUES('$number', '$number', '$number')";
if ($conn->query($sql) === TRUE) {
echo "insert to table successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>