Note that there are some explanatory texts on larger screens.

plurals
  1. POmysqli_real_escape and mysqli prepare both turn variable null?
    primarykey
    data
    text
    <p>I have been trying to secure my code for a few days since reading about mysql injection. The trouble I am having is that when I edit my code to add mysqli_real_escape_string it changes the variable I am trying to insert into the database to null.</p> <p>So no problem I thought, I can just go a step further and use a prepared statement instead. Only problem is, that is changing all the POST variables to null. Not sure what to do. both of the codes below run without error except that the first enters everything into the database except $escapecomment and the second insert NOTHING into the database. </p> <p>I have looked around quite a bit but when searching the problems others have had and corrected don't seem to be the problem I have. I am 100% sure that the variables have a value as when I remove $escapecomment = mysqli_real_escape_string($_POST['comment']); and just make the Value $_POST['comment'] instead of $escapecomment it works perfectly but obviously, is not very secure. Thanks for your time and knowledge.</p> <p>First code with mysqli_real_escape_string</p> <pre><code>$con=mysqli_connect($host,$username,$password,$dbname); if (mysqli_connect_errno()) { mysqli_connect_error(); } $escapecomment = mysqli_real_escape_string($_POST['comment']); $sql="INSERT INTO comments (cid, username, comment) VALUES ('$_POST[cid]','$_POST[username]','$escapecomment')"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error()); } mysqli_close($con); </code></pre> <p>Second code where I use prepared statements instead</p> <pre><code>$con=mysqli_connect($host,$username,$password,$dbname); // Check connection if (mysqli_connect_errno()) { mysqli_connect_error(); } /* Create the prepared statement */ if ($stmt = $con-&gt;prepare("INSERT INTO comments (cid, username, comment) values (?, ?, ?)")) { /* Bind our params */ $stmt-&gt;bind_param('iss', $ccid, $cusername, $ccomment); /* Set our params */ $ccid = $_POST[cid]; $cusername = $_POST_['username']; $ccomment = $_POST['comment']; /* Execute the prepared Statement */ $stmt-&gt;execute();} $stmt-&gt;close(); </code></pre> <p>Any thoughts? Thank you</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload