$bdd = new PDO('mysql:host=localhost;dbname=message_receiver', 'root', '',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$itms = [];
$i = 0;
for ($i ; $i < count($json); $i ) {
$itms[] = '(
' . floatval($json["result"][$i]['server.timestamp'] ?? 0) . ',
' . floatval($json["result"][$i]['position.longitude'] ?? 0) . ',
' . floatval($json["result"][$i]['position.latitude'] ?? 0) . ',
' . floatval($json["result"][$i]['timestamp'] ?? 0) . ',
' . floatval($json["result"][$i]['position.altitude'] ?? 0) . ',
' . floatval($json["result"][$i]['position.direction'] ?? 0) . ',
' . floatval($json["result"][$i]['position.speed'] ?? 0) . ',
' . intval($json["result"][$i]['position.satellites'] ?? 0) . '
)';
}
try
{
$requete = $bdd->prepare("
UPDATE
php_message_listener
SET
server.timestamp =?,
position.longitude =?,
position.latitude =?,
timestamp =?,
position.altitude =?,
position.direction =?,
position.speed =?,
position.satellites =?,
WHERE ident = '$ident_same_update'
");
$requete->execute(array(json_encode($itms)));
}catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
CodePudding user response:
There are two main issues in your code. Firstly, replace
$itms = [];
$i = 0;
for ($i ; $i < count($json); $i ) {
$itms[] = '(
' . floatval($json["result"][$i]['server.timestamp'] ?? 0) . ',
' . floatval($json["result"][$i]['position.longitude'] ?? 0) . ',
' . floatval($json["result"][$i]['position.latitude'] ?? 0) . ',
' . floatval($json["result"][$i]['timestamp'] ?? 0) . ',
' . floatval($json["result"][$i]['position.altitude'] ?? 0) . ',
' . floatval($json["result"][$i]['position.direction'] ?? 0) . ',
' . floatval($json["result"][$i]['position.speed'] ?? 0) . ',
' . intval($json["result"][$i]['position.satellites'] ?? 0) . '
)';
}
with
$i=0;$jri=$json["result"][$i];
$itms = [
$jri['server.timestamp'] ?? 0,
$jri['position.longitude'] ?? 0,
$jri['position.latitude'] ?? 0,
$jri['timestamp'] ?? 0,
$jri['position.altitude'] ?? 0,
$jri['position.direction'] ?? 0,
$jri['position.speed'] ?? 0,
$jri['position.satellites'] ?? 0
]
And secondly, further down, replace
$requete->execute(array(json_encode($itms)));
with
$requete->execute($itms);
This should supply the required array with 8 elements to the PDO::execute()
method. I haven't tested it but I expect it to work.
From your question it is not clear how many elements there are in the array $json["result"]
. With the above snippet ($i=0
) only the first element will be considered. You might have to use a loop if you want to do the same action with all elements of $json["result"]
. But for this case you should also make ident
in your MySQL table php_message_listener
parametric, i. e. bind a suitable PHP variable with the relevant id to it using another ?
in your bdd->prepare()
statement. The current PHP variable $ident_same_update
seems to contain only one value.