我想连接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());
}
}
但它总是给我提交状态异常 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
block 引用>returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return 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 }
关于php - android如何使用php页面代码连接MySQL数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34692445/