简体   繁体   中英

Compare PHP input with database using MySQLi

I am having problems with a code. It is suppose to check if the input name is the same as the information in the database for Name.

If not, it prints a different result and add this information to the database.

My problem is that the code in the else never works. It always prints the result of the if.

Also, when I try to copy the code for the INSERT in the if it does not insert any information in the database.

What I am doing wrong?. I am totally new in php and mysql

 <!DOCTYPE HTML> <html> <head> <?php // Load the configuration file containing your database credentials require_once('config.inc.php'); // Connect to the database $mysqli = new mysqli($database_host, $database_user, $database_pass, $database_name); // Check for errors before doing anything else if($mysqli -> connect_error) { die('Connect Error ('.$mysqli -> connect_errno.') '.$mysqli -> connect_error); } $name = $_GET["name"]; $email = $_GET["email"]; $mysqli->real_query("SELECT * FROM first_project WHERE Name = '$name'"); if ($mysqli->field_count > 0 ) { echo "HAVE A GOOD DAY! $name"; echo "Your email is $email"; } else { echo "Your were not part of the database, you and your data have been added $name"; $mysqli->query( "INSERT INTO first_project VALUES ('$name', '$email')"); } $mysqli -> close(); ?> </body> </html> 

Do the basic error checks first:

1 Check the error log to see if your mysql threw an error.

2 Verify that both variables exist (if (!empty(..))

3 try INSERT INTO first_project (name, email) VALUES (..,..)

4 Use prepared statements. This is to prevent people from changing your sql query causing security issues (SQL Injection)

What you are doing at the moment is IF the name exists, echo the name that the user posted. You are not actually retrieving anything from the database (you are only checking if there was a result, not sure if that was the purpose?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM