![](/img/trans.png)
[英]How do I code the php file to connect my multi-step form to MySQL database?
[英]How to do android connect to MySQL database with php page code?
我想連接MySQL數據庫,但沒有成功,我嘗試了以下代碼:
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
try{
String link="http://mwssong.esy.es/android/Login.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
if(sb.toString()=="admin")
new AdminScreen();
else if(sb.toString()=="Customer")
{
Intent myIntent(view.getContext(),AdminScreen.class);
startActivity(myIntent);
}
else
status.setText(sb);
}
catch(Exception e){
status.setText("Exception: " + e.getMessage());
}
}
但是它總是讓我進入狀態字段Exception null,並且Intent無法正常工作,Eclipse完全拒絕了此指令,沒有提出解決建議:
Intent myIntent(view.getContext(),AdminScreen.class);
startActivity(myIntent);
和PHP代碼是:
<?php
$db = mysqli_connect('mysql.hostinger.ae','u641845309_ur','q1p0w2o9','u641845309_song');
// username and password sent from Form and protect MySQL injection for Security purpose
$username=mysqli_real_escape_string($db,$_POST['username']);
$password=mysqli_real_escape_string($db,$_POST['password']);
$sql="SELECT * FROM customer WHERE UName='$username' and Password='$password'";
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$result=mysqli_query($db,$sql);
// If result matched $myusername and $mypassword, table row must be 1 row
if($result)
{
while($row = mysqli_fetch_array($result)) {
// Redirecting To Other Page
if(strtolower($username)=='admin')
echo "Admin";
else
echo "Customer";
}
}
else
{
echo "Your Login Name or Password is invalid";
}
?>
mysqli_query
失敗時返回FALSE。 對於成功的SELECT,SHOW,DESCRIBE或EXPLAIN查詢,mysqli_query()將返回mysqli_result對象。 對於其他成功的查詢,mysqli_query()將返回TRUE。
因此,在這種情況下(SELECT查詢),您應該使用mysqli_num_rows
知道結果中的記錄數(如果該數為零),那么SELECT查詢將不返回任何記錄,這意味着沒有這樣的用戶名和密碼
像這樣 :
if(mysqli_num_rows($result)>0){
//code executed when username and password are found
}
else {
//code executed when no such username and password
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.