2

I'm trying to make a form that adds information to my MySQL database. To do that, I have four scripts:

<html>
<head><title>Insert Data Into MySQL: jQuery + AJAX + PHP</title></head>
<body>

<form id="myForm" action="user_info.php" method="post">
User_id: <input type="text" name="user_id" /><br />
Hash : <input type="text" name="hash" /><br />
<button id="sub">Save</button>
</form>

<span id="result"></span>

<script src="jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="jcode.js" type="text/javascript"></script>
</body>
</html>

That's my main page, it mentions two other files, which are user_info.php and jcode.js (ignore the jQuery piece). This is user_info.php

<?php
        include_once('db.php');

        $user_id = $_POST['user_id'];
        $hash = $_POST['hash'];

        if(mysqli_query("INSERT INTO _test('user_id, 'hash') VALUES('$user_id', '$hash')"))
          echo "Successfully Inserted";
        else
          echo "Insertion Failed";
?>

It points to db.php, so here's that:

<?php
$con=mysqli_connect(" **taken out** ","root","password","test");
?> 

and finally, here's jcode.js:

$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); 
   });
 clearInput();
});

$("#myForm").submit( function() {
  return false; 
});

function clearInput() {
    $("#myForm :input").each( function() {
       $(this).val('');
    });
}

For a while, it would say that the insertion was successful. But strangely,it would input blank rows in the database. I don't know what needs to be changed but now it just says "Insertion Failed". I'm fairly new to this technology, so I'm probably missing something obvious.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 3
    So much SQL Injection oppurtunity. Please [`read this`](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1) and sanitize your user input. – Darren Jul 18 '14 at 03:20
  • 1
    What happens to your script if I post `'; DROP TABLE _test;` as my user ID? – Machavity Jul 18 '14 at 03:21
  • why do you have single quotes around your column names -> `'user_id, 'hash'`, and you are missing the closing around `userid` -> `'user_id`? typically mysql will fail, as column names either need to be unquoted -> `user_id, hash` or with backticks -> `\`user_id\`, \`hash\``. Is this just a copy/paste error/typo? – Sean Jul 18 '14 at 03:35
  • @Machavity , did it happen with Any site ever before ? – Pratik Joshi Jul 18 '14 at 03:49

1 Answers1

0

It will be useful if you print for us the return of

mysqli_error($con); 

after the line of

echo "Insertion Failed";

From now, what can I say is that it's not an AJAX/jQuery problem (conceptual, at least) More information about mysqli_error function can be found here.

And please, before getting it in production sanitize the user inputs as suggested here.

Community
  • 1
  • 1
Hamlett
  • 403
  • 6
  • 22