Convert SQL UPDATE statement to php with if else condition (codeigniter) - php

I want to make php code with SQL Update Statement in Codeigniter.
If I execution code in Codeigniter, the data in database will be updated too.
I want to update one column (ID_STATUS) but with several condition.
The connection column 'ID_STATUS' with column 'lama' and 'estimasi'
My table name is "pelayanan".
ID_STATUS is PK from table "status".
So, Column ID_STATUS in table "pelayanan" is foreign key from table "status".
I tried with this query, but, It isn't if else condition yet.
condition 1 :
UPDATE `dbhpl`.`pelayanan`
SET `pelayanan`.`ID_STATUS` = '1'
WHERE `pelayanan`.`LAMA` <> `pelayanan`.`ESTIMASI`;
condition 2:
UPDATE `dbhpl`.`pelayanan`
SET `pelayanan`.`ID_STATUS` = '2'
WHERE `pelayanan`.`LAMA` = `pelayanan`.`ESTIMASI`;
That is the query on mysql. But I want to convert that query to php code (Codeigniter).
How come It will be?

your first query is
UPDATE `dbhpl`.`pelayanan`
SET `pelayanan`.`ID_STATUS` = '1'
WHERE `pelayanan`.`LAMA` <> `pelayanan`.`ESTIMASI`;
convert it as follows:
$update_data=array('ID_STATUS'=>'1');
$this->db->where('LAMA <>','ESTIMASI');
$this->db->update('pelayanan',$update_data);
your second query is
UPDATE `dbhpl`.`pelayanan`
SET `pelayanan`.`ID_STATUS` = '2'
WHERE `pelayanan`.`LAMA` = `pelayanan`.`ESTIMASI`;
convert it as follows:
$update_data=array('ID_STATUS'=>'2');
$this->db->where('LAMA','ESTIMASI');
$this->db->update('pelayanan',$update_data);
I have remove database name. database name will be selected in connection and and did required to mentioned it here.

condition 3:
a. both LAMA and ESTIMASI are null.
b. LAMA is null
c. ESTIMASI is null
If you want to update all rows in the table, based on the values of LAMA and ESTIMASI, you could do that in one fell swoop with one UPDATE statement.
UPDATE `dbhpl`.`pelayanan` p
SET p.`ID_STATUS`
= CASE
WHEN p.`LAMA` = p.`ESTIMASI` THEN '2'
WHEN p.`LAMA` <> p.`ESTIMASI` THEN '1'
WHEN p.`LAMA` IS NULL AND p.`ESTIMASI` IS NULL THEN p.`ID_STATUS`
WHEN p.`LAMA` IS NULL THEN p.`ID_STATUS`
ELSE p.`ID_STATUS`
END
Note that assigning the current value of the ID_STATUS column back to the ID_STATUS column results in "no update".
Since the last two WHEN conditions return the same values as the ELSE, those could be removed. These were included just to illustrate possible handling of condition 3.
One small difference with this vs. the original is that it will attempt tto update every row in the table, including rows that have a NULL value in LAMA and/or ESTIMASI. That means any UPDATE triggers will be fired for those rows. To get exactly the same result as the original, you'd need to include a WHERE clause that excludes rows where LAMA is null or ESTIMASI is null. For example:
WHERE p.`LAMA` IS NOT NULL
AND p.`ESTIMASI` IS NOT NULL
As far as how to accomplish this same thing in PHP, someone else may be able to answer that. Personally, I'd just do it one SQL operation.
The ANSI-standard syntax is a bit verbose. A MySQL specific version that accomplishes the same thing is a bit shorter:
UPDATE `dbhpl`.`pelayanan` p
SET p.`ID_STATUS` = IFNULL((p.`LAMA`=p.`ESTIMASI`)+1,p.`ID_STATUS`)
FOLLOWUP
If LAMA and ESTIMASI are defined as NOT NULL, then you wouldn't have to deal with condition 3. (In the more general case, we don't necessarily have that guarantee, so I think it's better pattern to account for those conditions, even if they won't ever happen in our particular case.
For CodeIgniter ActiveRecord, you'd could try something like this:
$this->db
->set('ID_STATUS', 'IFNULL((`LAMA`=`ESTIMASI`)+1,`ID_STATUS`)', FALSE)
->update('`dbhpl`.`pelayanan`');

Related

Assigning the value to an empty field

Need to update a field in database, but when I make a request, it writes me "0 rows affected" although the image field is, and it is empty.
UPDATE `oc_product` SET `image`= 'no_image.png' WHERE `image`='';
Your query is checking for a value of an empty string, although from what you have shown the value you are actually looking to change has a value of NULL. These are two different values, NULL isn't equal to ''. As such if you are looking to replace items that have a NULL value you need to change your where statement for that (WHERE image IS NULL):
UPDATE `oc_product` SET `image`= 'no_image.png' WHERE `image` IS NULL;
Did select query returns any rows
select image from oc_product WHERE image='';
If so add other field confition as well to check whether it is getting affected ot not example
UPDATE oc_product SET image= 'no_image.png' WHERE (image= "" AND image IS NULL) and other_column ='column value';
Hope this helpful for you :)

ON DUPLICATE KEY UPDATE - Condition WHERE vs CASE WHEN vs IF?

I am refering to this post. I am stuck with a problem I can't resolve. I try to insert multiple rows with a php script into a MySQL database. I don't succeed in updating the whole thing using ON DUPLICATE KEY UPDATE and using a WHERE condition (at the end of the code below) I would like to use to update only an entry has been modified recently:
// for information (used in a foreach loop):
$args[] = '("'.$row['lastname'].'", '.$row['phone'].', "'.$row['lastModification'].'")';
// then:
$stringImplode = implode(',', $args);
// Where I am stuck - WHERE statement:
$sql = $mysqli->query('INSERT INTO table_name '. (lastname, phone, timestamp) .' VALUES '.$stringImplode .'ON DUPLICATE KEY UPDATE lastname=VALUES(lastname), phone=VALUES(phone) WHERE timestamp > VALUES(lastModification);
Everything works fine except I cannot set any WHERE condition at this point that involves multiples entries. Maybe the WHERE statement in this case is not intended to refer to a condition in this statement.
I was told to try with a database procedure using a JOIN statement and a temporary table with first all my entries and then querying some conditions. But I have to admit I don't understand very well how I could leverage such a table to update an other table.
Is there an easy and lovely way to use a "CASE WHEN" or an "IF" statement in this case?
Would something like
INSERT INTO ... ON KEY DUPLICATE UPDATE lastname = VALUES(lastname), phone = VALUES(phone)
CASE WHEN (timestamp > VALUES(lastModification)) THEN do nothing ...
or
...ON KEY DUPLICATE UPDATE... IF (timestamp > VALUES(lastModification)) ...
If anyone could help me, I would be very grateful.
EDIT: Since I will have many variables, could it be used in this way:
INSERT INTO ... ON KEY DUPLICATE UPDATE
IF(timestamp > VALUES(timestamp),
(
name = VALUES(name),
number = VALUES(number),
timestamp = VALUES(timestamp)
....many other variables
),
(
name = name,
number = number,
timestamp = timestamp
....many other variables)
)
You can use simple IF function in value like this:
INSERT INTO ... ON KEY DUPLICATE UPDATE
name = VALUES(name),
number = VALUES(number),
timestamp = IF(timestamp > VALUES(timestamp), VALUES(timestamp), timestamp)
If condition is not met, it will update timestamp with the same timestamp which already exists. It does not matter, because update to same values is optimized before it is even executed, so MySQL will not make real update. You should not afraid of some performance penalty.
EDIT:
IF works likes this:
IF(condition, returned when true, returned when false)
Maybe you need to switch those two arguments to fit your condition like you want.

PHP MySQLi insert get last column value add 1

I'm trying to run an INSERT query into a table with 3 columns. The first column is where I'm having the issue.
It is called COMM_CODE with VARCHAR value of 10 length, and is the primary key, ALLOW NULL is unchecked.
The values for COMM_CODE look like this:
COMM_CODE
c20188
c20189
c20190
// and so on
What I would like to do, is when a new record is inserted, to basically add 1 to the most recent record.
Therefore, the most recent record is:
c20190
So when I add a new record, the COMM_CODE for the new record will be:
c20191
I tried this:
INSERT INTO table_c
(COMM_CODE, COMM_DESC, DATE)
VALUES
(''+1, 'VIDEO GAMES', NOW());
But that just adds a number 1 to that column.
How can I make this happen?
Here the solution for your query :
To generate the new code I'hv created get_new_code function in mysql. I hope you know how funcions work in mysql.
CREATE FUNCTION `get_new_code`() RETURNS varchar(11)
BEGIN
Declare var_code VARCHAR(11);
SELECT max(`COMM_CODE`) INTO var_code FROM table_c;
RETURN (CONCAT('c',(convert(substr(var_code,2,length(var_code)), SIGNED INTEGER)+1)));
END
Just to verify your logic you can use :
select get_new_code();
So that you will get the clear picture.
Call this get_new_code function in insert query like this :
INSERT INTO
`table_c`(`COMM_CODE`, `COMM_DESC`, `COMM_DATE`)
VALUES
(get_new_code(),'Description text',NOW());
This should solve your problem. :)

