CodingFTW CodingFTW - 4 months ago 23
MySQL Question

How to Compare a String in an SQL Database to a PHP Variable

Ok, so as the title says, I want to find out how I can compare a string in an SQL database to a PHP string.

<!DOCTYPE html>

<title>Processing Request</title>
<link rel="Stylesheet" href="style.css" type="text/css" />

<h1>Account Creation</h1>

$dbhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect("$dbhost", "$username", "$password");
$db = "accounts";

if (!$connect){
die("ERROR: Database connection failed: " . mysqli_connect_error());

mysqli_select_db($connect, $db);

$makeUser = $_POST["makeUser"];
$makePass = $_POST["makePass"];
$sql = "INSERT INTO accounts (username, password) VALUES ('$makeUser', '$makePass')";

if("SELECT username FROM accounts WHERE username = '$makeUser'"){

The line of code above is where I am trying to compare a value (from the column "username" in the table "accounts") in my SQL database to a string that the user entered to create an account ($makeAccount). This specific piece of code is suppose to tell the user if the username they are trying to set their for their account has already been taken.

However, everytime I run this code (and enter a username into the form that I can visually see in my database is not taken), it still says the username has already been taken, even though it's definetly not.

header("Location: createaccount.php?status=userTaken");
mysqli_query($connect, $sql);
echo "Account creation was succesful!";


Click <a href="index.php">here</a> to login.


Thank you, all answers are appretiated. :)

P.S. This is the first program I am writing in PHP and the first time I am using an SQL database, so please, try to keep it simple, and understandable.

P.S.S I have tried many solutions, all with no success.


Please change the if statement of your comparison


if("SELECT username FROM accounts WHERE username = '$makeUser'"){


if(mysqli_query("SELECT username FROM accounts WHERE username = '$makeUser'")){