gpt4 book ai didi

php - JSON无法通过php正确插入到mysql中

转载 作者:行者123 更新时间:2023-11-29 20:50:56 25 4
gpt4 key购买 nike

我一直在尝试通过php将json文件中的数据插入到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

这是我的三个文件:

插入.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@example.com";

$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";

}

函数.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;
}

数据.json

<pre>
<code>
{"users":[
{
"email":"fakeemail@gmail.net",
"password":"mypass12",
"username":"myusername",
"deviceId":"21"
}

]}

当我使用 var_dump 显示 json 数组时,它看起来是正确的:

"data.json"array(1) { ["users"]=> array(1) { [0]=> array(4) { ["email"]=> string(19) "fakeemail@gmail.net" ["password"]=> string(6) "mypass12" ["username"]=> string(13) "myusername" ["deviceId"]=> string(2) "21" } } } 

我已经能够将行插入数据库,但除了日期和自动递增 ID 之外,它们都是空白的。当我设置 $email= email@example.com 时,它将显示密码不能为空,但是注释掉该行将导致错误显示“email”不能为空

最佳答案

您将在 ID 字段中插入 null。尝试删除它。

关于php - JSON无法通过php正确插入到mysql中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com