insertion on BIT column in mysql from Zend Framework 2

I need to update two columns in a table in mysql. I have written following code in ZF2 model
$sql = new Sql($dbAdapter);
$update = $sql->update();
$update->table($table_name)
->set(array('checksum' => '', 'mailed_status' => 0))
->where('id = ' . $record_id);
$statement = $sql->prepareStatementForSqlObject($update);
$statement->execute();
Here in the above code, checksum is varchar column and mailed_status is bit column. The above query only updates checksum field but the mailed_status remains same (previously 1)
When I was updating mailed_status as 1, it works. I mean it updates 0 to 1 but the vice versa is not working.
I have printed the query and found that it makes quote around digit like this: '0' and '1'.
But I am wondering here. '1' is working but '0' is not, why?
What is the proper solution for this? Temporarily I changed the bit data type to varchar(1) in mysql database's table.
Thanks
Thats because 0 is treated like a Null value when updating your database. Changing column type to varchar(1) it's simpler than override sql update method!

Unique constraint, how to avoid duplicates

According to my previous Query that post i have a table that looks like this:
|| *nid* || *language* ||
|| 8 || Chinese ||
|| 8 || Portuguese ||
|| 8 || German |
In which 'nid' and 'language' have a unique constraint.
With this setup how can i make sure that the there wont be any duplicate when i try to insert a new row ?
EDITED
I am guessing I should try to make a query such as:
SELECT * FROM lang WHERE nid = $nid AND language = $lang
If this return FALSE then i know i can now insert my data. Is this correct ?
Enforce the unique constraint by creating a unique key:
ALTER TABLE the_table
ADD UNIQUE INDEX nid_language_unique (nid, language);
This constraint forbid two rows having the same nid and language.
Any query attempting to violate the constraint will fail.
As you want to ignore errors (and still abort the query), you can use INSERT IGNORE and UPDATE IGNORE:
INSERT IGNORE INTO the_table (nid, language) VALUES (8, 'Chinese')
/* row not inserted and no error */
If you have actually established a unique constraint in the database then MySQL will not let you insert the second row. The statement will raise an exception. You can trap and ignore that in your code. If you're not interested in whether the row was added or not, you can use the IGNORE keyward in the MySQL INSERT INTO command and the row will either be added (if not there) or the command will complete without an error.
SELECT nid, language FROM lang WHERE nid = $nid AND language = $lang
If this return FALSE then i know i can now insert my data. Is this correct ?
Yes, but you need to write:
$nid = mysql_real_escape_string($_POST['nid']);
$lang = mysql_real_escape_string($_POST['lang']);
$query = SELECT nid, language FROM lang WHERE nid = '$nid' AND language = '$lang'
// notice the quotes ^ ^ ^ ^
If you forget these your query give an error (and be at risk from SQL-injection).
If you have a unique constraint, you can just go ahead and insert the data, because MySQL will do the above test for you.
You can use a counter in your code (not SQL, but the one you use to use SQL, like PHP, or else)
You can use MySQL max function and add one (like max(nid)+1 (but don't remember about MySQL's max function))
You can use a random number with 10 characters (so you'd would have a really really low risk to go into an error)
I used the first and last way many times.
And if you want to be sure that you won't have a duplicate, use the solutions from your last posts. Stuff like UNIQUE constraint will prevent you to insert twice the same nid or language (thus, if you don't handle it, your program will crash).

Categories