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';
Related
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...";
}
}
}
?>
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 :)
Bit of a noob when it comes to PDO. We have a a table that needs to be updated with a cron job daily. The idea is to query the table and for each "active = 1" get an integer from a duration column convert that into days, get the "expiration" column and the duration to the expiration and update the expiration.
I am not even close to getting this to work, I am trying to just get the basics for now. Return the duration which is in hours divide by 24 add that to the date column as days and update EACH row with the appropriate new time.
The problem is I do not know how to update each row with its own information. I have the code below, it updates each row but the new "expires" date ends up being the same even though the expires values are different.
static function cronSetFeatured(){
try{
$db = new PDO('mysql:host=127.0.0.1;dbname=mydb', 'dbuser', 'pw' );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
die();
}
$query = $db->query('SELECT * FROM featured_producers ');
$now = date('Y-m-d H:i:s');
while($r = $query->fetch(PDO::FETCH_OBJ)){
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
}
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != 0";
$q = $db->prepare($sql);
$q->execute(array($expires));
echo $expires.'<br>';
}
Well if you want to UPDATE each record on its own, that query need to be part of the loop body:
while($r = $query->fetch(PDO::FETCH_OBJ)){
//calculate expiration
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
//Get the id (needed for update)
$id = $r->id;
//updating
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != ?";
$q = $db->prepare($sql);
$q->execute(array($expires, $id));
echo $expires.'<br>';
}
I'm a MYSQL/PHP newbie and I'm sure this is a simple question. I'm trying to calculate the average of several questions and respondents from one table and updating a Group table with that value.
For example Table answers consists of (name, group_id, TaskClarity1, TaskClarity2, TaskClarity3) in Table B i want (group_id, avg(TaskClarity1,TaskClarity2,TaskClarity3)).
This is what I've got...
$avg_task_clarity_1 = mysql_query("SELECT AVG(TaskClarity1) WHERE gruppid = '$group_id'");
$avg_task_clarity_2 = mysql_query("SELECT AVG(TaskClarity2) WHERE gruppid = '$group_id'");
$avg_task_clarity_3 = mysql_query("SELECT AVG(TaskClarity3) WHERE gruppid = '$group_id'");
$avg_task_clarity = ($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3;
$print_task_clarity_1" UPDATE results SET results.TaskClarity = '$avg_task_clarity'";
if (mysql_query($print_task_clarity_1)) { echo $print_task_clarity_1; } else { echo "Error TaskClarity1: " . mysql_error();
First, mysql_query() returns a resource, and you then need to extract information from it. Your query doesn't mantion any table name (I'll call it MyTable).
Also, you can get all three averages with one query.
Here's how I would start:
$table = "MyTable";
$sql = "SELECT AVG(TaskClarity1) AS avgClarity1,
AVG(TaskClarity2) AS avgClarity2,
AVG(TaskClarity3) AS avgClarity1
FROM $table WHERE gruppid = '$group_id'";
$resource = mysql_query($sql); //execute the query
if (! $resource = mysql_query($sql) ){
echo "Error reading from table $table";
die;
}
if (! mysql_num_rows($resource ) ){
echo "No records found in $table";
}
else {
$row = mysql_fetch_assoc($resource); // fetch the first row
$avg_task_clarity_1 = $row['avgClarity1'];
$avg_task_clarity_2 = $row['avgClarity2'];
$avg_task_clarity_3 = $row['avgClarity3'];
$avg_task_clarity =
($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3;
//...
// other stuff you want to do
}
Please comment if this is not helpful enough, and I will revise my answer.