我在google / youtube上遵循了很多教程,但是仍然无法使用php连接数据库。我完全按照有关数据库连接的文档进行了编码,但是没有用。我已经使用mysql仪表板创建了名为userregistration的数据库。 这是myindex.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Login and Registration</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="login-box">
<div class="row">
<div class="col-md-6 login-left">
<h2>Login Here</h2>
<form action="validation.php" method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="user" class="form-control" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
<div class="col-md-6 login-right">
<h2>Register Here</h2>
<form action="registration.php" method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="user" class="form-control" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
这是我的Registration.php文件:
<?php
session_start();
$con = mysqli_connect('localhost','root','');
mysqli_select_db($con, 'userregistration');
$name = $_POST['user'];
$pass = $_POST['password'];
$s = "select * from usertable where name='$name'";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
echo "Username Already Taken";
}else{
$reg = "insert into usertable(name, password) values ('$name','$pass')";
mysqli_query($con, $reg);
echo "Registration Successful";
}
?>
我的代码有错误吗?
答案 0 :(得分:1)
尝试直接使用具有数据库名称的连接
基于模式
$con = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
尝试
$con = mysqli_connect('localhost','root','','userregistration');
,并确保您的php页面位于正确的路径中
最终尝试添加正确的路径或至少添加相对路径
<form action="./Registration.php" method="post">
答案 1 :(得分:0)
您的PHP部分看起来还不错。也许您可以尝试通过添加这样的调试代码(如此处https://www.php.net/manual/en/function.mysqli-connect.php
中所示的调试代码)来查看PHP是否能够建立连接。if (!$con) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($con) . PHP_EOL;
最后,最重要的是,您可能不应该直接使用此功能,因为这可能会引入严重的SQL注入漏洞。 Google多介绍一些最佳做法。 :)