CodingFTW CodingFTW - 1 month ago 8
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>
<html>

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

<body>
<h1>Account Creation</h1>
<h3>

<?php
$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");
}
else{
mysqli_query($connect, $sql);
echo "Account creation was succesful!";
}

mysqli_close($connect);
?>

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

</h3>
</body>
</html>


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.

Answer

Please change the if statement of your comparison

from

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

to

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