I have problem with record which I must record in my table. I want update row if product with same name exist.
if ((int)$price > 0) {
$query = "SELECT name FROM phones WHERE LOWER(`name`) = LOWER(?)";
$duplicate = $this->db->query($query, array($name));
if ($duplicate->num_rows() > 0) {
$query = "update phones (name,price,shop,link,photo,priority) VALUES (?,?,?,?,?,?)";
$this->db->query($query, array($name,$price,"Pigu.lt", $link, $photos, rand(0,1000)));
} else {
$query = "insert into phones (name,price,shop,link,photo,priority) VALUES (?,?,?,?,?,?)";
$this->db->query($query, array($name,$price,"Pigu.lt", $link, $photos, rand(0,1000)));
}
}
table structure:
CREATE TABLE `phones` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(500)
COLLATE utf8_lithuanian_ci NOT NULL, `price` int(15)
NOT NULL, `shop` varchar(100)
COLLATE utf8_lithuanian_ci NOT NULL, `link` varchar(400)
COLLATE utf8_lithuanian_ci NOT NULL, `photo` varchar(500)
COLLATE utf8_lithuanian_ci NOT NULL, `priority` int(5)
NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=544 DEFAULT CHARSET=utf8 COLLATE=utf8_lithuanian_ci;
at know code dont work, please help for this
I do not know the reason why your PHP doesn't work, but since you tagged your post with mysql and sql and not php, I assume you'll accept a SQL-centric solution. Here are two; both assume that name is the primary key in table phones.
ANSI-compliant:
$query = "INSERT INTO phones (name, price, shop, link, photo, priority) \
VALUES (?,?,?,?,?,?) \
ON DUPLICATE KEY UPDATE price=?, shop=?, link=?, photo=?, priority=?";
$randnum = rand(0, 1000);
$this->db->query($query, array($name, $price, "Pigu.lt", $link, $photos, $randnum,
$price, "Pigu.lt", $link, $photos, $randnum));
MySQL-only:
$query = "REPLACE INTO phones (name, price, shop, link, photo, priority) \
VALUES (?,?,?,?,?,?)";
$this->db->query($query, array($name, $price, "Pigu.lt", $link, $photos, rand(0,1000)));
Related
I am trying to execute this query but it is not working. whenever i try to put same equal values to any two or more input variables out of total 8, the SQL query does not execute.
php file:
include './config.php';
$counter = 0;
// these are my total 8 input variables
$INDEX_NUMBER = "43385";
$STATION_NAME = "NA";
$YEAR = "2020";
$MONTH = "12";
$DATE = "18";
$Ir = "3";
$RAIN_24HOURS_ACTUAL = "NA";
$RTRTRTRT = "NA";
$sql_rain_2 ="INSERT INTO `only_rainfall_2020` (`INDEX_NUMBER`, `STATION_NAME`, `YEAR`, `MONTH`, `DATE`, `Ir`, `DAILY`, `SEASONALLY_SYNOP`) SELECT * FROM (SELECT '$INDEX_NUMBER', '$STATION_NAME', '$YEAR', '$MONTH', '$DATE', '$Ir', '$RAIN_24HOURS_ACTUAL', '$RTRTRTRT') AS tmp WHERE NOT EXISTS (SELECT `INDEX_NUMBER`, `STATION_NAME`, `YEAR`, `MONTH`, `DATE`, `Ir`, `DAILY`, `SEASONALLY_SYNOP` FROM `only_rainfall_2020` WHERE `INDEX_NUMBER` = '$INDEX_NUMBER' AND `STATION_NAME` = '$STATION_NAME' AND `YEAR` = '$YEAR' AND `MONTH` = '$MONTH' AND `DATE` = '$DATE' AND `Ir` = '$Ir' AND `DAILY` = '$RAIN_24HOURS_ACTUAL' AND `SEASONALLY_SYNOP` = '$RTRTRTRT') LIMIT 1";
if (mysqli_query($conn, $sql_rain_2)) {
$counter++;
}
$array = array("rain1"=>$counter, "rain2"=>"yogi");
echo json_encode($array);
mysql table:
CREATE TABLE `only_rainfall_2020` (
`SERIAL` int(11) NOT NULL,
`SUB_DIVISION_NUMBER` varchar(2) NOT NULL,
`SUB_DIVISION_NAME` varchar(20) NOT NULL,
`INDEX_NUMBER` varchar(5) NOT NULL,
`STATION_NAME` varchar(30) NOT NULL,
`YEAR` varchar(4) NOT NULL,
`MONTH` varchar(2) NOT NULL,
`DATE` varchar(2) NOT NULL,
`Ir` varchar(2) NOT NULL,
`DAILY` varchar(7) NOT NULL,
`MONTHLY` varchar(7) NOT NULL,
`SEASONALLY_SYNOP` varchar(7) NOT NULL,
`SEASONALLY_CALCULATE` varchar(7) NOT NULL,
`ANNUALLY` varchar(7) NOT NULL,
`COMMENT` varchar(50) NOT NULL,
`MANUALLY_EDIT_VALUE` varchar(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `only_rainfall_2020`
ADD PRIMARY KEY (`SERIAL`);
ALTER TABLE `only_rainfall_2020`
MODIFY `SERIAL` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
Please point out my mistake.
After many attempts i could not find my mistake.
let me clear it again:
I am trying to insert data for 8 columns into a table which has total 16 columns. In my table, one column is for serial number which is auto incremental, seven are blank columns and eight are the columns in which i am inserting data. I am leaving seven blank column for future work with no default values. the condition for inserting data for these eight column: any row should not exist with same data for these eight columns which i am going to insert. when i give different values for these eight columns than query is successful and data inserted but when i put same values for any two or more columns than query does not execute.
this is successful:
$INDEX_NUMBER = "43385";
$STATION_NAME = "DELHI";
$YEAR = "2020";
$MONTH = "12";
$DATE = "18";
$Ir = "3";
$RAIN_24HOURS_ACTUAL = "NA";
$RTRTRTRT = "20";
But when i put any two values same the query does not execute.
Failed with error: (#1060 - Duplicate column name 'NA')
$INDEX_NUMBER = "43385";
$STATION_NAME = "NA";
$YEAR = "2020";
$MONTH = "12";
$DATE = "18";
$Ir = "3";
$RAIN_24HOURS_ACTUAL = "NA";
$RTRTRTRT = "NA";
And yes there are warnings for like:
Warning: #1364 Field 'SUB_DIVISION_NUMBER' doesn't have a default value
But i will add values in these columns later.
There are over 200 users loggedin. Each user insert/update 1000 records in child table car_prices per 15 minutes which is related to parent table cars.
CREATE TABLE `cars` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
CREATE TABLE `car_prices` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`car_id` bigint(20) unsigned NOT NULL,
`price` decimal(8,2) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `car_prices_car_id_foreign` (`car_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
Every 15 minutes users execute this query (As an example):
INSERT INTO `car_prices` VALUES(NULL, 1, 3000, NOW(), NOW())
INSERT INTO `car_prices` VALUES(NULL, 2, 7000, NOW(), NOW())
INSERT INTO `car_prices` VALUES(NULL, 3, 5000, NOW(), NOW())
// ...and many other inserts approximately 1000
OR
UPDATE `car_prices` SET `price` = 4000 WHERE `id` = 1;
UPDATE `car_prices` SET `price` = 8000 WHERE `id` = 2;
UPDATE `car_prices` SET `price` = 6000 WHERE `id` = 3;
// ...and many other updates approximately 1000
How can I overcome this issue? There are lots of data and it takes long time to update/insert. Should I do something special that MySQL might have like some features? Or the pattern might be wrong? Or I should use some features that Laravel might have?
You an performe this task in a more efficient way using chunks
See this example i'm using for daily cron job that synchronize my table products
DB::beginTransaction();
try {
$response = json_decode(file_get_contents('API_URL_GOES_HERE'), true);
if(!empty($response['products'])) {
$tempArr = [];
foreach ($response['products'] as $product) {
$tempArr[] = [
'name' => $product['name'],
'price' => $product['price'],
'category_id' => $product['category_id'],
];
}
Product::truncate();
$insertData = collect($tempArr);
$chunks = $insertData->chunk(500);
foreach ($chunks as $chunk) {
Product::insert($chunk->toArray());
}
DB::commit();
dd($countProducts . ' Products imported successfully.');
} else {
dd('No products to import were found.');
}
} catch(\Exception $e) {
DB::rollback();
$this->info('');
dump('Import failed : ' . $e->getMessage());
dd('DB rolled back.');
}
This is the table layout:
CREATE TABLE camera
(
entity_id VARCHAR(50) PRIMARY KEY NOT NULL,
area_type INT(11) NOT NULL,
type INT(11),
`from` INT(11),
`to` INT(11),
severity INT(11) NOT NULL,
description VARCHAR(255),
additional_information VARCHAR(255),
location POINT NOT NULL,
reported_at DATETIME NOT NULL,
road_id INT(11) NOT NULL,
ugc TINYINT(1) COMMENT 'user generated content',
event INT(11),
advice VARCHAR(255),
updated_at DATETIME NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);
CREATE UNIQUE INDEX camera_from_to_unique ON camera (`from`, `to`);
And this is the query:
INSERT INTO `camera`
(
`entity_id`,
`area_type`,
`type`,
`from`,
`to`,
`severity`,
`description`,
`additional_information`,
`location`,
`reported_at`,
`road_id`,
`ugc`,
`event`,
`advice`
) VALUES (
:id_28,
:area_type_28,
:type_28,
:from_28,
:to_28,
:severity_28,
:description_28,
:additional_information_28,
POINT(:position_x_28, :position_y_28),
:reported_at_28,
:road_id_28,
:ugc_28,
:event_28,
:advice_28
) ON DUPLICATE KEY UPDATE
`entity_id` = :id_28,
`area_type` = :area_type_28,
`type` = :type_28,
`from` = :from_28,
`to` = :to_28,
`severity` = :severity_28,
`description` = :advice_28,
`additional_information` = :description_28,
`location` = POINT(:position_x_28, :position_y_28),
`reported_at` = :reported_at_28,
`road_id` = :road_id_28,
`ugc` = :ugc_28,
`event` = :event_28,
`advice` = :advice_28
And these are the binded parameters:
array (
'id_28' => 'NLSIT0020843410',
'area_type_28' => 1,
'type_28' => 46,
'from_28' => 7775,
'to_28' => 683756,
'severity_28' => 80,
'description_28' => '',
'additional_information_28' => 'Tussen knp. Hattemerbroek en Zwolle-Noord',
'position_x_28' => 6.032483,
'position_y_28' => 52.490729000000002,
'reported_at_28' => '2017-01-06 16:43:00',
'road_id_28' => 621453,
'ugc_28' => 0,
'event_28' => 1072,
'advice_28' => '',
)
I thought that because my from and to field are both in the same unique index in my table, the ON DUPLICATE KEY UPDATE would be triggered, but apparently that is not the case.
Could someone please explain why my ON DUPLICATE KEY UPDATE is not triggered so the data gets updated instead of this mysql error?
The duplicate key update part of the insert is being activated. However the attempt to update the row instead of inserting is failing. Because of this.
) ON DUPLICATE KEY UPDATE
`entity_id` = :id_28,
`area_type` = :area_type_28,
`type` = :type_28,
`from` = :from_28, /* this one */
`to` = :to_28, /* and this one */
YOu are trying to force mysql to have the same values for the from and to columns that triggered the duplicate. You need to remove those two columns from the ON DUPLICATE KEY clause. So we have
ON DUPLICATE KEY UPDATE
`entity_id` = :id_28,
`area_type` = :area_type_28,
`type` = :type_28,
`severity` = :severity_28,
`description` = :advice_28,
`additional_information` = :description_28,
`location` = POINT(:position_x_28, :position_y_28),
`reported_at` = :reported_at_28,
`road_id` = :road_id_28,
`ugc` = :ugc_28,
`event` = :event_28,
`advice` = :advice_28
I have 2 rows which looks like this.
This is the create statement of the table.
CREATE TABLE `currency` (
`ID` int(10) unsigned NOT NULL,
`Name` varchar(100) NOT NULL,
`Abbreviation` varchar(10) NOT NULL,
`symbol` varchar(5) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE = InnoDB DEFAULT CHARSET = latin1;
And all I want to do is insert symbols for them, but its not working.
I tried doing it this way.
insert into currency (id, symbol ) values (1,'€') ;
insert into currency (id, symbol ) values (2,'$') ;
Use UPDATE with a WHERE condition.
UPDATE currency
SET symbol = '€'
WHERE ID = 1;
UPDATE currency
SET symbol = '$'
WHERE ID = 2;
You need to insert all the columns:
insert into currency(id, name, description, symbol )
select 1, 'EUR', 'Euro', '€' union all
select 2, 'USD', 'United States Dollar', '$';
You have columns that are declared NOT NULL with no default values. These need to be assigned a value.
I have my databse: public
I have my table: info
in row files of player Maria i have this:
['python22.dll', ''], ['python27.dll', ''], ['channel.inf', ''], ['devil.dll', ''],['is_hack.exe', '']
The first 4 is normal so I don't want to see them in the list .. i just want to catch the "is_hack.exe"
My mysql query to get all ( including my normal files) is:
query("SELECT files FROM public.info WHERE player = 'Maria' ORDER BY actual_time DESC LIMIT 0,1;")
I need to see all the names that are not mine. Like:
FILE_FROM_OUTSIDE1 = is_hack.exe
FILE_FROM_OUTSIDE2 = stackoverflow.dll
If you know about LUA, i can get the entire query results to LUA then begin to parse.. but how?
EDIT:
This is my table:
CREATE TABLE `info` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`player` varchar(12) DEFAULT NULL,
`type_check` varchar(10) DEFAULT NULL,
`normal` varchar(20) DEFAULT NULL,
`actual` int(3) DEFAULT NULL,
`actual_time` varchar(20) DEFAULT NULL,
`files` varchar(3000) DEFAULT NULL,
PRIMARY KEY (`id`)
In "files" i have all this:
['python22.dll', ''], ['python27.dll', ''], ['channel.inf', ''], ['devil.dll', ''],['is_hack.exe', '']
I just want to select the is_hack.exe .. like: print is_hack.exe
I'm not sure if this is what you want. But i think this might help:
Replace the filename_field with your col name.
query("SELECT files FROM public.info WHERE player = 'Maria' AND filename_field = 'is_hack.exe' ORDER BY actual_time DESC LIMIT 0,1;")
UPDATE
I don't know if this I'm right but you should not save data like this. You can create a files table and specify which user own each row. Like:
CREATE TABLE `playerfiles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`player` int(11) DEFAULT NULL,
`filename` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
);
Then you can retrieve data with JOIN.
SELECT * FROM `info`
JOIN `playerfiles` ON `playerfiles.player` = `info.id`
WHERE `info.player` = 'Maria' and `playerfiles.filename` = 'THE NAME'