0

When I did insert into the database, it worked. But when I try Update into the Database it doesn't insert the value.

<?php
// Connecting to MySQL Database.
$con = mysqli_connect("localhost", "root", "****", "users");
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
$username = $obj['username'];
// Populate Student name from JSON $obj array and store into $S_Name.
$Q1 = $obj['q1'];
// Populate Student Class from JSON $obj array and store into $S_Class.
$Q2 = $obj['q2'];
// Populate Student Phone Number from JSON $obj array and store into $S_Phone_Number.
$Q3 = $obj['q3'];
// Populate Email from JSON $obj array and store into $S_Email.
$Q4 = $obj['q4'];
// Creating SQL query and insert the record into MySQL database table.
$Sql_Query = "UPDATE testuser SET q1= '$Q1', q2 = '$Q2', q3 = '$Q3', q4 = '$Q4' WHERE username = '$username'";

if(mysqli_query($con,$Sql_Query)){
    // If the record inserted successfully then show the message.
    $MSG = 'Record Successfully Inserted Into MySQL Database.' ;
    // Converting the message into JSON format.
    $json = json_encode($MSG);
    // Echo the message.
    echo $json ;
}
else{
    echo 'Try Again';
}
mysqli_close($con);
?>

If there is anything wrong with this code, please let me know. I also want to say that I am a beginner in PHP and React Native.

Devang Naghera
  • 731
  • 6
  • 13
Laney Williams
  • 573
  • 3
  • 13
  • 34
  • 1
    You're not doing any error checking at all. – Jay Blanchard Feb 08 '18 at 17:09
  • Please learn to use prepared statements with `bind_param` to prevent SQL injection. – Barmar Feb 08 '18 at 17:10
  • You are wide open for SQL injection. Since you're using mysqli, take advantage of [prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [bind_param](http://php.net/manual/en/mysqli-stmt.bind-param.php). **This will take care of any pesky quoting issues that may occur.** – aynber Feb 08 '18 at 17:11
  • You should check for [mysqli errors](http://php.net/manual/en/mysqli.error.php) to find out if there's a reason why your insert is failing. – aynber Feb 08 '18 at 17:14
  • Does it go to this `echo 'Try Again';` ? – Funk Forty Niner Feb 08 '18 at 17:19
  • It echos `''Record Successfully Inserted Into MySQL Database."` @FunkFortyNiner and yes I know about SQL injection this is just a test. – Laney Williams Feb 08 '18 at 19:14

0 Answers0