0

I am trying to create a query with an if/else condition wherein after the user inputs then submits, I need to query first and check if it is already existing in the database, then there will be an error prompt but if it does not exist, it will proceed to inserting the data.

Is it possible using the if/else condition? Any suggestions will be accepted though.

$name = $_POST['first_name'];
$age = $_POST['age'];
$birthday = $_POST['birthdate'];

$info = "SELECT * FROM user_info WHERE name = $name";
$queryres = mysqli_query($conn,$info);

if(name != $name){     ///query to check if $name value exist in database
     $sql = "INSERT INTO user (name, age, birthdate)
            VALUES ('$name','$age', '$birthday')";
    } else {
       echo "Name already exist!";
}
Shadow
  • 30,859
  • 10
  • 44
  • 56
blue_ette
  • 1
  • 2
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Feb 20 '20 at 09:53
  • Check this https://stackoverflow.com/questions/7490991/mysql-if-exsists-insert-into-or-else-do-something-else – Full Stop Feb 20 '20 at 09:54
  • 1
    There's no need to upgrade to PDO, mysqli provides param binding also. – Andrei Feb 20 '20 at 09:54
  • yes it's possible but you need to learn how to read the results of your query properly using one of the fetch_xx functions of mysqli. Almost any tutorial should show you - did you look for anything? Although in this case you actually just need to check whether it returns any rows or not, using mysqli_num_rows (your WHERE clause already checked the name!). – ADyson Feb 20 '20 at 09:54

0 Answers0