MySQL Trigger Won't Fire After Insert From Wordpress Endpoint - mysql

I want to delete all high scores except the top 10.
My query works fine as a query in PHPMysql, but when I try to use it in a trigger, it doesn't fire.
If anyone has a suggestion or needs additional information, please let me know. Thanks.
//The query
DELETE FROM ONEGameleaderboard WHERE _id Not IN
(SELECT * FROM (SELECT _id FROM ONEGameleaderboard ORDER BY Score DESC , Date ASC LIMIT 10) as t)
//The Trigger insert query
CREATE TRIGGER `ONEGameleaderboardTop10Limit` AFTER INSERT ON `ONEGameleaderboard`
FOR EACH ROW DELETE FROM ONEGameleaderboard WHERE _id Not IN
(SELECT * FROM (SELECT _id FROM ONEGameleaderboard ORDER BY Score DESC , Date ASC LIMIT 10) as t)
//The insert code form the WordPress endpoint (Which inserts the data just fine)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$parameters = $request->get_json_params();
if($request['id'] == 1)
{
$sql = "INSERT INTO ONEGameleaderboard (Date, Name, Score) VALUES ('$parameters[Date]', '$parameters[Name]', '$parameters[Score]')";
}
elseif($request['id'] == 2)
{
$sql = "INSERT INTO TWOGameleaderboard (Date, Name, Score) VALUES ('$parameters[Date]', '$parameters[Name]', '$parameters[Score]')";
}
elseif($request['id'] == 3)
{
$sql = "INSERT INTO THREEGameleaderboard (Date, Name, Score) VALUES ('$parameters[Date]', '$parameters[Name]', '$parameters[Score]')";
}
else
{
$message = 'No Leaderboard Table for this Index';
return new WP_ERROR('no_data', $message, array('status' => 404));
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

Related

Update same tables from from select value from same table mysql

i am trying to update a table column which same column from same table select.
Here is the code (updated)
public function UpdateStockIn($id, $subUnitValue) {
$query = "UPDATE BRAND_LIST SET CURRENT_STOCK_BOTTLE = (SELECT CURRENT_STOCK_BOTTLE FROM BRAND_LIST WHERE ID = ?) + '.$subUnitValue.' WHERE ID = ? ";
$success = 0;
try {
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $id);
$stmt->execute();
$success = 1;
} catch (PDOException $ex) {
echo $ex->getMessage();
}
return $success;
}
it Show error like this
You can't specify target table 'BRAND_LIST' for update in FROM clause
Try run these 2 sqls, The first one will store a value into mysql local variable then use into 2nd sql.
SELECT #old_subUnitValue := GROUP_CONCAT(table1.CURRENT_STOCK_BOTTLE) FROM BRAND_LIST AS table1 WHERE table1.ID=2;
UPDATE BRAND_LIST AS table2 SET table2.CURRENT_STOCK_BOTTLE = #old_subUnitValue + '.$subUnitValue.' WHERE table2.ID=2;
Use the below query
$query = "UPDATE BRAND_LIST SET CURRENT_STOCK_BOTTLE = CURRENT_STOCK_BOTTLE + ".$subUnitValue." WHERE ID = ?";

Trigger that will insert deleted data into table

I want to create a trigger that will insert delete data into a backup table , I have wrote this code , but it's not working. MYSQL is throwing syntax error when i create this trigger . How can I get expected result ? Any Help would be appreciated.
BEGIN
IF EXISTS (SELECT *
FROM information_schema.tables
WHERE table_schema = 'jobportal'
AND table_name = 'dlt_jobs'
LIMIT 1) THEN
create table dlt_jobs (select *,now() as deleted_on from jobs where job_id=OLD.job_id) ;
ELSE
insert into dlt_jobs (username) values ('something');
END IF;
END
if u are deleting or insert simply add another line of code to perform the task here is and example
<?php
include_once '../dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$emails = trim($_POST['emails']);
$emails = strip_tags($emails);
$emails = htmlspecialchars($emails);
//basic emails validation
if ( !filter_var($emails,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailsError = "Please enter valid emails address.";
} else {
// check emails exist or not
$query = "SELECT emails FROM newsletter WHERE emails='$emails'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailsError = "Provided emails is already in use.";
}
}
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO newsletter(emails) VALUES('$emails')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($emails);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>

insert-update pdo mysql query and get last inserted id, if needed

I have simple insert/update page where I do check if there is "id", if no then proceed insert query otherwise proceed update query, and this works fine. Problem is that I need that id for the next query, in case of Insert query I will get it as "lastInsertId" but in case of Update query "lastInsertId" will overwrite $_POST["id"].
Is there a way to identify which query has been performed (insert or update) and then get right id, or I have to bind/ execute query's separately?
$id= $_POST["id"];
try {
$DBH = db_connect ();
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($id== "") {
$query= $DBH->prepare('INSERT INTO table (x1,x2) VALUES(:x1,:x2)');
} else {
$query= $DBH->prepare('UPDATE day SET x1=:x1, x2=:x2 WHERE id= :id');
$query-> bindValue(':id', $id);
}
$query-> bindValue(':x1', $x1);
$query-> bindValue(':x2', $x2);
$query-> execute();
$id= $DBH-> lastInsertId('id') ; //get last inserted ID
}
You can use exactly the same if clause as for picking the insert query as the query to excecute. Then your code would look like this:
$id= $_POST["id"];
try {
$DBH = db_connect ();
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($id== "") {
$query= $DBH->prepare('INSERT INTO table (x1,x2) VALUES(:x1,:x2)');
} else {
$query= $DBH->prepare('UPDATE day SET x1=:x1, x2=:x2 WHERE id= :id');
$query-> bindValue(':id', $id);
}
$query-> bindValue(':x1', $x1);
$query->bindValue(':x2',$x2);
$query-> execute();
if($id==""){
$id= $DBH-> lastInsertId('id') ; //get last inserted ID
}
}

joomla database select and insert query

