简体   繁体   中英

Json data not saved to DB in PHP

I am trying to make a functionality where I am sending Name and Age using ajax. The same is gathered by PHP and then stored to DB . I think I am doing it correctly but data not saved in database. Can someone help me out?

HTML

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('button').click(function(){
        $.ajax({
            url: 'addData.php',
            type: 'POST',
            dataType: "json",
            data: {
                name: $('#name').val(),
                age: $('#age').val(),
            }
        })
    });
});
</script>
</head>
<body> 
<input id="name" type="text" />
<input id="age" type="text" />
<button>Click</button>
</body> 
</html> 

PHP

<?php

//Parameters for connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test1";

//Reading json
$data_back = json_decode(file_get_contents('php://input'));

// set json string to php variables
$name = $data_back->{"name"};
$age = $data_back->{"age"};

// Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);

//Creating Query
$sql = "INSERT INTO table1 (name, age) VALUES ($name, $age)";

//Running Query
$conn->query($sql);

//Closing Connection
$conn->close();

?>

ERROR

在此输入图像描述

Even though you're sending data with jquery as json, php is still recieving it as a $_POST object. So, this should work:

 $name = $_POST['name']; $age = $_POST['age']; 

I think your object $data_back is empty because of errors in parsing of data by function json_decode. You should try to use var_dump($data_back); exit; after json_decode or more advanced methods such as debugging.

I believe this is the proper way to access data post json_decode

$name = $data_back->name;

I also recommend looking into prepared statements for the database query execution...Ok, I HIGHLY recommend you look into it.

Edit: Maybe try this as well: Replace file_get_contents() with $_POST ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM