This is the full code to grab the username from a db using mysqli
Check mysqli_stmt_fetch($stmt) for a doesExist and echo appropriately or use simons example above if (mysqli_stmt_fetch($stmt)) {
$con = mysqli_connect("localhost","name","pass","database") or die("Error " . mysqli_error($con));
$username = $_POST['username'];
$stmt = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt,"SELECT username FROM table WHERE username = ?");
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
$doesExist = mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
if($doesExist) {
echo $username. ' exists';
}
else {
echo $username. ' doesn\'t exist';
}
Callable:
$con = mysqli_connect("localhost","name","pass","database") or die("Error " . mysqli_error($con));
if(isset($_POST['username'])) {
$username = $_POST['username'];
$stmt = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt,"SELECT username FROM table WHERE username = ?");
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
$doesExist = mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
if($doesExist) {
echo $username. ' exists';
}
else {
echo $username. ' doesn\'t exist';
}
}
As a Function:
function checkUsername($username) {
$con = mysqli_connect("localhost","name","pass","database") or die("Error " . mysqli_error($con));
$stmt = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt,"SELECT username FROM table WHERE username = ?");
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
$doesExist = mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
if($doesExist) {
echo $username. ' exists';
}
else {
echo $username. ' doesn\'t exist';
}
}
Function Usage
if(isset($_POST['username'])) {
checkUsername($_POST['username']);
}
Optional Form
(This form requires the above function to be on the same page)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="username"/>
<input type="submit" value="Check Username">