-3

I’m having some problems with my database.

MySQL database is organized as:

——————————————————————
userId | value
——————————————————————
63     | {"pro":true}

The GET requests are working just fine but not the POST requests. POST requests return me just nothing, when it should return a JSON with a success index.

This is my index.php code:

<?php
    $database = "";
    $username = "";
    $password = "";
    $servename = "localhost";

    $connection = new mysqli($servername, $username, $password, $database);

    if ($connection->connect_error) {
        die("Connection failure: ".$connection->$connection_error);
    }

    header("Content-type: application/json");

    if ($_SERVER["REQUEST_METHOD"] == "GET") {
        if ($_GET["userId"]) {
            $result = $connection->query("SELECT value FROM main_table WHERE userId = ".$_GET["userId"]);
            if ($result->num_rows > 0) {
                echo $result;
            }
            else {
                echo json_encode(array());
            }
        }
    }
    elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
        if ($_POST["userId"] && $_POST["value"]) {
            $result = $connection->query("INSERT INTO main_table (userId, value) VALUES ('".$_POST["userId"]."', '".$_POST["value"]."')");
            if ($result) {
                echo json_encode(array("success" => TRUE));
            }
            else {
                echo json_encode(array("success" => FALSE));
            }
        }
    }

    $connection->close();
?>

Could you guys spot any mistakes in my code?

Thank you in advance!

Octonions
  • 1
  • 3

1 Answers1

1

your code is not secure ,Use this to avoid sql injection

Simple you can should as below code ..also better safety

For select


$query = "
    SELECT *
    FROM main_table
    WHERE userId= ?
";
$stmt = $connection->prepare($query);


$userId=$_GET["userId"];

$stmt->bind_param("i", $userId);

$result = $stmt->get_result();

$rows=[];
while ($data = $result->fetch_assoc())
{
    $rows[] = $data;
}

echo json_encode($rows);


Insert for example


$stmt = $connection->prepare("INSERT INTO main_table (value,userId) VALUES (?, ?)");
$stmt->bind_param("ii", $_POST['value'], $_POST['userId']);
if($stmt->execute())

{
  echo "insert successful";

}
else
{

 echo "couldn't insert successful";

}
$stmt->close();

dılo sürücü
  • 3,821
  • 1
  • 26
  • 28