我试图在插入表格之前检查用户名是否可用。
但无论用户名是否已经存在,它似乎都会插入到表中。
这是我的php代码:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'myPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
}
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
}
$username = $_POST['username'];
$password = $_POST['password'];
$name = $_POST['name'];
$email = $_POST['email'];
$username = mysqli_real_escape_string($link,$username);
$password = mysqli_real_escape_string($link,$password);
$name = mysqli_real_escape_string($link,$name);
$email = mysqli_real_escape_string($link,$email);
$password = md5($password);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count > 0) {
$sql = "INSERT INTO mainLogin (username, password, name, email) VALUES ('$username', '$password', '$name','$email' )";
$result = mysqli_query($link, $sql);
if (!$result) {
die('Error: ' . mysqli_error($link));
}else {
$_SESSION['login'] = $username;
echo "<script>window.location = 'http://madsanker.dk.linux101.unoeuro-server.com'</script>";
}
}else {
echo "username taken";
}
mysqli_close($link);
?>
我做错了什么?
谢谢!
更新
更改$ count&gt; 0到$ count == 0工作
答案 0 :(得分:0)
只需在“&gt;”中更改if语句中的更大符号到== 0
if($count==0){
}
答案 1 :(得分:0)
如果username
已经在db中而不是更改此条件:
if($count > 0) {
//your stuff
}
使用:
if($count <= 0) { // if not found
//your stuff
}