我一直試圖通過php將json文件中的數據插入到mysql中。 我有一個功能在一個文件中插入,而解碼在另一個文件中完成。 當我運行的代碼,我收到此錯誤:JSON沒有正確地通過php插入到mysql
You could not be registered due to a system error. We apologize for any inconvenience.
Column 'password' cannot be null
Query: INSERT INTO users (id, email, password, username, deviceId, date_created) VALUES (null, ?, ?, ?, ?, NOW())
Query was executed
enter code here
這裏是我的三個文件:
insertion.php:
//Require files
require('functions.php');
if(file_exists('data.json')){
echo "The file exists ";
$file= file_get_contents('data.json');
echo json_encode('data.json');
$data=json_decode($file, true);
var_dump($data);
$email= $data["email"];
$password= $data["password"];
$username= $data["username"];
$deviceId= $data["deviceId"];
$tableName= 'users';
$email= "[email protected]";
$error=json_last_error();
echo "<br><br>";
echo "your email shoudl be displayed right here: ".$email. "This is email";
echo "<br>JSON Errors will display here:". $error;
$execute= dataInsert($tableName, $email, $password, $username, $deviceId);
if($execute){
echo "Query was executed";
}
}
else{
echo "file does not exist";
}
的functions.php:
//------------------------dataInsert()---------------------------//
function dataInsert($tableName, $email, $password, $username, $deviceId){
//set database connection
require('mysqli_connect.php');
if($dbc){
echo "<h3>connection successful</h3>";
}
//form query using the values and tablename
$query = "INSERT INTO users (id, email, password, username, deviceId, date_created)
VALUES (null, ?, ?, ?, ?, NOW())";
//Prepare statement
$stmt= mysqli_prepare($dbc, $query);
//Bind the variables
mysqli_stmt_bind_param($stmt, 'sssi', $email, $password, $username, $deviceId);
//Execute the query
$result=mysqli_stmt_execute($stmt);
if($result){
echo "Success !";
}
else{
// Public message:
echo 'System Error
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $query . '</p>';
}
mysqli_close($dbc); // Close the database connection.
return true;
}
data.json
<pre>
<code>
{"users":[
{
"email":"[email protected]",
"password":"mypass12",
"username":"myusername",
"deviceId":"21"
}
]}
當我用var_dump顯示JSON數組,它看起來是正確的:
"data.json"array(1) { ["users"]=> array(1) { [0]=> array(4) { ["email"]=> string(19) "[email protected]" ["password"]=> string(6) "mypass12" ["username"]=> string(13) "myusername" ["deviceId"]=> string(2) "21" } } }
我已經能夠將行插入數據庫中,但他們都是空白的,除了日期和汽車增量ID。當我設置$ email = [email protected]時,它將顯示密碼不能爲空,但註釋該行將導致錯誤顯示'電子郵件'不能爲空
嘗試刪除ID在查詢中插入 – claudios
我刪除在插入ID和空自的值,但我仍然得到相同的錯誤 – Fritz
也嘗試刪除查詢參數date_created – claudios