I am trying to CREATE TRIGGER on custom table in mySQL db with dbDelta() function in wordpress plugin I am building!
On plugin activation, tables are created and populated with default data. When execute this function:
function PDFsem_initial_trigger($ldd_tabela) {
global $wpdb;
$table_name = $wpdb->prefix.$ldd_tabela;
//it works!!!
$sql = "CREATE TRIGGER brisIspod BEFORE DELETE ON ".$table_name." FOR EACH ROW INSERT INTO wp_ldd_usluga (usluga_naziv,usluga_rbr,seminar_id) VALUES('NEW TRIGGERED DATA', 2, 2)";
/*
//dont work!!!
$sql = "CREATE TRIGGER brisIspod BEFORE DELETE ON wp_ldd_seminar FOR EACH ROW DELETE FROM wp_ldd_usluga WHERE wp_ldd_usluga.seminar_id = old.id_seminar;";
*/
dbDelta( $sql );
}
Function creates trigger on BEFORE DELETE ... INSERT INTO..., but wont create trigger on BEFORE DELETE ... DELETE... . If execute sql query in phpMysqlAdmin console directly trigger is created regularly.
I am not creating both triggers in same time so one is under comment. First trigger is just test sample.
Is it possible to add trigger I want with dbDelta() in wordpress mySql db?
Trigger in mySql can be created with :
$sql = "CREATE TRIGGER brisIspod BEFORE DELETE ON wp_ldd_seminar FOR EACH ROW DELETE FROM wp_ldd_usluga WHERE wp_ldd_usluga.seminar_id = old.id_seminar;";
$wpdb->query($sql);
Related
WordPress 5.3
I'm writing a plugin thif method removes the database table.
When I put a breakpoint in this function and execute the copied value of $sql, the table is been really removed. But this very code doesn't remove the table. Could you help me here?
public function deactivate(){
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$sql = "drop table if exists $this->table_name;";
dbDelta($sql);
}
Try this:
$sql = "drop table if exists ".$this->table_name.";";
or this:
$sql = "drop table if exists {$this->table_name};";
I have a crud system using Oracle DB to store the data. There are two tables (the main table and history). Users have to login to the system. I already created an update or delete trigger from main to the history table, and it works fine for both. Now I want to capture $_SESSION NAME and insert it into column ACTION_BY in table HISTORY when the user deletes any row. I have no idea how to do it. Can anyone help me.
proc_delete.php
<?
require 'inc_instance.php';
$id = $_POST["id"];
$user = $_SESSION['name'];
$db = Database::obtain(HDBUSER, HDBPASS, HDBNAME);
$db->connect();
$sql = "DELETE FROM CIM_TRACKING_MAIN WHERE id = '".$id."'";
$db->query($sql);
echo json_encode([$id]);
$db->close();
Can I directly insert session name into the history table when the user pushes the delete button?
This is how it looks:
Not sure is this the thing you want
$query = $db->query($sql);
if($query){ // return true if your delete query success
// Insert query into your History table here
$sql_02 = "INSERT INTO History(ACTION_BY) VALUES ('$user')";
if($db->query($sql_02)=== TRUE){
// do the action you want here, if no need then remove this if statement
}
}
But using this will cause major security vulnerability, try to use prepare statement next time
I need to create a new table with certain data from another table but update the original table with the ID of the newly inserted record from the new table. Like so:
NEW_TABLE
----------------
id
-- other data --
ORIGINAL_TABLE
----------------
id
new_table_id
-- other data --
However, the added records to new_table will be grouped to get rid of duplicates. So, it won't be a 1-to-1 insert. The query needs to update matching records, not just the copied record.
Can I do this in one query? I've tried doing a separate UPDATE on original_table but it's not working.
Any suggestions?
You are going to be doing 3 seperate queries as I see it.
$db = new PDO("...");
$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();
$results = $stmt->fetchAll();just iterate o
foreach ($results as $result) {
$stmt = "INSERT INTO new_table (...) VALUES (...)";
$stmt = $pdo->prepare($stmt);
$data = $stmt->execute();
$insert_id = $pdo->lastInsertId();
// Update first table
$stmt = "UPDATE table SET id=:last WHERE id=:id";
$stmt = $pdo->prepare($stmt);
$data = $stmt->execute(array('last' => $insert_id, 'id' => $result['id']));
}
The above is a global example of your workflow.
You can use temporary tables or create a view for NEW_TABLE.
Temporary Tables
You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.) To create temporary tables, you must have the CREATE TEMPORARY TABLES privilege.
--Temporary Table
create temporary table NEW_TABLE as (select * from ORIGINAL_TABLE group by id);
Views
Views (including updatable views) are available in MySQL Server 5.0. Views are stored queries that when invoked produce a result set. A view acts as a virtual table. Views are available in binary releases from 5.0.1 and up.
--View
create view NEW_TABLE as select * from ORIGINAL_TABLE group by id;
The view will always be updated with the values in ORIGINAL_TABLE and you will not have to worry about having duplicate information in your database.
If you do not want to use the view, I believe you can only perform an insert on one table at a time unless you have some sort of view that would allow you to do both, but you probably want to do it as two steps in a transaction
First you will have to tell the database that you want to start a transaction. Then you will perform your operations and check to see if they were successful. You can get the id of last inserted row (this assumes you have an auto_increment field) to use in the second statement. If both statement seem to work fine, you can commit the changes, or if not, rollback the changes.
Example:
//Assume it will be okay
$success = true;
//Start the transaction (assuming you have a database handle)
$dbh->beginTransaction();
//First Query
$stmt = "Insert into ....";
$sth = $dbh->prepare($stmt);
//See if it works
if (!$sth->execute())
$success = false;
$last_id = $dbh->lastInsertId();
//Second Query
$stmt = "Insert into .... (:ID ....)";
$sth = $dbh->prepare($stmt);
$sth->bindValue(":ID", $last_id);
//See if it works
if (!$sth->execute())
$success = false;
//If all is good, commit, otherwise, rollback
if ($success)
$dbh->commit();
else
$dbh->rollBack();
I have a page which is doing an insert. The DB table has a unique column called "order" that auto increments upon adding a new row. I am executing the insert in this way:
$insert = <<<SQL
INSERT INTO `order` (name, email, team, project, startdate, enddate, comment, server) VALUES (?,?,?,?,?,?,?,?);
SQL;
$instat = $mysqli->prepare($insert);
$bind = mysqli_stmt_bind_param($instat, "ssssssss", $name, $email, $team, $project, $timestart, $timeend, $comment, $code);
$exec = mysqli_stmt_execute($instat);
mysqli_stmt_close($instat);
mysqli_close($mysqli);
I am allowing the DB to handle an auto increment of the order column so that it cannot be duplicated. This works just fine, but if I were to hit refresh on the page, it will insert another row with the same data on a new unique order id. How can I prevent another insert upon a page refresh?
After saving the row, redirect the page to another page with corresponding message . Your flow will be like
1) $service->saveObject($dataObject);
2) redirect_to_success page.
before every insert - make select query and check
Make insert query with NOT EXIST:
How to 'insert if not exists' in MySQL?
MySQL: Insert record if not exists in table
3.Redirect to current page after insert.
I am making a wordpress plugin, where I have functions in the main php file:
<?php
include_once "define.php";
include_once 'includes/form_processor.php';
include_once 'includes/email_subscriber.php';
include_once 'includes/options_page.php';
include_once 'includes/widget.php';
//register the plugin installation methods
register_activation_hook(__FILE__, 'install_simple_subscriber_plugin');
register_deactivation_hook(__FILE__, 'uninstall_simple_subscriber_plugin');
//register the plugin url
wp_enqueue_style('simple-email-subscriber-css', plugins_url('/simple_email_subscriber/stylesheets/style.css'));
function install_simple_subscriber_plugin(){
add_action('plugins_loaded', 'setup_plugin_actions');
email_subscriber::install_database();
email_subscriber::update_database();
}
function setup_plugin_actions(){
if(has_action('publish_post')){
$simple_email_subscriber = new email_subscriber();
//add action listener to post publication
add_action('publish_post', array($simple_email_subscriber, 'on_publish_post'));
add_action('publish__future_post', array($simple_email_subscriber, 'on_publish_post'));
}
//add the admin menu pages
$options_page = new options_page();
}
function uninstall_simple_subscriber_plugin(){
remove_action('plugins_loaded', 'setup_plugin_actions');
}
?>
AND in my custom class I have:
<?php
class email_subscriber{
/*
* Plugin Core Methods
* */
static function install_database() {
//define create table query
$sql = "CREATE TABLE IF NOT EXISTS ".SIMPLE_EMAIL_SUBSCRIBER_DB_NAME."(
id mediumint(9) NOT NULL AUTO_INCREMENT,
subscribe_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
email VARCHAR(55) NOT NULL,
UNIQUE KEY id (id)
);";
//update db and make it auto adjust
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
//HERE IS THE NEW BITS ADDED TO THE EXISTING PLUGIN THAT'S NOT GET CALLED
static function update_database(){
$sql=
"DELIMITER $$
CREATE PROCEDURE Alter_Table()
BEGIN
DECLARE _count INT;
SET _count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'email_subscription' AND
COLUMN_NAME = 'subscribe_all');
IF _count = 0 THEN
ALTER TABLE ".SIMPLE_EMAIL_SUBSCRIBER_DB_NAME."
ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1,
ADD COLUMN subscribe_category varchar(512) DEFAULT NULL;
END IF;
END $$
DELIMITER ;
CALL Alter_Table();
DROP PROCEDURE Alter_Table;
";
//update db and make it auto adjust
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
//add the options for db defination
add_option("ses_db_version", SES_PLUGIN_VERSION);
}
.................and other codes
}
The update_database() method is the new method I added in, that's trying to update the database for extra functions. but it's never get run when the plugin activates.
You just want to execute that query.
global $wpdb;
$wpdb->query($sql);
dbDelta is used to create new tables or update existing ones to conform to an updated scheme. Simply put, it accepts a CREATE TABLE query and transforms it into an ALTER TABLE query if necessary. The Codex says:
The dbDelta function examines the current table structure, compares it
to the desired table structure, and either adds or modifies the table
as necessary, so it can be very handy for updates [...] Note that the
dbDelta function is rather picky, however.