The Problem
The real reason this script is failing to record anything into the database is because at line 7, you have a line of code that tells the script to die if there is an error in the database connection:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
But what if the connection was successful? We look for the CLOSING BRACES for the if ($conn->connect_error) statement, which is found at line 22:
}
?>
But instead of doing things that should happen if the connection is successful, this script ends immediately after the closing brace to the code block for the if ($conn->connect_error) statement. In other words, nothing happens.
The Fix
Remove the closing bracket at line 22, below the $conn->close(); statement; and place it instead immediately after the die(); statement.
Next, fix a few syntax errors:
- You need a semicolon after the
mysqli_real_escape_string() statement.
- Don't use '-' (dashes or minus signs) in variable names. Remove them or replace them with the more conventional underscore character (_).
Your SQL syntax is incorrect. Try something like this:
$sql = "INSERT INTO table_name ('APP_NAME') VALUES ('".$field1."')";
Because you have already connected to your desired database ($dbname = "db";), SQL only needs to know the table to use within that database. Replace table_name from my example as appropriate. It'll be the table with a column called APP_NAME where it appears you want to store the form's post data. Finally, for the VALUES(), it is best to use the ('".$field1."') format rather than ('$field1') because it is more explicit. The latter will cause you problems under certain circumstances.
My rewrite of your code looks like this:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$field1 = mysqli_real_escape_string ( $conn , $_POST['field1']);
$sql = "INSERT INTO table_name ('APP_NAME') VALUES ('".$field1."')";
if ($conn->query($sql) === TRUE) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>