insert query only if mysql enum value is set to 'Yes' - php

i amn trying to run an insert query to insert the NOW() time and date only if certian enum values in my table are set to yes.
my table has 4 columns 'form1_completed', 'form2_completed', 'form3_completed', 'form4_completed'
the columns will be yes or no.
i am using this query to try and insert the current time and date into the database, its inserting but it doesnt pay attention to the where clause and just inserts anyway, can someone please show me what im doing wrong
$query2 = "IF (SELECT * FROM `supplier_session` WHERE `form1_completed` = 'Yes' AND `form2_completed` = 'Yes' AND `form3_completed` = 'Yes' AND `form4_completed` = 'Yes') INSERT INTO `supplier_session` (`completed_date`) VALUES (NOW());
WHERE `user_IP` = '$ipaddress '";

Instead of
WHERE `form1_completed` = Yes
use
WHERE `form1_completed` = 'Yes'

I think it should be:
IF EXISTS (SELECT * FROM ...) INSERT INTO ...
EXISTS (subquery) is true when the subquery returns any rows.
Or you could do:
IF (SELECT COUNT(*) FROM ...) INSERT INTO ...

Related

MySQL Update activity when selecting user details

Table:
userid, sessionid, last_active
I got the following requests:
SELECT `userid` FROM `session_keys` WHERE `sessionid`='SESSION_ID'
UPDATE `session_keys` SET `last_active`=now() WHERE `sessionid`='SESSION_ID'
Is it possible to put it in one request? but I need the callback from the select request.
The only goal i wanna reach is to update the last_active time of an timestamp when selecting the data.
Thank you.
try:
SET #session_id = 'SESSION_ID';
SELECT `userid` INTO #sid FROM `session_keys` WHERE `sessionid` = #session_id;
UPDATE `session_keys` SET `last_active`=now() WHERE `sessionid` = #session_id;
SELECT #sid;
Could you give more context?
Try this query.
UPDATE
'tableA' AS 'A',
(
SELECT
*
FROM
'tableB'
WHERE
'id' = x
) AS 'src'
SET
'A'.'col1' = 'src'.'col1'
WHERE
'A'.'id' = x
;
Maybe this will be helpful:
Select and Update in same query (I know that you have the same table in both queries)
mysql select and update using one query in this case?

multiple select statement on one column php mysql

Hello i am trying to retrieve a list of records from my database and table using two criterias and the data has to be combined as one
the first statement which i have written is
FROM `transactions` WHERE `Start_Date` = '$_POST[start]' AND `Company` = '$_POST[star]' and Status = ''
this statement all the records which has its column as empty,
now i want to also capture together with this data all columns that have status as successful
FROM `transactions` WHERE `Start_Date` = '$_POST[start]' AND `Company` = '$_POST[star]' and Status = 'successful'
please how do i combine this, i initially tried this
FROM transactions WHERE Start_Date = '$_POST[start]' AND Company = '$_POST[star]' and Status = '' and (status = 'successful')
i thought it should work but it dosent seem to work, any help please on the correct way
Each row in your table will be evaluated individually to see if it meets the criteria defined in the WHERE clause. Since you need to check for two possible values in the same column, and one row cannot have two different values for the same column, you'll need to use OR instead of AND.
WHERE
`Start_Date` = '$_POST[start]'
AND `Company` = '$_POST[star]'
AND (`Status` = '' OR `Status` = 'successful')
The effect of this will be like combining your two queries. You'll get all rows that meet the Start_date and Company criteria as well as having either Status = '' or Status = 'successful'.
You can use "IN" operator to achieve this.
FROM 'transactions'
WHERE 'Start_Date' = '$_POST[start]' AND 'Company' = '$_POST[star]' AND
Status IN ('','successful')

mysql insert record not immediately available, select count(*) doesn't see it right away

In my php code, I have a Mysql query:
SELECT COUNT(*)
to see if the record already exists, then if it doesn't exist I do an:
INSERT INTO <etc>
But if someone hits reload with a second or so, the SELECT COUNT(*) doesn't see the inserted record.
$ssql="SELECT COUNT(*) as counts FROM `points` WHERE `username` LIKE '".$lusername."' AND description LIKE '".$desc."' AND `info` LIKE '".$key."' AND `date` LIKE '".$today."'";
$result = mysql_query($ssql);
$row=mysql_fetch_array($result);
if ($row['counts']==0) // no points for this design before
{
$isql="INSERT INTO `points` (`datetime`,`username`,`ip`,`description`,`points`,`info`, `date`,`uri`) ";
$isql=$isql."VALUES ('".date("Y-m-d H:i:s")."','".$lusername."',";
$isql=$isql."'".$_SERVER['REMOTE_ADDR']."','".$desc."','".$points."',";
$isql=$isql."'".$key."','".$today."','".$_SERVER['REQUEST_URI']."')";
$iresult = mysql_query($isql);
return(true);
}
else
return(false);
I was using MyISAM database type
Instead of running two seperate queries just use REPLACE INTO.
From the documentation:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
For example if your key field is id then:
REPLACE INTO my_table SET id = 4 AND other_field = 'foobar'
will insert if there is no record with id 4, or if there is then it will replace the other_field value with foobar.

Insert data with MAX(id) and values of status at the same time

I was trying with this code but it didn't work. it's always get the MAX(eq_no) as 0
$sql1 =mysqli_query($con, "SELECT MAX(eq_no) AS val FROM tech_add_equip");
$sql2 = "INSERT INTO time (eq_no,status_no) VALUES ('$val', 4 );";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con)); };
Finally, after I try with this code, it inserts in the right number of MAX(eq_no) but i still cant insert the values of status_no
INSERT INTO time (eq_no) SELECT MAX(eq_no) AS vale FROM tech_add_equip
Could you suggest me what did i missing in the code?
Thank you for your helping
One row returned from SELECT a,b,c statement in sub query is equivalent to set of values that is otherwise hardcoded as ('a-value','b-value','c-value')*. You can hardcode a value within select as well:
INSERT INTO time (eq_no, status_no)
SELECT MAX(eq_no), 4
FROM tech_add_equip
No need for aliases within select - order of columns matters.
*) One row result can be used for IN() clause. Another row would become set of values after comma - can't be uset for IN(), but it works ok for INSERT
('row1-a-value', 'row1-b-value'), ('row2-a-value', 'row2-b-value')
$max = SELECT MAX( customer_id ) FROM customers;
INSERT INTO customers( customer_id, statusno )
VALUES ($max , 4)

Count rows in one table within a IF statement

Is it possible to check if num rows in a table is 0 then perform an insert, all in ONE sql statement?
Here's my query that I tried but it says I have a syntax error:
$query =
"IF (SELECT COUNT(ID) FROM votes WHERE userid = $userid AND itemid = $itemid AND itemtype=1) = 0
INSERT INTO votes (itemtype, itemid, userid) VALUES (1, $itemid, $userid)
SELECT 1 AS result
ELSE
SELECT 0 AS result
END IF";
I know the SELECT COUNT bit works successfully on its own.
NO IDEA if this is the best way of solving this, but it will work. Basically, it simply causes an error if the condition is false, and so it prevents insert:
-- make itemtype not nullable then simply insert
INSERT INTO votes SELECT
CASE
WHEN
(SELECT COUNT(ID)
FROM votes
WHERE userid = $userid AND itemid = $itemid AND itemtype=1) = 0 THEN 1
ELSE NULL
END CASE,
$itemid, $userid;
I don't have access to MySQL to test this right now, but would this work?
INSERT INTO votes (itemtype, itemid, userid)
(SELECT 1,$itemid, $userid
WHERE NOT EXISTS (
SELECT *
FROM votes
WHERE itemtype=1
AND itemid=$itemid
AND userid=$userid))

Categories