MysQL SELECT statement if empty [duplicate] - php

This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 5 years ago.
I am struggling a bit with something that I think should be simple to solve.
I first check the database to see if it exists. I would like it to insert the date if it does not exist but I am not sure how to structure the IF statement part. Many thanks
$date='2017-05-13';
$select_date = mysqli_query($link, "SELECT * from `marker` WHERE `date`='$date' ");
$insert_date = mysqli_query($link, "INSERT INTO `marker` (`date`,`value`) VALUES ('$date','1') ");

In general, for this type of operation, you want to use on duplicate key update. This starts with a unique index:
CREATE UNIQUE INDEX unq_marker_date ON marker(date);
Then the database guarantees only one row per date. You can then do the insert as:
INSERT INTO `marker` (`date`, `value`)
VALUES ('$date', '1')
ON DUPLICATE KEY UPDATE `date` = VALUES(`date`);
The ON DUPLICATE KEY part does nothing except prevent an error for a duplicate date.

Related

MySQL "IF NOT EXISTS" [duplicate]

This question already has answers here:
MySQL: Insert record if not exists in table [duplicate]
(16 answers)
Closed 5 years ago.
I am having error in SQL syntax but I don't see it.
$query = "IF NOT EXISTS ( SELECT id FROM Provider
WHERE name=('$filename') )
INSERT INTO Provider (Name) VALUES ('$filename')";
$query_result = mysqli_query($connect, $query);
The code
INSERT INTO Provider (Name) VALUES ('$filename')
worked normally if I use just that.
Also the code
SELECT id FROM Provider WHERE name=('$filename')
worked fine when I tested its value
When I added IF NOT EXISTS I have SQL syntax error but I can't see it!
Any ideas?
You cannot use NOT EXISTS in this context. Try the following query instead:
INSERT INTO Provider (Name)
SELECT filename
FROM (SELECT ('$filename') AS filename) AS t
WHERE NOT EXISTS (SELECT id
FROM Provider
WHERE name=('$filename')

MySQL CREATE TRIGGER using php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I have read some other posts like mine, but none of them solve my problem,
I have two tables, user and purchase, When a user signup, I want to add the same user_id to the purchase table as well. I try to right a php code for that like this:
$query = "CREATE TRIGGER `purchase_insert` AFTER INSERT ON `user` FOR EACH ROW BEGIN INSERT INTO purchase (user_id) VALUES (NEW.user_id)";
$result = mysqli_query($connection, $query);
if($result){echo "<br>TRIGGER Success!";} else {die("<br>Database query failed. " . mysqli_error($connection));}
this is the error I get:
Database query failed. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
I'm sorry if the question is repetitious.
It should be back tick not single quotes
CREATE TRIGGER `purchase_insert` AFTER INSERT ON `user` FOR EACH ROW BEGIN INSERT INTO purchase (user_id) VALUES (NEW.user_id)
UPDATE
Try this
DELIMITER$$
CREATE TRIGGER `purchase_insert`
AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
INSERT INTO purchase (user_id) VALUES (NEW.user_id);
END$$
DELIMITER ;

Insert and select in one row sql [duplicate]

This question already has answers here:
Can I use a subquery inside an INSERT statement?
(2 answers)
Closed 8 years ago.
I need to insert some values in the table.
I can do it easily using the query(from php):
mysql_query('INSERT INTO `TABLE1`(`user_id`,`value1`,`date`) VALUES("'.$user_id.'",".$value1.",".time().")');
But this time I do not have variable $user_id. I only have the username. So I need to do one more query to USERS dataase to get user_id from row where username is equal to my variable.
Is it possible not to do 2 queries? I meen INSERT and SELECT in one query?
P.S. I know that mysql_query function is depreciated. I used it here jusst for example.
Try nested subquery:
INSERT INTO `TABLE1`
(`user_id`,`value1`,`date`)
VALUES
(
(
SELECT
`user_id`
FROM
`user`
WHERE
`username` = 'your-user-name' // should be unique in order to work
),
'value1',
NOW()
);
The following query may be what you're looking for but it may be better to first get the user_id and then proceed the insert:
INSERT INTO TABLE1 (user_id, value1, date)
SELECT MAX(user_id) + 1 -- If the user_id is an numeric value...
,'user-name-here'
,NOW()
FROM TABLE1
With this query i'm getting the last user_id from the table and i increment it by 1 in order to insert the new user in the table.
Hope this will help you.

What faster "Insert ignore" or "Select and Insert" [duplicate]

This question already has answers here:
Which DB design is faster: a unique index and INSERT IGNORE, or using SELECT to find existing records?
(6 answers)
Closed 9 years ago.
mysql database.
Table have index on field "Code".
I need to insert to table new rows.
What works faster?
1)
simple index on field Code - for fast select
befor insert check rows : SELECT COUNT(*) FROM table WHERE Code = 'NewCode';
simple insert(if rows not found): Insert into table values ('NewCode')
2)
unique index on field Code - for insert
Insert IGNORE into table values ('NewCode')
For me more secure (and can be a backup of changes - better way) is the first, but I think that the action is similar.
Consult http://dev.mysql.com/doc/refman/5.5/en/insert.html for more detali
paladinux

mysql update if some values exists otherwise create a new entry [duplicate]

This question already has answers here:
MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?
(3 answers)
Closed 10 months ago.
I have a table rating with these fields rate_id, game_id, rating, ip. Let suppose that these fields has the following values 1,130,5,155.77.66.55
When a user try to vote for a game, I want with mysql to check if he has already vote for this game so mysql will check if ip and game_id already exists, if they exists then mysql will update the value of rating otherwise will create a new entry.
What is a efficient way to do this?
Create unique index that covers ip + game_id. After that you can use INSERT ... ON DUPLICATE KEY UPDATE statement.
So the total query will be something like
INSERT INTO rating (rate_id, game_id, rating, ip) VALUES (1,130,5,'155.77.66.55')
ON DUPLICATE KEY UPDATE rating = 5
MySQL allows an on duplicate key update syntax for INSERT. So if you set your key to be game_id, user_id (or whichever way you identify the user) then you can use INSERT...on DUPLICATE KEY UPDATE which will do just that:
http://dev.mysql.com/doc/refman/5.5/en/insert.html
You could also take a look at REPLACE INTO. Maybe not for this project but for future reference:
REPLACE works exactly like INSERT,
except that if an old row in the table
has the same value as a new row for a
PRIMARY KEY or a UNIQUE index, the old
row is deleted before the new row is
inserted
from: dev.mysql.com
// check to see if exist
$sql = "SELECT ip FROM rating WHERE ip=$ip && game_id={$game_id}";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(isset($row['ip'])){
mysql_query("UPDATE HERE");
}else{
mysql_query("INSERT HERE");
}

Categories