I have written a before insert trigger that will not insert the data in the tables if the 'ratings' > 5 and inserts it on a table 'rating_check' with a message .For 'ratings' <= 5 the data is inserted on all the tables.But its not working nor am I getting any errors. Here is the trigger code-
DELIMITER $$
CREATE
TRIGGER `mytrigger` BEFORE INSERT
ON `review`
FOR EACH ROW BEGIN
IF NEW.ratings > 5 THEN
SET #trigger_desc = 'You cannot rate greater than 5!';
INSERT INTO `rating_check` (`trig_id`, `trigger_desc`) VALUES ('', #trigger_desc);
ELSE
INSERT INTO `developer_details` (`developer_id`,`developer_name`,`developer_email`) VALUES ('$appDevId','$appDevName','$appDevEmail');
INSERT INTO `apps` (`app_id`,`app_name`,`app_icon`,`dev_id`) VALUES (LAST_INSERT_ID(),'$appName','$appIcon','$appDevId');
INSERT INTO `app_details` (`app_id`,`description`,`version`,`release_date`,`size`) VALUES (LAST_INSERT_ID(),'$appDesc','$appVersion','$appDate','$appSize');
INSERT INTO `app_specs` (`app_id`,`downloads`,`category_name`) VALUES (LAST_INSERT_ID(),'$appDownloads','$appCategory');
INSERT INTO `review` (`app_id`,`ratings`) VALUES (LAST_INSERT_ID(),'$appRatings');
END IF;
END$$
'trig_id' is auto incremented here.Please help me with this!
Related
I have a trigger that I cannot get to work properly.
I have at table called _WorkOrderDump where data is input via a form. There is a trigger on this table that inserts some of the data into a table called _RefTable. The second part of this trigger is to insert some of the data into another table called __XClient.
I cannot get the second insert into the __XClient table to work, it does not insert any data into this table. The first part of the trigger inserting into Ref table is however working perfectly.
What is wrong with my query?
Thanks for any help provided!
CREATE TRIGGER WorkOrderTrigger
AFTER INSERT on _WorkOrderDump
BEGIN
Declare EntryDate DATETIME;
Declare RefIDDump INT;
SET EntryDate = CURDATE();
Set RefIDDump = LAST_INSERT_ID();
CASE WHEN (EntryDate) > 0
THEN INSERT INTO `_RefTable`( `WOID`, `ClientID`, `ProjectScope`, `ProjectID`, `ClientRef`, `SiteID`, `SiteName`, `RegionID`, `SiteAddressLine`, `SiteAddressSuburb`, `SiteAddressState`, `SiteAddressPostcode`, `SiteAddressCountry`, `SiteContactName`, `SiteContactMobile`, `SiteContactPhone`, `SiteContactEmail`, `RefEntryDate`, `CreatedBY`)
VALUES
( new.WOID, new.ClientID, new.ProjectScope, new.ProjectID, new.ClientRef, new.SiteID, new.SiteName, new.RegionID, new.SiteAddressLine, new.SiteAddressSuburb, new.SiteAddressState, new.SiteAddressPostcode, new.SiteAddressCountry, new.SiteContactName, new.SiteContactMobile, new.SiteContactPhone, new.SiteContactEmail, EntryDate, new.CreatedBY);
WHEN (new.ClientID) = 1
THEN INSERT INTO `__XClient`( `RefID`, `ITContactName`, `ITContactPhone`, `ITContactEmail`, `XScope32`, `XScope43`, `XScopeMediaPlayer`, `XScopeInstallDate`, `XScopeInstallTime`, `XScopeComments`)
VALUES
( RefIDDump, new.Dump_1, new.Dump_3, new.Dump_2, new.Dump_4, new.Dump_5, new.Dump_6, new.Dump_7, new.Dump_8, new.Dump_9);
END CASE;
END
My trigger is not working at all.
DELIMITER $$
CREATE TRIGGER leave_credit_nt
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
INSERT INTO nonteaching_leavecredit (IdNum, Date_Hired, Emp_Stat, Date_Leave_Ac, Vac_Leave, Sick_Leave)
VALUES (new.IdNum, new.Date_Hired, new.Emp_Stat, new.Date_Hired + INTERVAL 1 YEAR, 0, 0)
WHERE employees.Emp_Type = 'NON-TEACHING';
END $$
DELIMITER
I want that the trigger will insert values into my second table only those with employees.emp_type = 'NON-TEACHING'. Can someone help me get this trigger working?
emp_type is a column in my table employees.
Your INSERT query is wrong. MySQL INSERT Syntax does not support the WHERE clause so your query as it stands will fail.
You cant use WHERE condition with INSERT query. If you are using WHERE condition, it means you already have that row in the table. So , you should use UPDATE query instead of INSERT.
You can add conditional logic to your trigger with:
if new.Emp_Type = 'NON-TEACHING' then
INSERT INTO nonteaching_leavecredit (IdNum, Date_Hired, Emp_Stat, Date_Leave_Ac, Vac_Leave, Sick_Leave)
VALUES (new.IdNum, new.Date_Hired, new.Emp_Stat, new.Date_Hired + INTERVAL 1 YEAR, 0, 0);
end if;
I have an update.php form which is updating existing data. My problem is when I want to submit and part of my form is dynamic so they can add a new row to mysql while they are updating, so I keep getting duplicate dynamic rows in MySQL which are submitted before.
$i = 0;
while($i<count($fromhours)){
$fromhours[$i]= $fromhours[$i];
$fromminutes[$i]= $fromminutes[$i];
$tohours[$i]= $tohours[$i];
$tominutes[$i]= $tominutes[$i];
$resulthours[$i]= $resulthours[$i];
$resultminutes[$i]= $resultminutes[$i];
$hrscode[$i]= $hrscode[$i];
$gremark[$i]= $gremark[$i];
$query = "INSERT INTO `generalreport` (
`ID`, `date`, `fromhours`, `fromminutes`, `tohours`, `tominutes`, `resulthours`, `resultminutes`, `code`, `remark`
) VALUES (
'".$id."',
'".$date."',
'".$fromhours[$i]."',
'".$fromminutes[$i]."',
'".$tohours[$i]."',
'".$tominutes[$i]."',
'".$resulthours[$i]."',
'".$resultminutes[$i]."',
'".$hrscode[$i]."',
'".$gremark[$i]."'
);";
mysql_query($query);
$i++;
};
How can I use this code for update and just insert new data in MySQL and old data won't be duplicated.
i think you have to index your table in mysql such that if any new data enters that have any similar date and entry the mysql will automatically pop out a duplicate entry error
Use
INSERT INTO `generalreport` (
`ID`, `date`, `fromhours`, `fromminutes`, `tohours`, `tominutes`, `resulthours`, `resultminutes`, `code`, `remark`
) VALUES (...),(...),(...)
I have this PHP function below that Creates a new Project Task MySQL database record if one with the same ID does not exist already.
If one does already exist with the same ID, then it instead UPDATES the MySQL record.
This code has a lot of time invested into it as it is very important that the Task record's date_modified field is to ONLY be updated in the event that any of these 5 fields have changed to a new value!:
- name
- description
- status
- type
- priority
If all of these fields have the same value as the previous value when making an UPDATE, for example if the sort_order value is changed then it would NOT update the date_modified field!
It works great after lots of work crafting it to work just right. I mention all this as it is important to not break this functionality!
Now this question is because this function can CREATE and UPDATE Task records in MySQL.
I now have the need to know when each of these events happens.
If a new Task record is CREATED then I need to know that a new record was created.
If the Task record is simply UPDATED then I need to know that the record had already existed and was simply Updated.
Is there anyway to determine which of the 2 events happened with what I have?
private function _addOrUpdateTaskRecord($taskId, $projectId, $created_by_user_id, $modified_user_id, $name, $description, $status, $priority, $type, $date_entered, $date_modified, $date_started, $date_completed, $date_due, $milestone_id, $assigned_user_id, $sort_order, $heading){
$sql = "
INSERT INTO
$this->tasksDbTableName(task_id, project_id, created_by_user_id, modified_user_id, name, description, status, priority, type, date_entered, date_modified, date_started, date_completed, date_due, milestone_id, assigned_user_id, sort_order, heading)
VALUES
('$taskId', '$projectId', '$created_by_user_id', '$modified_user_id', '$name', '$description', '$status', '$priority', '$type', UTC_TIMESTAMP(), UTC_TIMESTAMP(), '$date_started', '$date_completed', '$date_due', '$milestone_id', '$assigned_user_id', '$sort_order', '$heading')
ON DUPLICATE KEY UPDATE
date_modified = (CASE
WHEN name <> values(name)
OR description <> values(description)
OR status <> values(status)
OR type <> values(type)
OR priority <> values(priority)
THEN UTC_TIMESTAMP()
ELSE date_modified
END),
modified_user_id='$modified_user_id',
name='$name',
description='$description',
status='$status',
priority='$priority',
type='$type',
date_started='$date_started',
date_completed='$date_completed',
date_due='$date_due',
milestone_id='$milestone_id',
assigned_user_id='$assigned_user_id',
sort_order='$sort_order',
heading='$heading'";
$insertOrUpdateTasks = $this->db->query($sql);
return $insertOrUpdateTasks;
}
Update
I am adding my MySQL Triggers code here for others to see as it might help someone someday with similar issue, or myself so I don't end up posting a question I have a solution to again!
Trigger to create an Event record when a Task is CREATED
DROP TRIGGER IF EXISTS project_task_new_event;
CREATE TRIGGER `project_task_new_event` AFTER INSERT ON `apoll_web_projects_tasks`
FOR EACH ROW
INSERT INTO apoll_web_projects_events (event_type, project_id, task_id, created_by_user_id, description, date_created) VALUES ('6', NEW.project_id, NEW.task_id, NEW.modified_user_id, NEW.name, UTC_TIMESTAMP());
Trigger to create an Event record when a Task is UPDATED
DROP TRIGGER IF EXISTS project_task_update_event;
DELIMITER $$
CREATE TRIGGER `project_task_update_event` AFTER UPDATE ON `apoll_web_projects_tasks` FOR EACH ROW
BEGIN
IF NOT (NEW.date_modified <=> OLD.date_modified)
THEN
INSERT INTO apoll_web_projects_events (event_type, project_id, task_id, created_by_user_id, description, date_created) VALUES ('7', NEW.project_id, NEW.task_id, NEW.modified_user_id, NEW.name, UTC_TIMESTAMP());
END IF;
END $$
DELIMITER ;
You can use affected_rows from your db class. (I am uncertain what class that is exactly). From the manual:
With ON DUPLICATE KEY UPDATE, the
affected-rows value per row is 1 if
the row is inserted as a new row and 2
if an existing row is updated.
Your code is insecure. You have SQL Injection problem.
To know if the record was created or updated, simple compare if create_date != update_date
When you insert data, set create_date and update_date to the same value. In "ON DUPLICATE" section update "update_date" field.
Another solution is to use triggers, something like this:
DELIMITER $$
CREATE TRIGGER `update_trigger` BEFORE UPDATE ON `tasks_table` FOR EACH ROW
BEGIN
/* Add any fields you want to compare here */
IF !(OLD.name <=> NEW.name OR OLD.description <=> NEW.description OR OLD.description <=> NEW.description OR OLD.status <=> NEW.status OR OLD.type <=> NEW.type OR OLD.priority <=> NEW.priority) THEN
NEW.date_modified = NOW()
END IF;
END;$$
DELIMITER ;
I have been working on my first webapp and I hit a bit of a wall. I have a table in my db set up as follows:
student_id(student_id, first_name, last_name, bdate, etc...)
I also have several tables for classes set up similarly to this
class_table(id, student_id, quiz_1, quiz_2, etc....)
student_id is how I would like to track everything, from my understanding, this would be a primary key that would become a foreign key on the class tables.
What I would like to do is create an entry for the student on each class table when the php script I am writing creates a new student. This is what my query looks like:
$query = "INSERT INTO student_id(0, '$first_name', '$last_name'.... etc);".
"INSERT INTO class_table(0, LAST_INSERT_ID(), '$quiz_1', $quiz_2'...etc)";
Is this the right way to do this? I keep getting an error from my mysqli_query... so I am guessing this is where the problem is. How would I achieve this?
mysqli_query() (and mysql_query()) will only execute a single query. You would need to perform two calls to mysqli_query() or use mysqli_multi_query(), which will execute multiple queries in one call.
You're missing the VALUES clause:
$query = "INSERT INTO student_id VALUES (0, '$first_name', '$last_name'.... etc);".
"INSERT INTO class_table VALUES (0, LAST_INSERT_ID(), '$quiz_1', '$quiz_2'...etc)";
and you will need to use the mysqli_multi_query() function. See the example at http://www.php.net/manual/en/mysqli.multi-query.php#106126:
if ($mysqli->multi_query($query)) {
$i = 0;
do {
$i++;
} while ($mysqli->next_result());
}
if ($mysqli->errno) {
echo "Batch execution prematurely ended on statement $i.\n";
var_dump($statements[$i], $mysqli->error);
}
You could also create a stored procedure, and call it with all the needed parameters:
CALL insert_student('$first_name', '$last_name', '$quiz_1', $quiz_2', ... etc);
Here's an example:
CREATE PROCEDURE add_student(
IN v_first_name VARCHAR(50),
IN v_last_name VARCHAR(50),
IN v_quiz_1 VARCHAR(255),
IN v_quiz_2 VARCHAR(255)
)
DETERMINISTIC
MODIFIES SQL DATA
proc: BEGIN
START TRANSACTION;
INSERT INTO student_id VALUES (0, v_first_name, v_last_name);
IF ROW_COUNT() <= 0 THEN
ROLLBACK;
SELECT 0 AS result;
LEAVE proc;
END IF;
INSERT INTO class_table VALUES (0, LAST_INSERT_ID(), v_quiz_1, v_quiz_2);
COMMIT;
SELECT 1 AS result;
END;