PHP check if username is available

一笑奈何 提交于 2019-12-01 14:00:23

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

?>

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

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

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

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');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!