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.
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 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...";
}
}
}
?>
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 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
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.