Douwsky Douwsky - 5 months ago 12
PHP Question

Successfully created records don't show up in SQL database

This code doesn't work for some reason. It says "record created successfully", but when I check the SQL DB the record doesn't show up for some reason.

Here is my code:

<html>
<title>Voer gegevens in</title>
<body>
<?php
$serverName = "***";
$usr="*****";
$pwd="*****";
$db="********";

$connectionInfo = array("UID" => $usr, "PWD" => $pwd, "Database" => $db);

$con = sqlsrv_connect($serverName, $connectionInfo);
// $con = require_once "db_config.php";
// koppeling met de database-server, gebruikersnaam en wachtwoord

if (!$con)
{
die ("kon niet verbinden met: " . sqlsrv_connect_error());
}
echo "OK, er is verbinding met de server <br>";

$sql="INSERT INTO tblRelatie (fldNaam, fldPostcode, fldPlaats, fldAdres) VALUES ('".$_POST['Naam']."','".$_POST['Postcode']."','".$_POST['Plaats']."','".$_POST['Adres']."';)";
sqlsrv_query($con,$sql);
// Tabelnaam en alle genoemde kolom-namen waarin de waarden vervolgens worden geplaatst

if (!$con) { echo "error"; }
else { echo "1 record toegevoegd"; }
sqlsrv_close ($con);
?>
</html>


What might cause that and how do I resolve it?

Answer

You're not checking the return value from sqlsrv_query, so you're getting "success" when you should not be. This is obscuring your ability to see what's really happening.

Change the lines to this to get the proper result:

$stmt = sqlsrv_query($con, $sql);
if ($stmt === false) { echo "error: " . print_r(sqlsrv_errors(), true); }
else { echo "1 record toegevoegd"; }

The actual error is that the INSERT statement is ill-formed, at the very end of the statement. I assume that the invalid snippet $_PO ST['Adres'] is due to copy/paste error, however the real issue is immediately afterward.

This end of the statement:

$_POST['Adres']."';)";

should be changed to this:

$_POST['Adres']."');";

so that the statement terminator (;) appears outside the statement parenthesis.