OLucky OLucky - 2 months ago 7
MySQL Question

PHP doesn't send data to MySQL

Have some problem I couldn't find solution for, though searched through many sources(and questions here too). So, here it is.

With php-code below I suppose to collect data from html-form and send it to local WAMP-server. But, though final check shows me "Success!", no new rows in the database's table are found, it stays empty. Names are correct, commands are (as I see it) too, so I just don't know what's wrong.

I hope you guys could help me. ^^


<?php
//Check if user submited a form
if (isset($_POST['submit']))
{
//Check if from is properly filled
if (empty($_POST['itemName'])||empty($_POST['itemPic'])||empty($_POST['itemPrice'])||empty($_POST['itemProvider']))
{
echo '<script>alert ("Fill out the form please!")</script>';
}
else {
$conn = new mysqli('localhost:3306','root','','goods-review');
//Check if connection established
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
//Sending data
$newItem = array('itemName' => $_POST['itemName'], 'itemPic' => $_POST['itemPic'], 'itemPrice' => $_POST['itemPrice'], 'itemProvider' => $_POST['itemProvider']);
$sql = "INSERT INTO goods (itemName, itemPic, itemPrice, itemDate, itemProvider) VALUES ('".$newItem['itemName']."', '".$newItem['itemPic']."', '".$newItem['itemPrice']."', date('Y:m:d, H:i:s'), '".$newItem['itemProvider']."')";
//Check if sent
if ($sql){
echo '<script>alert ("Success!")</script>';
}
else{
echo '<script>alert ("Error!")</script>';
}
$conn->close();
}
}
?>

Answer

The code is just assigning a string value to a variable.

  $sql = "INSERT ...";

And the string value is not submitted to the database; it's not being executed as a SQL statement. There's nothing magical about the name of the variable. As far as PHP is concerned, the code is just assigning a value to a variable. That's it.

If you want to execute a SQL statement, you need to add code that actually does that. It shouldn't be difficult to find an example of how to do that.

IMPORTANT NOTE: The code in the question appears to create a SQL statement that is vulnerable to SQL Injection. A much better pattern is to use prepared statements with bind placeholders.

Reference: mysqli_prepare

If there's some (unfathomable) reason that you can't use prepared statements, then at a minimum, any potentially unsafe values that are included in the SQL text must be properly escaped.

Reference: mysqli_escape_string

Comments