I am wondering if mysqli works when binding a column reference +1 type of field. Example.
UPDATE `table` SET `sys-helpful-yes` = `sys-helpful-yes`+1 WHERE `id` = 1;
When using mysqli bind parameters, it doesn't add the one.
UPDATE `table` SET `sys-helpful-yes` = ? WHERE `id` = 1;
I am trying to bind
`sys-helpful-yes`+1
Wondering if anyone has a workaround.
What about
UPDATE `table` SET `sys-helpful-yes` = `sys-helpful-yes`+ ? WHERE `id` = 1;
and then, of course, only bind 1 ...
(not tested) ?
Related
I am trying to create a query inside a PDO script that checks if a record exists if it does the query should update the record and if it doesn't exist it should create a new one.
The column that should only exist once in the table is not an INDEX key (cannot make it unique right now) so it is not set as unique and I cannot use the ON DUPLICATE KEY UPDATE
I would like to use this queries logic below to make it work:
$stmt = $conn->prepare('IF EXISTS (SELECT * FROM `Table1` WHERE `code`= :code )
UPDATE `Table1`
SET `code_stat` = 2
WHERE code = :code
ELSE
INSERT INTO `Table1` (`code`,`code_stat`)
VALUES (:code, 2 ) ' );
$stmt->execute([
'code' => $_POST['code']
]);
The problem is when executing the query I get the following error saying there is a syntax problem:
SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near
'IF EXISTS (SELECT * FROM Table1 WHERE code= ? ) UPDATE Table1' at line 1
If you can't add a unique key to the table, you can attempt an update first, and if that doesn't update any rows, do an insert. Something like this:
$stmt = $conn->prepare('UPDATE `Table1` SET `code_stat` = 2 WHERE code = :code');
$stmt->execute(array(':code' => $_POST['code']));
if (!$stmt->rowCount()) {
// no rows updated, so insert
$stmt = $conn->prepare('INSERT INTO `Table1` (`code_stat`, `code`) VALUES (2, :code)');
$stmt->execute(array(':code' => $_POST['code']));
}
Note that you may need to set the PDO::MYSQL_ATTR_FOUND_ROWS attribute to ensure that the UPDATE query returns 1 if it finds the row but the value doesn't change. You must set that attribute when you make the connection e.g.
$conn = new PDO($dsn, $user, $pass, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
Why not write a stored procedure to handle this, similar to the below:
DROP PROCEDURE IF EXISTS db.SP_NEW_CODE;
CREATE PROCEDURE db.`SP_NEW_CODE`(IN `in_code` INT)
BEGIN
DECLARE numFound INT DEFAULT 0;
SET numFound=(SELECT * FROM `Table1` WHERE `code`= in_code);
IF (numFound=0) THEN
INSERT INTO `Table1` (`code`,`code_stat`) VALUES (in_code, 2 );
ELSE
UPDATE `Table1` SET `code_stat` = 2 WHERE code = in_code
END IF;
END;
From your code, simple execute CALL SP_NEWCODE(3); (for example, where 3 is the appropriate code value).
how should i update my attempt's using variable ? it wont work
mycode
$db_attempts = 'MAX_ATTEMPTS';
//here
$attemtps_pdo = 'UPDATE `attempts` SET `MAX_ATTEMPTS`= ? +1 WHERE `IP` = ?';
$results = $ALIST->update($attemtps_pdo,$db_attempts,$user_ip);
public function update($sql,$values1,$values2){
try{
$results = $this->connection->prepare($sql);
$results->bindValue(1, $values1);
$results->bindValue(2, $values2);
$results->execute();
return $results;
}
how do i make my MAX_ATTEMPTS +1 to variable , if i do it with my code , the update only update once , once is == 1 it wont update anymore why?
but if i using
$attemtps_pdo = 'UPDATE `attempts` SET `MAX_ATTEMPTS`= `MAX_ATTEMPTS` +1 WHERE `IP` = ?';
it work perfectly.
Because you are not referencing the MAX_ATTEMPTS column when you BIND the variable $db_attempts into your SQL query. Binding prevents stuff like this, because it could potentially lead to SQL injection.
In other words, your second example IS the correct way of doing this. If you want this to be dynamic (eg. if $db_attempts can change), then you have to build the query using string concatenation.
Alternative solutions:
Assuming it will always update by 1 every time the sql gets executed and assuming $value1 is the value currently in the database for MAX_ATTEMPTS.
What I would suggest is to it when you bind the parameters:
$results->bindValue(2, (int)$values1 + 1);
Your sql will be:
$attemtps_pdo = 'UPDATE `attempts` SET `MAX_ATTEMPTS`= ? WHERE `IP` = ?';
OR
Add a database query to find the latest value of MAX_ATTEMPTS and pass it as $value1 which realizes the assumption made in the previous solution.
Just try the incrementation :
UPDATE attempts SET MAX_ATTEMPTS++ WHERE IP = ?
I have face a problem with my UPDATE Query in Mysql-
mysql_query( INSERT INTO `cost`
SET `cat_id` = '18', `feature_id` = '77', `type_id` = '5',
`cost_from` = '600', `cost_to` = '800'
WHERE `type_id` = 5 && `cat_id` = 18 && `feature_id` = 77");
type_id = 5 is not in my current table where i want to SET my new values.
The result is Unsuccessful.
I tried also an UPDATE query for the same
mysql_query( Update `cost`
SET `cat_id` = '18', `feature_id` = '77', `type_id` = '5',
`cost_from` = '600', `cost_to` = '800'
WHERE `type_id` = 5 && `cat_id` = 18 && `feature_id` = 77");
What should i do to insert and update values at the same time?
Note:
You don't use WHERE and SET on an INSERT query.
Make sure you have a table named cost along with the columns cat_id, feature_id, cost_from, cost_to, type_id.
You're trying to update the cost table columns with the ones you are looking for. Doesn't seem right.
Your first and second given sample codes have the same format, you just changed the first word, INSERT and UPDATE. Doesn't work that way.
You can, I think the recommendation of all people that would see your code, create better queries using mysql_* prepared statements.
A simple example of an INSERT query would look like this:
/* PREPARE YOUR QUERY */
$stmt = $con->prepare("INSERT INTO cost (cat_id, feature_id, type_id, cost_from, cost_to) VALUES (?,?,?,?,?)");
/* BIND PARAMETER TO THE QUERY. REPLACE NECESSARY VALUE OR VARIABLE */
$stmt->bind_param('iiiss', $catid,$featureid,$typeid,$costfrom,$costto);
$stmt->execute(); /* EXECUTE QUERY */
A simple example of an UPDATE query:
/* PREPARE YOUR QUERY */
$stmt = $con->prepare("UPDATE cost SET cat_id=?, feature_id=?, type_id=?, cost_from=?, cost_to=? WHERE id=?");
/* BIND PARAMETER TO THE QUERY. REPLACE NECESSARY VALUE OR VARIABLE */
$stmt->bind_param('iiissi', $catid,$featureid,$typeid,$costfrom,$costto,$id);
$stmt->execute(); /* EXECUTE QUERY */
First of all, you cannot use 'set ' with ' insert into' , and if you want to insert and update queries at the same time, then your best bet is using transaction . (you have to enclose insert and update queries in a transaction) , you cannot enclose both on a single sql statement..
This post might help you
SQL Update,Delete And Insert In Same Time
I am trying to find a way to insert a value into one of two columns depending on which one is NULL.
$accept_sth = $dbh->prepare("UPDATE user_properties
IF(followup_offer <> NULL, fstatus=?)
ELSE (istatus=?)
WHERE id=?");
$accept_sth->execute($_POST['option'], $_POST['id']);
I am doing it wrong.
No ...brain damage... necessary. You can do it with a query
UPDATE user_properties
SET fstatus = IF(followup_offer IS NULL, fstatus, ?),
istatus = IF(followup_offer IS NULL, ?, istatus)
WHERE id = ?
Note: the only possible drawback for some scenarios of this type of query with conditional SET is that both columns are updated every time (one with a value and one with the old one).
Here is SQLFiddle demo
Ok so i want to do a prepared insert such as:
prepare("INSERT INTO `analyzeditemsdetails` SET
analyzeditem_id = ? ,
start_time = ? ,
end_time = ?
");
start_time and end_time are stored in the database as sql dates. Fill in the ?'s in this next statement:
$stmt->bind_param('i??',
$this->sqlid,
$item['start_time'],
$item['end_time']
);
So basically what do I put in a bind_param method call for sql dates???
I think it would be s (string).
$stmt->bind_param('iss',
$this->sqlid,
$item['start_time'],
$item['end_time']
);