我正在尝试使用以下代码将我的数据库连接到我的PHP代码:
<html>
<head>
<title>Landing page</title>
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<?php
// Check if username and password are correct
if ($_POST["username"] == "logintest" && $_POST["password"] == "access123!") {
// If correct, we set the session to YES
session_start();
$_SESSION["logged_in"] = "YES";
echo "<h1>You are now logged in</h1>";
echo "<p><a href='secure1.php'>Link to protected file</a></p>";
echo "<p><a href='secure2.php'>Link to protected file #2</a></p>";
}
else {
// If not correct, we set the session to NO
session_start();
$_SESSION["logged_in"] = "NO";
echo "<h1>You are NOT logged in </h1>";
echo "<p><a href='secure1.php'>Link to protected file</a></p>";
echo "<p><a href='secure2.php'>Link to protected file #2</a></p>";
}
?>
<p><a href="public.html">Public Page</a></p>
<p><a href="logout.html">Logout</a></p>
</body>
</html>
我想使用特定表中的数据库用户名和密码,而不是使用内联用户名和密码。我出于某种原因无法让它工作,我发现它真的很难。如果有人能帮忙的话会很棒。
答案 0 :(得分:2)
mysqli_*
prepared statement而不是deprecated mysql_*
if ($_POST["username"] == "logintest" && $_POST["password"] == "access123!") {
替换为if($checklog > 0 ){
代码:
/* ESTABLISH FIRST YOUR CONNECTION TO YOUR DATABASE */
$con = new mysqli("host", "User", "Password", "Database"); /* REPLACE NECESSARY DATA */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT Username, Password FROM user_login WHERE Username = ? AND Password = ?")){
$stmt->bind_param("ss",$_POST["username"],$_POST["password"]);
$stmt->execute();
$stmt->store_result();
$checklog = $stmt->num_rows;
if($checklog > 0){
/* HERE IS YOUR CODE WITH SUCCESSFUL LOGIN */
}
else {
/* HERE IS YOUR CODE WITH UNSUCCESSFUL LOGIN */
}
$stmt->close();
}
答案 1 :(得分:0)
有几种方法可以连接到MySQL。但是,仅仅知道如何连接是不够的。您还需要学习如何使用它。因此,我首先给你一些MySQLi和PDO的链接:
PHP: MySQLi - Manual
PHP: PDO - Manual
现在回答你的问题,这里有一些常用的连接mysql的方法:
MySQLi对象已发布的样式
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
?>
MySQLi程序风格
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_error()){
echo "Failed to connect to MySQL: (" . mysqli_connect_error() . ")";
}
?>
PDO对象已发布的样式
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try{
$pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>