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...";
}
}
}
?>
Related
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 = ?";
I am having a weird issue but I do not understand what is happening. I amcreated a function to update up to three columns (end_plan_date, balance and server) in a table (user) and 2 inserts in another table.
For some reason, my last update (column server of the user table) is not committed ($query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");) unless I give a value for at leat one of the two other values ($subamt or $subday).
Do you know why this query is not updating the user table with the server value I parsed?
function addBalance($subemail, $subamt,$subday,$userid,$serv) {
$q = "SELECT * FROM user WHERE email = '$subemail'";
$result = mysql_query($q, $this->connection);
$dbarray = mysql_fetch_array($result);
$endplan_date=$dbarray['end_plan_date'];
if($subday >0){
if($endplan_date=="0000-00-00" ){
$endplan_date = date('Y-m-d');
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}else{
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}
$query = mysql_query("UPDATE user SET end_plan_date='$new_endplan_date' WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES ('$recdate','$userid','Plan Date','$subday')";
mysql_query($q, $this->connection);
}
if($subamt >0){
$query = mysql_query("UPDATE user SET balance=balance+".$subamt." WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES '$recdate','$userid','Balance','$subamt')";
mysql_query($q, $this->connection);
}
$query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");
return 0;
}
In your code u can't get directly this
$endplan_date=$dbarray['end_plan_date'];
for fetching this variable u have to use while loop like
while($dbarray = mysql_fetch_array($result);) {
$endplan_date=$dbarray['end_plan_date'];
}
There was an issue when calling this function.
I have written following code for my sales_invoice.php
if(isset($_POST['submit1'])){
// $cat_array = $_POST['category_name'];
// $qua_array = $_POST['quantity'];
//$mrp_array = $_POST['mrp'];
//$vat_array = $_POST['vat'];
// print_r($_POST);
if(!empty($_POST['item_name']) && is_array($_POST['item_name'])){
$name_array =$_POST['item_name'];
//print_r($name_array);
for($j=0; $j< count($name_array);$j++){
$name = mysql_real_escape_string($name_array[$j]);
//echo $name;
//$n = explode('/',$name);
$sql = "select quantity from purchase_stock where item_name = '$name'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($res);
if($num_rows <=0){
echo "<b>not in stock</b>";
exit();
}
else
continue;
}
}
$sql = "insert into material_inv set order_date='$new_date', due_date='$new_date1', dealer='".$_POST['dealer']."', customer='".$_POST['customer']."'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
if($res == true){
echo "sales invoice created";
}
else
{
echo "error";
}
$myid = mysql_insert_id();
$sales_id = $myid;
//display_item();
// print_r($_POST);
if (!empty($_POST['category_name']) && !empty($_POST['item_name']) && !empty($_POST['quantity']) && !empty($_POST['mrp']) && !empty($_POST['vat']) &&
is_array($_POST['category_name']) && is_array($_POST['item_name']) && is_array($_POST['quantity']) && is_array($_POST['mrp']) && is_array($_POST['vat'])){
// echo 'start';
$name_array = $_POST['item_name'];
$cat_array = $_POST['category_name'];
$qua_array = $_POST['quantity'];
$mrp_array = $_POST['mrp'];
$vat_array = $_POST['vat'];
//print_r($mrp_array);
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$cat = mysql_real_escape_string($cat_array[$i]);
$q = mysql_real_escape_string($qua_array[$i]);
$mrp = mysql_real_escape_string($mrp_array[$i]);
//echo $mrp;
$vat = mysql_real_escape_string($vat_array[$i]);
// mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
$sql ="Insert into material_items SET category_name='$cat', item_name='$name', quantity='$q',
mrp='$mrp', vat='$vat', inv_id ='$sales_id'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
$sql1 = "Update stock set quantity=quantity -'$q' where item_name='$name'";
$res1 = mysql_query($sql1) or die(mysql_error());
echo "stock updated and invoice created";
}
}
}
I have first checked if item is present in purchase_stock table. (items are inserted in purchase_stock table after a purchase order is created). Then i insert in the sales table quantity which is sold. And then I write query to update stock table.
My question is do I write a insert query for stock table if no items are initially present there? Is it logically correct? Or should I keep same stock table to update quantity and items after purchase and sales transactions?
Here is an example of a stored procedure syntax
DELIMITER //
CREATE PROCEDURE GetProduct(IN param_ProductID INT)
BEGIN
SELECT *
FROM Products
WHERE ProductID = param_ProductID;
END //
DELIMITER ;
and this is how you call it from your php:
$mysqli->query("CALL GetProduct(".$param_ProductID.")");
regarding your question about inserting the the product,
you need to perform an UPSERT (insert if not exists and update if exists)
here is an example how to do it:
PHP / MySQL : Insert if doesnt exist else update
shimon :)
I'm having trouble trying to set a variable then use it in a select statement. I keep getting a "general error" and can't figure out what I'm doing wrong. Any input would be appreciate. I'm trying to set a variable using subqueries with named parameters.
$query = $dbh->prepare("Set #available = (SELECT SUM(payments) FROM payments WHERE customer = :customer) - (SELECT SUM(charges) FROM charges WHERE customer = :customer); SELECT #available");
$query->bindParam(":customer", $customer);
$query->execute();
If you want to use MySQL user variables, for some reason, you don't need multi-queries support. They (user variables) live as long as you session (connection) is open. Therefore you can do something like this
$customer = 1;
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SET #available = (SELECT SUM(payments) FROM payments WHERE customer = ?) -
(SELECT SUM(charges) FROM charges WHERE customer = ?)";
$query = $db->prepare($sql);
$query->execute(array($customer, $customer));
$query = $db->prepare("SELECT #available");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Exeption: " .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
var_dump($result);
Sample output:
array(1) {
[0]=>
array(1) {
["#available"]=>
string(6) "100.00"
}
}
PDO doesn't seem to offer any formalised support for multi-queries (but some support does seem to be available), but mysqli does. Neither offer support for prepared multiple statements, though.
You can use mysqli like this:
$mysqli = new mysqli('servername', 'username', 'password', 'dbname');
$query = sprintf("Set #available = (SELECT SUM(payments) FROM payments WHERE customer = %1$s)" .
" - (SELECT SUM(charges) FROM charges WHERE customer = %1$s);".
" SELECT #available",
$mysqli->real_escape_string($customer) );
// Following code lifted from PHP Manual.
// This code will read multiple results, if they're available.
// Your query only returns one.
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
The reference is here
The table is like this
and I want to update DecryptionDate by specify ArchiveID and RecipientID
this is my code
$this->load->database();
$date = date("Y-m-d H:i:s");
$data = array('DecryptionDate' => $date);
$array = array('ArchiveID'=>$archiveID.'','RecipientID'=>$userID.'');
$this->db->where($array);
$this->db->update('log', $data);
if ($this->db->affected_rows() > 0) {
echo "SUCCESS";
} else {
echo "FAIL";
}
my problem is I can update the data only when $archiveID is 911 and $userID is test01 but the program fail to update when $archiveID is 911 and $userID is test02
after added echo $this->db->last_query(); I've got
UPDATE log SET DecryptionDate = '2011-11-16 20:01:39' WHERE ArchiveID = '911' AND RecipientID = 'test01'
when ArchiveID is test01 and the update is SUCCESS
and
UPDATE log SET DecryptionDate = '2011-11-16 20:03:10' WHERE ArchiveID = '911' AND RecipientID = 'test02'
when ArchiveID is test02 and the update is FAIL
I've try this
$this->load->database();
$date = date("Y-m-d H:i:s");
$this->db->query('UPDATE log
SET DecryptionDate = \''.$date.'\'
WHERE ArchiveID = \''.$archiveID.'\' AND RecipientID = \''.$userID.'\'');
if ($this->db->affected_rows() > 0) {
echo "SUCCESS";
return TRUE;
} else {
echo "FAIL";
return FALSE;
}
but the result's still the same
and try check only the RecipientID like this
$this->load->database();
$date = date("Y-m-d H:i:s");
$this->db->query('UPDATE log
SET DecryptionDate = \''.$date.'\'
WHERE RecipientID = \''.$userID.'\'');
if ($this->db->affected_rows() > 0) {
echo "SUCCESS";
return TRUE;
} else {
echo "FAIL";
return FALSE;
}
make the update success with only record that match with the RecipientID but not with duplicate ArchiveID with other record
like this
Finally, I've test update with common php file with following code instead of via CI and also result is fail
$date = date("Y-m-d H:i:s");
$strSQL = "UPDATE log SET DecryptionDate = '".$date."' WHERE ArchiveID = '911' AND RecipientID = 'test02' ";
$objQuery = mysql_query($strSQL);
if( mysql_affected_rows($objQuery) != 0 )
{
echo (" SUCCESS ");
} else {
echo (" FAIL ");
}
so I think this must be database problem
here is the DB structure
and ArchiveID and RecipientID are index
The code looks fine. Please check that all your fields are correctly spelt, and values are as expected.
Try with a more verbose and debugging-friendly way like this, it should help you spot the problem (maybe the $userID contains a space, or something trivial like that). Call last_query() at the end to see if the query is really the one you wanted
//...
var_dump($archiveID);
var_dump($userID);
$this->db->where('ArchiveID',$archiveID);
$this->db->where('RecipientID',$userID);
$data = array('DecryptionDate' => $date);
$this->db->update('log', $data);
// call this to test the correct query; see if is what you intended
echo $this->db->last_query();
When you say no, do you mean no you cannot connect to MySQL or phpMyAdmin, or no, the query on test2 doesn't return any results? If the second one is true, can you do a select * and verify the fields existance? I cant help but think something may have happened to your data.
I try export the data from database and truncate it then import the data back, it can help, the problem solved.
I have use this code for checking update query status.
$this->db->where($array);
$status = $this->db->update('log', $data);
if($status)
echo 'Success';
else
echo 'Fail';