Peter Pik Peter Pik - 6 months ago 15
SQL Question

php api insert query do not add to database

i've created below very simple script which is suppose to take information and insert it into a database, however nothing happens when i do, what could tricker this? i've tried running following in the url:

http://localhost/insert.php?title=test&body=lol&longitude=12&latitude=53&status=0


<?php

$db = new mysqli("localhost","test","test", "test");

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

if (isset($_GET['title']) && isset($_GET['body']) && isset($_GET['longitude']) && isset($_GET['latitude'])) {
$title = $_GET['title'];
$body = $_GET['body'];
$longitude = (float)$_GET['latitude'];
$latitude = (float)$_GET['latitude'];


$strSQL = $db->query("INSERT INTO camps (title, body, longitude, latitude, status) VALUES (`$title`, `$body`, `$longitude`,`$latitude`, 0)");



}



?>

Answer

You should check for Errors after executing an query.

Remove the back ticks around the values in your query, because These are for escaping column names. You should use single quotes instead:

 $strSQL = $db->query("INSERT INTO camps (title, body, longitude, latitude, status) VALUES ('$title',  '$body', '$longitude','$latitude', 0)");

But the best solution is to learn about prepared Statements.

Comments