PHP check if username is available

2020-03-31 05:51发布

问题:

I'm working on checking if the username exists from the database. While the user is typing this username, it will check up if it exists from the database. I've got an error

Warning: mysql_result() expects parameter 1 to be resource, boolean given in username_check.php on line 12.

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);
    }
}

?>

回答1:

Use the following code to get the count and check whether user exists or not for username_check.php page.

<?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;
            }
    }
}

?>


回答2:

I would add or die(mysql_error()); to the end of the sql line. It will display any errors in your query in the first place. It would be like

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

Also COUNT has to be like COUNT(column_name)

Also the mysql_ functions are depecrated. It would be wise to use mysqli or PDO



回答3:

Replace the code in the username_check.php and your problem will be solved

 <?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);
        }
    }
    ?>


回答4:

You can use this code:

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;
        }}}


回答5:

To check username using php first you need to request a input from html. Here i am using ajax technique for this purpose.You can watch demo and download link from 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');