PHP检查用户名是否可用

时间:2013-11-13 12:03:56

标签: php mysql username exists

我正在检查数据库中是否存在用户名。当用户输入此用户名时,它将检查数据库中是否存在该用户名。我有一个错误

警告:mysql_result()要求参数1为资源,第12行的username_check.php中给出布尔值。

HTML CODE

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">

        </style>
    </head>
    <body>
        <input id="username" type="text">
        <span id="username_status"></span>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/users.js"></script>
    </body>
</html>

users.js

$('#username').keyup( function() {
    var username = $(this).val();

    $('#username_status').text('Searching...');

    if(username != '') {
        $.post('php/username_check.php', { username: username}, function(data) {
            $('#username_status').text(data);
        });
    }
    else {
        $('#username_status').text('');
    }
});

db.php中

<?php

mysql_connect('xxx', 'xxx', 'xxx');
mysql_select_db('xxx');

?>

username_check.php

<?php

require 'db.php';

if (isset($_POST['username'])) {
    $username = mysql_real_escape_string($_POST['username']);

    if (!empty($username)) {
        $username_query = mysql_query("SELECT COUNT user_id
                                       FROM users
                                       WHERE username = '$username'");
         echo $username_result = mysql_result($username_query, 0);
    }
}

?>

5 个答案:

答案 0 :(得分:1)

使用以下代码获取计数并检查用户是否存在 username_check.php 页面。

<?php
 require 'db.php';

    if (isset($_POST['username'])) 
    {
        $username = mysql_real_escape_string($_POST['username']);

        if (!empty($username)) 
    {
            $username_query = mysql_query("SELECT *
                                           FROM users
                                           WHERE username = '$username'");
             $count=mysql_num_rows( $username_query);
             if($count==0)
             {
               echo "Username doesn't exist";
               exit;
             }
            else
            {
              echo "Username already exists";
              exit;
            }
    }
}

?>

答案 1 :(得分:0)

我会在sql行的末尾添加或die(mysql_error());。它将首先显示查询中的任何错误。 这就像

 $username_query = mysql_query("SELECT COUNT(user_id) FROM users WHERE username = '$username'") or die(mysql_error());

COUNT必须与COUNT(column_name)

类似

还要取消mysql_函数。 使用mysqli或PDO

是明智的

答案 2 :(得分:0)

替换username_check.php中的代码,您的问题将得到解决

 <?php

    require 'db.php';

    if (isset($_POST['username'])) {
        $username = mysql_real_escape_string($_POST['username']);

        if (!empty($username)) {
            $username_query = mysql_query("SELECT COUNT(user_id)
                                           FROM users
                                           WHERE username = '$username'");
             echo $username_result = mysql_result($username_query, 0);
        }
    }
    ?>

答案 3 :(得分:0)

您可以使用此代码:

if (isset($_POST['username'])) 
{
 $Usuario = mysqli_real_escape_string($conexion, $_POST['username']);
    if (!empty($username))  {
        $query = "SELECT Usuarios FROM preregistro WHERE username= '$username'";
        $result=mysqli_query($conexion,$query);
        $mostrar = $result->num_rows;
         if($mostrar==0){
           echo "√ Usuario disponible ";
           exit;
         }else {
          echo "X El nombre de Usuario ya existe...";
          exit;
        }}}

答案 4 :(得分:0)

要首先使用php检查用户名,您需要从html请求输入。 在这里,我正在使用ajax技术。您可以从ajax live username availability check

观看演示和下载链接

<强> Demo.html

 <!DOCTYPE html>
<head>
<script>
function check(str) {
if (str.length == 0) { 
document.getElementById("demo").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "demo.php?u=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<center>
<form>
<div style="margin-top:200px">
<h3 id="demo">  </h3>
Enter Username to check availability: <input type="text" name="user" placeholder="EnterUserName" onKeyUp="check(this.value)"/> 
</div>
</form>
</center>
</body>
</html>

<强> Demo.php

 <?php
$user=trim($_GET['u']);
@mysql_connect("localhost","root","");
@mysql_select_db("test");
if($user!="")
{
$sql="select user from users where user='$user'";
$user_array=array();
$rdata=mysql_query($sql);
$res=mysql_fetch_array($rdata);
if($res['user']==$user)
{
echo " <p style='color:red;'><b>\"$user\"</b> Is already taken.</p>";
}
else
{
echo "<p style='color:green;'><b>\"$user\"</b> is available.</p>";
}
}
?>

<强> Users.sql

-- phpMyAdmin SQL Dump
-- version 2.10.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Sep 12, 2016 at 12:13 PM
-- Server version: 5.0.41
-- PHP Version: 5.2.3

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`user` VARCHAR(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `user`) VALUES
(1, 'mahendra'),
(2, 'narendra'),
(3, 'michael'),
(4, 'ankit');