从Android应用程序将数据插入MySQL数据库.更改未反映在数据库中
我正在编写一个将数据插入MySQL数据库的应用程序.我用PHP编写了sql查询,当我在android应用程序中输入值时,在log cat中没有看到任何错误,但是这些值未存储在数据库中.
I'm writing an application to insert data into a MySQL database. I wrote the sql query in PHP and when I enter values in the android application, I don't seen any errors in the log cat but the values aren't getting stored in the database.
这是PHP代码:
<?php
$connect = mysqli_connect("localhost","root","","easyassigndroid");
if(mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "success";
}
$username = isset($_POST['sPhone']) ? $_POST['sPhone'] : '';
$password = isset($_POST['sPassword']) ? $_POST['sPassword'] : '';
$query = mysqli_query($connect, "insert into users (sphone, spassword) values ('$username' ,'$password') ");
mysqli_close($connect);
?>
这是android部分:
Here's the android part:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register_lecturer);
phonenum = (EditText) findViewById(R.id.id_phone);
password = (EditText) findViewById(R.id.id_password);
sPhone = phonenum.toString();
sPassword = password.toString();
registerLecturer=(Button)findViewById(R.id.lecturerregister);
registerLecturer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2/project/insert.php");
try
{
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("sphone", sPhone));
nameValuePairs.add(new BasicNameValuePair("spassword", sPassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
我是Android和PHP编码的初学者.谁能告诉我问题出在我的代码中吗?我的项目工作需要这个.
I'm a beginner to both Android and PHP coding. Can anyone tell me where the problem is in my code? I need this for my project work.
只有一点:我们使用
x.getText().toString();
其中x是EditText对象,对吗?希望对您有帮助.
where x is an EditText object, right? hope it helps at all.
但是,由于这是在onCreate()中完成的,而不是在onClick()中完成的,因此您应该进行以下更改:
But, since this is being done in the onCreate() - rather than inside the onClick() - you should change:
nameValuePairs.add(new BasicNameValuePair("sphone", sPhone));
到
nameValuePairs.add(new BasicNameValuePair("sphone", phonenum.getText().toString()));
对于另一个也是类似的. 干杯.
And similarly for the other one. Cheers.