Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 05:36
Show Gist options
  • Save code-boxx/af16a94d01366d483f4d3c740e43da66 to your computer and use it in GitHub Desktop.
Save code-boxx/af16a94d01366d483f4d3c740e43da66 to your computer and use it in GitHub Desktop.
PHP MYSQL Check Username Availability

PHP MYSQL USER NAME AVAILABILITY CHECK

https://code-boxx.com/check-username-availability-php-mysql/

NOTES

  1. Create a test database and import 1-users.sql.
  2. Change the database settings to your own in 2-users-lib.php.
  3. Access 4a-register.html in your browser. Captain Obvious, use http://. Not file://.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `users` (
`user_id` bigint(20) NOT NULL,
`user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `users` (`user_id`, `user_name`) VALUES
(1, 'joedoe'),
(2, 'johdoe'),
(3, 'joidoe'),
(4, 'jondoe'),
(5, 'joydoe');
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`),
ADD UNIQUE KEY `user_name` (`user_name`);
ALTER TABLE `users`
MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
<?php
class Users {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo = null;
private $stmt = null;
public $error = null;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) HELPER FUNCTION - RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GET USER BY USERNAME
function getByName ($name) {
$this->query("SELECT * FROM `users` WHERE `user_name`=?", [$name]);
return $this->stmt->fetch();
}
// (E) ADD NEW USER
function add ($name) {
// (E1) VALID USER NAME
if (preg_match("/\s/", $name)) {
$this->error = "User name cannot contain spaces.";
return false;
}
// (E2) ALREADY REGISTERED
$user = $this->getByName($name);
if (is_array($user)) {
$this->error = "$name is already registered.";
return false;
}
// (E3) INSERT
$this->query("INSERT INTO `users` (`user_name`) VALUES (?)", [$name]);
return true;
}
}
// (F) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (G) NEW USERS OBJECT
$_USR = new Users();
<?php
if (isset($_POST["req"])) {
require "2-users-lib.php";
switch ($_POST["req"]) {
case "add":
echo $_USR->add($_POST["name"]) ? "OK" : $_USR->error;
break;
}}
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
<meta charset="utf-8">
<script src="4b-register.js"></script>
<link rel="stylesheet" href="4c-register.css">
</head>
<body>
<form id="register" onsubmit="return register()">
<label>User Name</label>
<input type="text" name="name" required>
<input type="submit" value="Register">
</form>
</body>
</html>
function register () {
// (A) FORM DATA
var data = new FormData(document.getElementById("register"));
data.append("req", "add");
// (B) AJAX FETCH
fetch("3-users-ajax.php", { method:"POST", body:data })
.then(res => res.text())
.then(txt => {
// (B1) ADD OK - REDIRECT TO WELCOME PAGE? RELOAD?
if (txt == "OK") {
alert("OK");
// location.href = "welcome.html";
}
// (B2) NOT OK
else { alert(txt); }
})
.catch(err => console.error(err));
// (C) PREVENT FORM SUBMIT
return false;
}
/* DOES NOT MATTER - COSMETICS */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
form {
width: 320px;
padding: 20px;
border: 1px solid #e1e1e1;
background: #f3f3f3;
}
label, input {
display: block;
width: 100%;
}
label {
color: #5e5e5e;
margin: 0 0 5px 0;
}
input[type=text] {
padding: 10px;
border: 1px solid #cdcdcd;
background: #fff;
}
input[type=submit] {
margin-top: 20px;
padding: 10px;
border: 0;
color: #fff;
background: #2e3fb5;
cursor: pointer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment