You Kuper
You Kuper

Reputation: 1113

INSERT INTO if condition is satisfied

I need to save the array $solution into the SQL table only if $solution[$i][0] belongs to the result of the query SELECT num_arr FROM Schedule WHERE num_arr<>''. If it does not belong to it, then the row $i must be not saved in the SQL table. The below-provided query seems to be incorrect. How do I implement the described task? What would be the correct approach to do this?

$query_land = "INSERT INTO `Sequence` (`num_arr`,`start`,`fin`,`way_id`) 
               VALUES ('".$solution[$i][0]."','".$solution[$i][1]."',
                                   '".$solution[$i][2]."','".$solution[$i][3]."') 
               WHERE '".$solution[$i][0]."' IN (SELECT num_arr 
                                                FROM Schedule 
                                                WHERE num_arr<>'')";

Upvotes: 1

Views: 778

Answers (1)

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115510

The INSERT statment has two variations:

INSERT INTO tableX
    (a, b, c, ...)
VALUES
    (1, 2, 3, ...) ;

and

INSERT INTO tableX
    (a, b, c, ...)
SELECT
    1, 2, 3
FROM
    ... ;             --- the same or another table or many tables

The dual is a system table with exactly 1 row. It can be used for various things. Here it's used so a VALUES (...) is rewritten as a SELECT ... where we don't have any suitable table to put in the FROM clause:

$query_land = "INSERT INTO `Sequence` (`num_arr`,`start`,`fin`,`way_id`) 
               SELECT '".$solution[$i][0]."','".$solution[$i][1]."',
                      '".$solution[$i][2]."','".$solution[$i][3]."'
               FROM dual 
               WHERE '".$solution[$i][0]."' IN (SELECT num_arr 
                                                FROM Schedule 
                                                WHERE num_arr<>'')";

Upvotes: 5

Related Questions