I have a mysql database and a form that inserts stuff into it. I would like to prevent adding a row if there was a row where the Status column equaled "New" or "Redeploy" and is the same $tag (which is what they are entering in to the area of the form)
Basically i want to prevent people from adding a entry if that $tag already was there with a status of "new" or "redeploy". kind of hard to explain
here is my current query any assistance or ideas would be appreciated.
mysql_query ("INSERT INTO Assets (`Badge`, `First Name`, `Last Name`, `Service Tag`, `Asset Tag`, `Status`, `Employee Status`, `Username`, `deleted`)
VALUES('$badge', '$first', '$last', '$tag', '$asset', '$status', '$estatus', '$user', '$deleted') ") or die (mysql_error());
The best way to do this would be to use a check constraint on the table. That way your condition will always be enforced, no matter how the insert/update is made.
http://www.w3schools.com/sql/sql_check.asp
For something like this you'd probably want to create a function as well. So your function would look like:
CREATE FUNCTION CheckAssetRows(#Tag VARCHAR(50))
RETURNS INT
AS
BEGIN
DECLARE #NumInvalidRows INT
SELECT #NumInvalidRows = COUNT(*)
FROM Asset
WHERE [Service Tag]=#Tag
AND [Status] in ('New', 'Redeploy')
RETURN #NumInvalidRows
END
GO
And your check is easy:
ALTER TABLE ASSET
ADD CONSTRAINT chk_Tag CHECK(CheckAssetRows([Service Tag]) = 0)
Related
I need to log the updated columns into an existing empty column in which it should appear "Updated" or "Not Updated". I am running this query in MS Access.
Below find an example for my update query (which works) and code for the trigger (not sure i need one, or if i'm using it correctly)
update my_table
set col_i_need_to_set = 'value'
WHERE another_col like 'some_text'
and another_col2 LIKE 'some_other_text'
and another_col3 LIKE 'text'
CREATE OR REPLACE TRIGGER historyKeeper
AFTER UPDATE my_table
FOR EACH ROW
BEGIN
IF( UPDATING( 'col_i_need_to_set' ) )
THEN
INSERT INTO my_table( column_in_which_i_want_to_insert, column_value )
VALUES( 'Updated');
else
INSERT INTO my_table( column_in_which_i_want_to_insert, column_value )
VALUES( 'Not updated');
END IF;
END;
Thank you
actually, found the solution. after set col_i_need_to_set = 'value' I just need to add , column_in_which_i_want_to_insert = 'UPDATED' Maybe this will help someone
What I'm trying to do is INSERT subscribers in my database, but IF EXISTS it should UPDATE the row, ELSE INSERT INTO a new row.
Ofcourse I connect to the database first and GET the $name, $email and $birthday from the url string.
$con=mysqli_connect("localhost","---","---","---");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['name'];
$email=$_GET['email'];
$birthday=$_GET['birthday'];
This works, but just adds the new row;
mysqli_query($con,"INSERT INTO subs (subs_name, subs_email, subs_birthday)
VALUES ('$name', '$email', '$birthday')");
mysqli_close($con);
Here's what I tried;
mysqli_query($con,"INSERT INTO subs (subs_name, subs_email, subs_birthday)
VALUES '$name', '$email', '$birthday'
ON DUPLICATE KEY UPDATE subs_name = VALUES($name), subs_birthday = VALUES($birthday)");
mysqli_close($con);
and
mysqli_query($con,"IF EXISTS (SELECT * FROM subs WHERE subs_email='$email')
UPDATE subs SET subs_name='$name', subs_birthday='$birthday' WHERE subs_email='$email'
ELSE
INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES ('$name', '$email', '$birthday')");
mysqli_close($con);
and
mysqli_query($con,"IF NOT EXISTS(SELECT * FROM subs WHERE subs_email='$email')
Begin
INSERT INTO subs (subs_name, subs_email, subs_birthday)
VALUES ('$name', '$email', '$birthday')
End");
mysqli_close($con);
But none of them work, what am I doing wrong?
Any help is greatly appreciated!
Create a UNIQUE constraint on your subs_email column, if one does not already exist:
ALTER TABLE subs ADD UNIQUE (subs_email)
Use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO subs
(subs_name, subs_email, subs_birthday)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
subs_name = VALUES(subs_name),
subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to
refer to column values from the INSERT portion of the INSERT ... ON
DUPLICATE KEY UPDATE - dev.mysql.com
Note that I have used parameter placeholders in the place of string literals, as one really should be using parameterised statements to defend against SQL injection attacks.
Try this:
INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';
INSERT ... ON DUPLICATE KEY UPDATE
is a good solution as long as you don't mind AUTO_INCREMENT counters unnecessarily incrementing every time you end up doing an UPDATE. Since it tries to INSERT first, I noticed auto counters do increment.
Another solution I like that may be less performant, but easy to maintain is:
IF EXISTS(SELECT 1 FROM table WHERE column = value...) THEN
UPDATE table
SET column = value ...
WHERE other_column = other_value ...;
ELSE
INSERT INTO table
(column1, column2, ...)
VALUES
(value1, value2, ...);
END IF;
recently i've been searching for a solution to the following situation:
I have mysql table with structure:
CREATE TABLE IF NOT EXISTS `battles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`active` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`begindate` datetime NOT NULL,
`enddate` datetime NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Every battle has begindate and enddate. Begindate is datetime of insert and usually enddate is three days later.
I would like to create a mysql event that stops the battle (sets active = 0) at the battle enddate. And i would like this event to be created on insert trigger in the battles table.
There is an related issue with very few answers (here).
They advise:
You should be able to do it using a trigger and the event scheduler:
create a trigger on the table that is fired on every update / insert
this trigger creates a scheduled event that occurs at the datetime of the row and updates >your second table
I've tried to create such a query but with no success.
DELIMITER |
DROP TRIGGER IF EXISTS battle_create_end|
CREATE TRIGGER battle_create_end AFTER INSERT ON battles
FOR EACH ROW BEGIN
CREATE EVENT IF NOT EXISTS CONCAT('battle_end_',NEW.id)
ON SCHEDULE AT NEW.enddate
DO
UPDATE battles SET battles.active = 0 WHERE battles.id = NEW.id;
END|
DELIMITER ;
The error i get is
1576 - Recursion of EVENT DDL statements is forbidden when body is present
I've tried with different delimiters in the for each row structure with no success either.
If someone can help, please advise.
BR,
Ilko
Sorry brother but from what I have been reading what you are proposing is not possible. I don't think you can create an event with a trigger. Which is a bummer because it would be useful for me as well.
It would however be easier to create the event when the row for each battle is created. Hear is an example of some code I found from a guy explaining how events work.
<?php
// establish database connection and filter incoming data
// ...
// insert blog post with pending status, get id assigned to post
$query = "INSERT INTO blog_posts (id, title, post_text, status)
VALUES (NULL, :title, :postText, 'pending')";
$stm = $db->prepare($query);
$stm->execute(array(":title" => $title, ":postText" => $text));
$id = $db->lastInsertId();
// is this a future post?
if (isset($_POST["schedule"], $_POST["time"])) {
$scheduleDate = strtotime($_POST["time"]);
$query = "CREATE EVENT publish_:id
ON SCHEDULE AT FROM_UNIXTIME(:scheduleDate)
DO
BEGIN
UPDATE blog_posts SET status = 'published' WHERE id = :id;
END";
$stm = $db->prepare($query);
$stm->execute(array(":id" => $id, ":scheduleDate" => $scheduleDate));
}
// this is not a future post, publish now
else {
$query = "UPDATE blog_posts SET status = 'published' WHERE id = :id";
$stm = $db->prepare($query);
$stm->execute(array(":id" => $id));
}
So basically create the event when you add a battle to the table.
The thing that i want to do is to check if there is a same row and if not to insert a new row to the table.
In that case, how can i use if not exists ?
INSERT INTO `facebook` (`ID`,`fb_id`,`label_id`,`page_ids`,`token`) VALUES (NULL,'". $session['id'] ."','$id','','". $access_token ."')
For example, in that query, i want to check if there is a row with the same label_id record and if not, execute that query.
any help ?
thanks
You can use the INSERT IGNORE INTO ... syntax. When using this, duplicate key errors are treated as warnings and the statement will return without having inserted the affected row.
INSERT INTO `facebook` (`ID`,`fb_id`,`label_id`,`page_ids`,`token`)
SELECT NULL, '". $session['id'] ."', '$id', '', '". $access_token ."'
FROM DUAL
WHERE NOT EXISTS (SELECT 'x' FROM facebook WHERE label_id = '$id')
I think FROM DUAL is optional, but I'm an Oracle guy. :)
User Insert Into to ignore duplicates:
INSERT IGNORE INTO `facebook`
SET `ID` = null,
`fb_id` = '". $session['id'] ."',
`label_id` = '$id',
`page_ids`='',
`token`='". $access_token ."';
I do have a table with more than 100000 data elements, but there are almost 350 blank rows within. How do I delete this blank rows using phpmyadmin? Manually deleting is a tedious task.
The general answer is:
DELETE FROM table_name WHERE some_column = '';
or
DELETE FROM table_name WHERE some_column IS NULL;
See: http://dev.mysql.com/doc/refman/5.0/en/delete.html
More info when you post your tables!~
Also, be sure to do:
SELECT * FROM table_name WHERE some_column = '';
before you delete, so you can see which rows you are deleting! I think in phpMyAdmin you can even just do the select and then "select all" and delete, but I'm not sure. This would be pretty fast, and very safe.
I am doing the mysql operation in command prompt in windows. And the basic queries:
delete * from table_name where column=''
and
delete * from table_name where column='NULL'
doesn't work. I don't know whether it works in phpmyadmin sqlcommand builder. Anyway:
delete * from table_name where column is NULL
works fine.
I have a PHP script that automatically removes empty rows based on column data types.
That allows me to define "emptiness" differently for different column types.
e.g.
table
first_name (varchar) | last_name (varchar) | some_qty ( int ) | other_qty (decimal)
DELETE FROM `table` WHERE
(`first_name` IS NULL OR `first_name` = '')
AND
(`last_name` IS NULL OR `last_name` = '')
AND
(`some_qty` IS NULL OR `some_qty` = 0)
AND
(`other_qty` IS NULL OR `other_qty` = 0)
Since "0" values are meaningless in my system, I count them as empty. But I found out that if you do (first_name = 0) then you will always get true, because strings always == 0 in MySQL. So I tailor the definition of "empty" to the data type.
This procedure will delete any row for all columns that are null ignoring the primary column that may be set as an ID. I hope it helps you.
DELIMITER //
CREATE PROCEDURE DeleteRowsAllColNull(IN tbl VARCHAR(64))
BEGIN
SET #tbl = tbl;
SET SESSION group_concat_max_len = 1000000;
SELECT CONCAT('DELETE FROM `',#tbl,'` WHERE ',(REPLACE(group_concat(concat('`',COLUMN_NAME, '` is NULL')),',',' AND ')),';') FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = #tbl AND COLUMN_KEY NOT LIKE 'PRI' into #delete_all;
PREPARE delete_all FROM #delete_all;
EXECUTE delete_all;
DEALLOCATE PREPARE delete_all;
END //
DELIMITER ;
Execute the procedure like this.
CALL DeleteRowsAllColNull('your table');
I know this has already been answered and has got a tick, but I wrote a small function for doing this, and thought it might be useful to other people.
I call my function with an array so that I can use the same function for different tables.
$tableArray=array("Address", "Email", "Phone"); //This is the column names
$this->deleteBlankLines("tableName",$tableArray);
and here is the function which takes the array and builds the delete string
private function deleteBlankLines($tablename,$columnArray){
$Where="";
foreach($columnArray as $line):
$Where.="(`".$line."`=''||`".$line."` IS NULL) && ";
endforeach;
$Where = rtrim($Where, '&& ');
$query="DELETE FROM `{$tablename}` WHERE ".$Where;
$stmt = $this->db->prepare($query);
$stmt->execute();
}
You can use this function for multiple tables. You just need to send in a different table name and array and it will work.
My function will check for a whole row of empty columns or NULL columns at the same time. If you don't need it to check for NULL then you can remove that part.