when I enter a command to execute the script, namely ‘php get.php ‘, then the following error is displayed:
PHP Warning: Attempt to read property "devEUI" on null in /var/www/html/get.php on line 8
PHP Fatal error: Uncaught mysqli_sql_exception: Column count doesn't match value count at row 1 in /var/www/html/get.php:24
Stack trace:
#0 /var/www/html/get.php(24): mysqli->query()
#1 {main}
thrown in /var/www/html/get.php on line 24
I can’t figure out what the problem is, I’m asking for help editing the code…
here is the code I tried to run:
<?php
header("Content-type: application/json");
$json = file_get_contents("php://input");
$obj = json_decode($json);
#$decoded = base64_decode(json_encode($obj->data));
$id = $obj->devEUI;
$server = "localhost:3306";
$username = "phpmyadmin";
$password = "srv";
$DB = "cows";
$conn = new mysqli($server, $username, $password, $DB);
if ($conn->connect_error)
{
die("Connection_failed: " . $conn->connect_error);
}
$insert = "INSERT INTO rum(st1) VALUES ($id)";
$conn->query($insert);
$conn->close();
?>
the code is needed to send data using a script to the database. the data in the frame is 12.
I tried to change the code, the file was named get2.php
here is the code that I got:
<?php
// Устанавливаем правильную кодировку для корректного отображения текста на русском языке
header("Content-type: application/json; charset=utf-8");
// Получаем JSON данные из тела запроса
$json = file_get_contents("php://input");
error_log($json); // Логирование полученного JSON
// Декодируем JSON данные в объект PHP
$obj = json_decode($json);
// Проверяем, удалась ли декодирование и нет ли ошибок
if ($obj === null && json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(array('error' => 'Недопустимые данные в формате JSON: ' . json_last_error_msg()), JSON_UNESCAPE>
exit;
}
// Получаем значение devEUI из объекта
$id = $obj->devEUI;
$server = "localhost";
$username = "phpmyadmin";
$password = "srv";
$DB = "cows";
// Создаем соединение с базой данных
$conn = new mysqli($server, $username, $password, $DB);
// Проверяем успешность подключения
if ($conn->connect_error) {
die("Ошибка подключения: " . $conn->connect_error);
}
// Подготавливаем SQL запрос для вставки данных
$insert = $conn->prepare("INSERT INTO rum (st1) VALUES (?)");
$insert->bind_param("s", $id);
// Выполняем подготовленный запрос
if ($insert->execute()) {
echo json_encode(array('message' => 'Новая запись успешно добавлена'), JSON_UNESCAPED_UNICODE);
} else {
echo json_encode(array('error' => 'Ошибка: ' . $insert . '<br>' . $conn->error), JSON_UNESCAPED_UNICODE);
}
// Закрываем соединение с базой данных
$insert->close();
$conn->close();
?>
after its execution, an error is displayed:
“error”:”Invalid data in JSON format: Syntax error”
please tell me what to do about it
Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.