1

I am fairly new to SQL and I am trying to write code to insert information from a messages form. Here is the SQL code:

$con = mysqli_connect($hostname,$username,$password,$db);

// Check connection
if (mysqli_connect_error()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$name = mysqli_real_escape_string($con, $_POST['name']); 
$email = mysqli_real_escape_string($con, $_POST['email']); 
$message = mysqli_real_escape_string($con, $_POST['message']); 

$sql = "INSERT INTO messages (name, email, message) VALUES ( '$name' , '$email' , '$message' )";


if (!mysqli_query($sql)) {
die ('Error: ' . mysqli_error());
}
else {
echo "<html><script language='JavaScript'> alert('Thank you for your submission.'),window.location = 'home'</script></html>";
}

This code returns "Error: " that I interpreted as it thinking there is an error, but there isn't any errors. The connection variables in mysqli_connect are all correct, but I am unsure if I am using the mysqli_real_escape_string correctly and even the $sql statement, because this code also doesn't insert anything into my database. Thanks in advance.

Will
  • 122
  • 1
  • 9

2 Answers2

1

As per the mysqli_query() documentation, if you are using the procedural notation you need to include your mysqli link:

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

This would suggest you need to pass in $con to mysqli_query() as you have with your other function calls as below:

mysqli_query($con, $sql)

Also, please look up and read about parametrization as your code as it is should not be used on a live site as you are vulnerable to SQL injection. Please take the time to read this and learn how to prevent it.

Peter Featherstone
  • 7,835
  • 4
  • 32
  • 64
1

Try running the query this way

mysqli_query($con, $sql);

mysqli_query requires the link to your db connection which is "$con"

staynjokede
  • 87
  • 1
  • 9