我看到一些PHP课程,然后我主要通过实用的方式学习所以我的问题是非常新手,我不明白为什么这个代码不适用于注册时重复用户名的解决方案,每次我收到带头的问题< / p>
function signup($conn) {
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
if (isset($_POST['signupSubmit'])) {
$query = mysql_query("select * from user where uid='$uid'");
$encrypted_password = password_hash($pwd, PASSWORD_DEFAULT);
if(mysql_num_rows(query)>0)
{
echo "<script> window.location.replace('test.php') </script>" ;
}
else {
$sql = "insert into usi (uid, pwd) values('$uid','$encrypted_password')";
$result = $conn->query($sql);
header("Location: test.php");
}
}
}
答案 0 :(得分:0)
这样:
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
if (isset($_POST['signupSubmit'])) {
应该是:
if (isset($_POST['signupSubmit'])) {
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
我没有mysql_的解决方案,但这里是我制作的PDO示例,希望有所帮助
$dbhost = "localhost";
$dbname = "database";
$mysqlusr = "root";
$mysqlpass = "";
try {
$db = new PDO("mysql:host={$dbhost};dbname={$dbname}", $mysqlusr, $mysqlpass);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
catch (PDOException $e){
echo $e->getMessage();
}
if(isset($_POST['signupSubmit'])){
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$encrypted_password = password_hash($pwd, PASSWORD_DEFAULT);
try {
$sql = "SELECT uid FROM user WHERE uid=:uid";
$statement = $db->prepare($sql);
$statement->bindParam(':uid', $uid, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if (empty($result)) {
try {
$sql = "INSERT INTO user (uid, pwd) VALUES (:uid, :pwd)";
$statement = $db->prepare($sql);
$statement->bindParam(':uid', $uid, PDO::PARAM_STR);
$statement->bindParam(':pwd', $encrypted_password, PDO::PARAM_STR);
$statement->execute();
echo "new user registered";
}
catch (PDOException $e){
echo $e->getMessage();
}
}
else {
echo "username already exists";
}
}
catch (PDOException $e){
echo $e->getMessage();
}
}