我正在努力创建"注册"使用php和mysql形成。注册表格要求输入用户名和密码。如果任何字段为空,它将让用户知道哪一个。如果用户名正在使用中,它也会让用户知道。
我知道与数据库的连接没问题,因为我创建了一个手动添加到数据库中的用户。
奇怪的是我的代码在Cloud9中运行。但是,它不适用于安装在谷歌云上的虚拟机实例。
在cloud9中,它将用户添加到数据库中。在谷歌的例子中,它不会。
任何人都可以检查这个并告诉我我做错了吗?
感谢。
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$display = $_POST['display'];
$dbh = new PDO("mysql:host=localhost;dbname=mydb","root",NULL);
$stmt = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if($stmt->rowCount() == 0 and $username != null and $password != null){
$insert = $dbh->prepare("INSERT INTO users(username,password) VALUES(:username, :password)");
$insert->bindParam(':username', $username);
$insert->bindParam(':password', $password);
$insert->execute();
echo ("The user ".$username. " has been created.");
答案 0 :(得分:-1)
在你需要检查之前试试这个
检查用户名是否正在使用
如果用户名未使用,请将数据插入数据库
脚本
<?php
// error_reporting on
error_reporting(1);
ini_set('error_reporting', E_ALL);
$username = $_POST['username'];
$password = $_POST['password'];
// i commented $display variable because i don't see that u using it anywhere
//$display = $_POST['display'];
// database connection
$dbh = new PDO("mysql:host=localhost;dbname=mydb","root","");
// query
$stmt = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
// check if username and password is not empty
if ($username != '' && $password != '')
{
// check if username is in use
if($stmt->rowCount() > 1)
{
echo "Username in use, please choose another one.";
}
else
{
$insert = $dbh->prepare("INSERT INTO users(username,password) VALUES(:username, :password)");
$insert->bindParam(':username', $username);
$insert->bindParam(':password', $password);
$insert->execute();
// if last inserted id is true
if ($dbh->lastInsertId())
{
echo "The user ".$username. " has been created.";
}
else
{
echo "User not registered, please try again.";
}
}
}
else
{
echo "Please enter username and password.";
}
?>