0

I'm trying to insert the data that's in the form into the database that I made. I keep getting this error when I check if the data is in the database:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'user_comments' at line 1

This is my php:

<?php
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
    die('Failed to connect to MySql:'.mysql_error());
}else{
    echo "it worked";
}

if(isset($_POST['insertComments'])){
    $name=$_POST['name'];
    $comment=$_POST['comment'];
    mysqli_query($db_connection,"INSERT INTO user_comments (name, comment) VALUES ($name, $comment)");
    Print "Your information has been successfully added to the database.";
}

?>

This is my html:

<div id="uploadComments">
    <form id="insertComments" name="insertComments" method="post">
        <label for="name">Name: </label><input type="text" id="name" name="name"><br/>
        <label for="comment">Comments: </label><textarea name="comment" id="comment"></textarea>
        <input type="submit" value="Submit">
    </form>
</div>
Sammitch
  • 30,782
  • 7
  • 50
  • 77
lorenzo456
  • 29
  • 1
  • 7
  • 2
    Nice security hole you have there, check this http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – Fabio Mar 10 '14 at 20:31
  • 2
    You need to quote and escape your values. But the best solution would be to use a prepared statement. Also see http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – jeroen Mar 10 '14 at 20:32
  • @Fabio This guy is obviously a beginner... so your comment is completely useless to him. How about explaining why there is a security hole? Or pointing him to a link that explains SQL injection attacks? – bobwienholt Mar 10 '14 at 20:32
  • If you echo your query before running it you should be able to see exactly what's wrong with the syntax. Sorry I couldn't give any exact answers this time. – Arthur Hylton Mar 10 '14 at 20:31

1 Answers1

1

As pervious people have commented you should construct your "query" separately, makes it easier to handle and change. Additionally when passing any variable into your query you need to bring them out of the string so PHP can process them correctly.

Here is how I would suggest you structure your code:

....

$name=$_POST['name'];
$comment=$_POST['comment'];

$sql="INSERT INTO user_comments (name, comment)VALUES('{$name}','{$comment}')";

if (!mysqli_query($db_connection,$sql))
{
 die('Error: ' . mysqli_error($con));
 }
echo "1 record added";
binaryNomad
  • 336
  • 2
  • 6