I have an array ($array) which is structured like that:
[auctions]
(
[0]
(
[item]
(
[id] => 45422
)
[quantity] => 22
[buyout] => 40
[bid] => 25
)
[1]
(
[item]
(
[id] => 24555
)
[quantity] => 85
[buyout] =>120
[bid] => 58
)
[2]
....
I want to store some of these values in a mysql table. Additionally I want a timestamp and if the item->id
already exists in my table (as the primary key) the other values should just get updated.
[item] -> [id]
[quantity]
[buyout]
TIMESTAMP
I tried it like that:
foreach ($array['auctions'] as $auctiondata) {
$sql ="INSERT INTO `blackrock` (`item_id`, `actual_prices`, `actual_quantity`, `last_update`) VALUES ('". $auctiondata['item']['id']."', '". $auctiondata['buyout']."', '". $auctiondata['quantity']."', 'CURRENT_TIMESTAMP')
ON DUPLICATE KEY UPDATE item_id='". $auctiondata['item']['id']."', '". $auctiondata['buyout']."', '". $auctiondata['quantity']."'";
}
I suggest you to google "php mysql insert" first There are some references to you
It is no meaning if you update the id when the key duplicated I think you can use REPLACE INTO instead of ON DUPLICATE KEY UPDATE if there are no any operation.
Please note that the old row will be deleted before it make a new row with the same id and the updated data
In addition, curly braces serve good substitution for concatenation PHP is forced to re-concatenate with every '.' operator, slow.
w3schools.com - PHP MySQL Insert Data
MySQL 8.0 Reference Manual - REPLACE Statement
<?php
$conn = new mysqli("localhost", "ur_db_username", "ur_db_password", "ur_schema");
if ($conn->connect_error) {
//
}
foreach ($array['auctions'] as $auctiondata) { {
//`actual_prices` = $auctiondata['buyout'] according to your code provided
//it is no meaning if you update the id when the key duplicated
//i think you can use REPLACE instead of ON DUPLICATE KEY UPDATE
$sql = "REPLACE INTO `blackrock`
(`item_id`, `actual_prices`, `actual_quantity`, `last_update`)
VALUES
('{$auctiondata['item']['id']}', '{$auctiondata['buyout']}', '{$auctiondata['quantity']}', NOW())";
if ($conn->query($sql) === TRUE) {
//
} else {
//
}
}
$conn->close();
?>
The above if the code mainly copy from the site I provided You need to implement the error handling
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.