i am trying to insert another info to joomla (2.5.7) database after user is registered. The user chooses his usergroup and I want the insertion to happen only when the user is in a specific group. So I am trying to use this code to get the group data from the databse first to be used in the insert query. Now it is just a testing ground, later this retrieved value be used in if statement.
This is the code:
function onUserAfterSave($user, $isnew, $success, $msg)
{
if ($isnew && $success) {
$db = &JFactory::getDBO();
$query = "SELECT #__k2_users.group FROM #__k2_users WHERE userID = ".$user['id'];
$db->setQuery($query);
$group = $db->loadResult();
$db->setQuery( 'INSERT INTO #__user_profiles (ordering) VALUES ('.$group.')' );
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
return $this->onAfterStoreUser($user, $isnew, $success, $msg);
}
and this is the error I am getting upon the failed registration:
Column count doesn't match value count at row 1 SQL=INSERT INTO std13_user_profiles (ordering) VALUES ()
If I read it correctly, it means that the select statement is not returning anything but why? Thank you for your help.
UPDATE:
if ($isnew && $success) {
$db = &JFactory::getDBO();
$userId = JArrayHelper::getValue($user, 'id', 0, 'int');
$query = "SELECT #__k2_users.group FROM #__k2_users WHERE userID = ".$userId;
$db->setQuery($query);
$group = $db->loadResult();
$query2 = "INSERT INTO #__user_profiles (ordering) VALUES ('".$group."')";
$db->setQuery($query2);
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
with this code, I don't get any errors and the user is registered and the values are inserted. However the $group is always 0 and based on the value is only 1 or 3 in k2_users table, I am guessing that it returns nothing. I think it may be because the registered user is not stored in the databse yet and it doesn't have his ID yet to look for the group?
UPDATE2:
if ($isnew && $success) {
$count = JRequest::getVar('gender');
if($count == 3) {
$db = &JFactory::getDBO();
$alias = $user['name'];
$table = array(
' '=>'-', 'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'Ž'=>'Z', 'ž'=>'z', 'C'=>'C', 'c'=>'c', 'C'=>'C', 'c'=>'c',
'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'ě'=>'e', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'R'=>'R', 'r'=>'r', " "=>'-', '"'=>'-'
);
$string = strtr($alias, $table);
$alias_low = strtolower($string);
$query = "INSERT INTO #__menu (menutype, title, alias, path, link, type, published, level, component_id, access) VALUES ('stavebnici','".$user['name']."','".$alias_low."','".$alias_low."',
'index.php?option=com_k2&view=itemlist&layout=user&id=".$user['id']."&task=user','component',1,1,10012,1)";
$db->setQuery($query);
$db->query();
if (!$db->query())
{
throw new Exception($db->getErrorMsg());
}
}
}
OKAY! I got it working so now I can insert new menu every time a user is created, however th activation link is not created and the registration says that it failed. This is the error:
Duplicate entry '0-1-vojtech-plesner-' for key 'idx_client_id_parent_id_alias_language' SQL=INSERT INTO std13_menu (menutype, title, alias, path, link, type, published, level, component_id, access) VALUES ('stavebnici','Vojtěch Plešner','vojtech-plesner','vojtech-plesner', 'index.php?option=com_k2&view=itemlist&layout=user&id=2789&task=user','component',1,1,10012,1)
The client_id, parent_id and language have values of 1,1 and * abd they are in all the rows so why is it saying it is duplicate?
You need to update that query to 2.5 style.
http://www.theartofjoomla.com/home/9-developer/135-database-upgrades-in-joomla-16.html
is a good article.
You definitely seem to be missing
$query = $db->getQuery(true);
not to mention that you are using & for an object. That usage will generate strict errors.
You can do it with one query:
$query = "
INSERT INTO #__user_profiles (ordering)
SELECT #__k2_users.group
FROM #__k2_users
WHERE userID = " . user['id']
";
But doesn't #__user_profiles have other columns like the user id?
Also You can do it with one query:
$query = "
INSERT INTO #__user_profiles (ordering)
SELECT "YOURJOOMLADBPREFIX"_k2_users.group
FROM "YOURJOOMLADBPREFIX"_k2_users
WHERE userID = " . user['id']
";

if specific row = null, execute query

how do i check if the value of a column is null, and only then execute the query? for example:
col1 col2 col3
01 abc
i run a query which first checks if the record exists or not; if it exists, it should execute the update query and if it doesn't exist, it executes the insert query. how do i check if col3 is null and if it is null, it should execute the update query. .
$sql = "SELECT uid FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
updateSessionKey($user_id,$sk,$conn);
}
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Not really checking a value of the column, but I don't think you actually need that.
You need to have uid as a UNIQUE column. You try to insert a row for a new user with the given uid; if it finds the user with the same uid, then you do the update instead.
UPDATE:
I guess you did not bother to read the link.
I did not test it, but it should be something like this:
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session='SeSsIoN_iD'
This will insert the user if he does not exist, and if he does, it will set a new session key. OR, if you want to preserve the old session key if he already has one,
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session=IFNULL(session, 'SeSsIoN_iD')
One query, not three. You were not already doing it.
$sql = "SELECT * FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
$res = mysql_fetch_array($sql);
if(!empty($res['col3'])) {
insertUser($user_id,$sk, $conn);
}
}
else
{
updateSessionKey($user_id,$sk,$conn);
}
Is this what you mean?
If the record does not exist -> insert.
If the record does exist and its col3 is null -> update
If the record does exist, but its col3 is not null -> do nothing?
That could be achieved like this (untested):
$sql = "SELECT uid, col3 FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
$col3value = mysql_result($result, 0, 'col3');
if (is_null($col3value))
{
updateSessionKey($user_id,$sk,$conn);
}
}