首页 > 解决方案 > 使用 PHP 和 SQL Server 的登录脚本

问题描述

我是 PHP 新手,无法弄清楚我的脚本有什么问题。网上到处找了,还是不行。我有一个简单的登录表单:

电子邮件:

密码:

以及 html 中的登录按钮。

<?php

#starts a new session
session_start();

#includes a database connection
$serverName = "ServerNamehere"; //serverName\instanceName
$connectionInfo = array( "Database"=>"DatabaseNameHere", 
"UID"=>"ServerUsernameHere", "PWD"=>"ServerPasswordHere");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
 echo "Connection established.<br />";
}else{
 echo "Connection could not be established.<br />";
 die( print_r( sqlsrv_errors(), true));

#catches user/password submitted by html form
$email = $_POST['email'];
$password = $_POST['password'];

#checks if the html form is filled
if(empty($_POST['email']) || empty($_POST['password'])){
echo "Fill all the fields!";
}else{

#searches for email and password in the database
$query = "SELECT * FROM [dbo].[Test] WHERE UserEmail(SQL Table 
column)='{$email}' AND"
     "UserPassword(SQL table column)='{$password}';
$result = sqlsrv_query($conn, $query);  

#checks if the search was made
if($result === false){
 die( print_r( sqlsrv_errors(), true));
}

#checks if the search brought some row and if it is one only row
if(sqlsrv_has_rows($result) != 1){
   echo "Email/password not found";
}else{

#creates sessions
while($row = sqlsrv_fetch_array($result)){
   $_SESSION['id'] = $row['id'];
   $_SESSION['name'] = $row['name'];
   $_SESSION['user'] = $row['user'];
   $_SESSION['level'] = $row['level'];
}
#redirects user
header("Location: homepage.html");
}
}

?>

我的 html 通过

form class="login-form" name = 'signin.php'>

目前,当我输入正确的凭据并单击登录时,没有任何反应。我应该先检查一下我在这里遗漏了什么吗?

谢谢

标签: phpsqlsql-server

解决方案


从外观上看,您的表单永远不会发布到 PHP 脚本。你会想要改变你的form元素,它应该是action指定表单发布到哪里的属性,而不是name.例如:

<form class="login-form" action="signin.php" method="post">
...
</form>

推荐阅读