douyi8732 2017-02-01 05:58
浏览 30

如何使用PHP和Mysql设置登录系统?

I am trying to set up a login system but the page is not doing the validation of the user and passwors. I know is connecting to the database but it doesn't show any results after the for each statement. I have two files one for the login form(login.php) and one for the login to the database(process.php).

Here is my code:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">

<title>Login Page</title>
</head>

<body>
<div>
<form action="process.php" method="POST">
<p>
<label>Username:</label>
<input type="text"  id="user" name="user">
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass">
</p>
<p>
<label>Username:</label>
<input type="submit" id="btn" value="Login">
</p>
</form> 
</div>
</body>
</html> 


Process.php
<?php
   //Get values from login.php file
   $username = $_POST['user'];
   $password = $_POST['pass'];

   //Stop SQL injection
 /*  $username = stripcslashes($username);
   $password = stripcslashes($password);
   $username = mysql_real_escape_string($username);
   $password = mysql_real_escape_string($password);*/

   //Connect to the server and select database
$domainsn = 'mysql:host=localhost;dbname=login';
$username = 'root';
$password = 'costarica';

try {
    $db = new PDO ($domainsn, $username, $password);
    echo "Connected";

 } catch (Exception $e) {
    $error_message = $e->getMessage();
    echo "Coudn't connect due to $error_message";
 } 

   $query = "SELECT * FROM users WHERE username = '$username' AND password ='$password'";
  $result = $db->query($query);
   //echo "$result";


  foreach ($result as $results) {
   echo "$results";
   echo $users['id'];

    if ($results['username'] == $username && $results['password'] == $password) {
        echo "Login success!!! Welcome ".$results['username'];
    } else {
          echo "failed try {} catch ( $e) {}";

    }
    } 
?>`enter code here`
  • 写回答

1条回答 默认 最新

  • drryyiuib43562604 2017-02-01 06:41
    关注

    You can use this i hope it will help.

    $query = "SELECT * FROM users WHERE username = '".$username."' AND password ='".$password."' ";
    $result = $db->query($query);
    
    if($result->num_rows>0){
     // User exists
    }else{
    // User not exists.
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大