0

I created the following scripts to send data to server, but when I use postman to send data in json format it sent blanks data, the following are my scripts

 <?php
header("Content-Type: application/json; charset=UTF-8");


//open connection to mysql db
$connection = mysqli_connect("localhost","wamesh","wames9est","wam90est")
or die("Error " . mysqli_error($connection));




// recieved from app
$mtitle = $_POST['mytitle'];
$mdate = $_POST['mydate'];
$mnews = $_POST['mynews'];


echo "Response: ".$mtitle." ";


$sql_query = "INSERT INTO news (title,news,time) VALUES ('$mtitle','$mnews','$mdate')";


if (mysqli_query($connection, $sql_query)) {
    echo "We just posted a news response!";
} else {
    echo "Error: " . $sql_query . "<br>" . mysqli_error($connection);
}

mysqli_close($conn);


?>

and this is a sample of data I try to send

{
    "mytitle": "COVID 19 Updates",
    "mynews": "COVID 19 - Breaking News",
    "mydate": "19 may 2020"
}

in postman it shows success but in database I just found row added but no values inside.

  • print the content of `$_POST` to clarify what data is received by the server – Guga Nemsitsveridze May 19 '20 at 08:20
  • The code works on my end. Be sure to close: mysqli_close($connection); And make sure your form specified method="post" – Chris Medina May 19 '20 at 08:33
  • Setting this response header: `header("Content-Type: application/json; charset=UTF-8");` makes no sense because your script is outputting plain text or HTML, not JSON – ADyson May 19 '20 at 08:35
  • This might help you with receiving the data from postman: https://stackoverflow.com/questions/18866571/receive-json-post-with-php – ADyson May 19 '20 at 08:35
  • Also: **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson May 19 '20 at 08:35
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli – ADyson May 19 '20 at 08:35

1 Answers1

-1

Check the $_POST if it contain any data and use prepared statemnt when dealing with DB. Yours can be SQL Injection

zimorok
  • 326
  • 1
  • 11