SQL: INSERT 1 if value=0 and 0 if value=1 - php

I have data from an SQL query that is 'fileUnavailable' and need to insert into another table that is 'fileAvailable.' The values are either 1 or 0 and I need to do an SQL insert. Since fileUnavaiable and fileAvailable are opposite, I'd need to change the first value to either 1 if it's 0 or 0 if it's 1. Originally, I was thinking to just do an if, else statement to change the value, but that seems bulky and seems too simple for there not to be a method already.
I'm mostly curious as to whether or not SQL has something like !(fileUnavailable) but works for 1 and 0 because these values are ints in my db.
Pseudo:
INSERT INTO table (fileAvailable) VALUES ( NOT($fileUnavailable));

Use a hint with ABS:
UPDATE table SET field = ABS(field - 1)
So if field is 1, then field - 1 is 0, abs(0) is still 0.
And if field is 0, then field - 1 is -1, abs(-1) is 1.
ABS() man page.
For query you provided in a question:
INSERT INTO table (fileAvailable) VALUES ( ABS($fileUnavailable - 1) );

I found this from another stack overflow question.
INSERT INTO `table` SET `my_bool` = NOT my_bool
Update a boolean to its opposite in SQL without using a SELECT

Related

Return BLOB column Which is Empty Or Not Empty as 1 or 0

I have a table with BLOB column that some row has BLOB, some empty.
1 Apple BLOB-8KiB
2 Banana
3 Pear BLOB-6KiB
4 Orange BLOB-7KiB
Is there any way I can use PHP MYSQL to get the array like this:
$fruit = array(
array("1",Apple,1),
array("2",Banana,0),
array("3",Pear,1),
array("4",Orange,1)
);
I just want to change the BLOB data with 1, Empty with 0 in my PHP array. Pls help.
Your select statement can use IF and ISNULL (note these are not widely implemented in the same format on different database backends, this is for MySQL).
So you would use:
SELECT ID, Name, IF(ISNULL(BlobField), 0, 1) FROM TableName
IF allows you to choose one of two values according to a logical operation.
ISNULL returns true or false according to whether or not the value is NULL

MySQL Query - replace or remove 0 (zero) in a column, but not remove the digit zero in a word or number?

I have a table where one column has 0 for a value. The problem is that my page that fetches this data show's the 0.
I'd like to remove the 0 value, but only if it's a single 0. And not remove the 0 if it's in a word or a numeric number like 10, 1990, 2006, and etc.
I'd like to see if you guys can offer a SQL Query that would do that?
I was thinking of using the following query, but I think it will remove any 0 within a word or numeric data.
update phpbb_tree set member_born = replace(member_born, '0', '')
Hopefully you guys can suggest another method? Thanks in advance...
After discussed at the comments you have said that you want to not show 0 values when you fetching the data. The solution is simple and should be like this.
lets supposed that you have make your query and fetch the data with a $row variable.
if($row['born_year'] == '0'){
$born_year = "";
} else {
$born_year = $row['born_year'];
}
Another solution is by filtering the query from the begging
select * from table where born_year !='0';
update
if you want to remove all the 0 values from your tables you can do it in this way. Consider making a backup before.
update table set column='' where column='0';
if the value is int change column='0' to column=0

Laravel Form $request input value of 0 turns NULL while trying to update

I have a Laravel Form with a input field percentage (defined as $table->decimal('percent', 5, 2);).
If user enter values like 1 , 2, 2.04, 8.97, 100.00, 88.00. everything goes thru.
Even when user enters 0.00 everything updates properly.
but when user enters 0, before updating the record it fails as that 0 (actually it is '0' string) is turned into null in the SQL that is being executed and because field is non null-able it gives me SQL error.
Is this expected or am I missing something here?
Thanks,
K
Try to use isnull check
isnull(value,0) as value
or
coalesce(value, 0) as value;
in your sql query.

PDO Sqlite General error: 25 bind or column index out of range

Read some relevant questions here, here and here. A simple query still triggers an error
SQLSTATE[HY000]: General error: 25 bind or column index out of range
The $query
INSERT OR IGNORE INTO `menu` (`id`,`name`,`name_clean`,`display`) VALUES (:idInsert,:nameInsert,:name_cleanInsert,:displayInsert);
UPDATE `menu` SET id=:idUpdate,name=:nameUpdate,name_clean=:name_cleanUpdate,display=:displayUpdate WHERE id = 1;
';
The $values
[:idInsert] => 1
[:idUpdate] => 1
[:nameInsert] => 2
[:nameUpdate] => 2
[:name_cleanInsert] => 3
[:name_cleanUpdate] => 3
[:displayInsert] => 1
[:displayUpdate] => 1
The snippet. $this->db->handle is the DB handle. As stated in one of the references above, I have implemented the setAttribute(\PDO::ATTR_EMULATE_PREPARES, true) to be able to execute multiple queries
$statement = $this->db->handle->prepare($query);
$statement->execute($values);
Fighting with this one for hours and feels like I am running circles. What am I missing here?
Update
Table definition as required
DROP TABLE IF EXISTS `menu`;
CREATE TABLE `menu` (`id` INTEGER PRIMARY KEY NOT NULL ,`name` VARCHAR,`name_clean` VARCHAR,`sequence` INTEGER, `display` INTEGER);
I think you're running into this:
The keys from input_parameters must match the ones declared in the SQL. Before PHP 5.2.0 this was silently ignored.
Reference: PHP: PDOStatement::execute
My guess is that PHP tries to match the parameters on each of the two queries.
Your input and update parameters look the same, so I don't think there is a requirement to have the two sets. Try collapsing them into one set
[:id] => 1
[:name] => 2
[:name_clean] => 3
[:display] => 1
and referencing them in both queries.
Another note: are you sure you want
WHERE id = 1
This should probably also be
WHERE id=:id
The issue is that PDO wants to bind 8 values to 4 params in the first query split by the ";".
Seeing you SQL code (and your added database structure) I would change it to something like:
INSERT INTO menu (id, name, name_clean, display) VALUES
(
:idInsert, :nameInsert, :name_cleanInsert, :displayInsert
)
ON DUPLICATE KEY UPDATE
id = VALUES(:idUpdate),
name = VALUES(:nameUpdate),
name_clean = VALUES(:name_cleanUpdate),
display = VALUES(:displayUpdate);
This is written by hand, might contain syntax errors.

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

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`');

Categories