0

I have the following code:

$sql = "SELECT id,name,type FROM $this->objectsTable WHERE name = $key[Name] AND ( ";
foreach( $key['type'] as $pt=>$val)
    if( count( $key['type'] ) != $pt + 1  )
        $sql .= "type LIKE '%$val%' OR ";
    else
        $sql .= "type LIKE '%$val%')";

In above code $key is an array that contains my values.
I want add this to the above :

If above code has result then update that row else add my data to table as a new row

Note: The $key array has no 'id'.
Is it possible to do that in one query ?
Thanks.

Farhan
  • 96
  • 2
  • 11
  • Take a look here: http://stackoverflow.com/questions/4205181/insert-to-table-or-update-if-exists-mysql –  Mar 12 '15 at 17:28
  • The problem is that in my case there is no id ( in my new data array) . – Farhan Mar 12 '15 at 17:31
  • Please note that $key['Name'] in that context will produce a parse error. It should be $key[Name] (without quotes) – Whirlwind Mar 12 '15 at 17:31
  • I am just curious, why don't you execute two queries where needed? Or change your database and make a unique key and then use - on duplicate key ? – Whirlwind Mar 12 '15 at 17:45
  • @Whirlwind because the $key is a array in another array. And that array conrains 20 or 30 or even maybe 100 arrays or more. Then i decided to do it in one query if is possible. – Farhan Mar 12 '15 at 17:51
  • I think you have to dynamically build update query while iterating through that array. http://stackoverflow.com/a/25674827/3402095 – Whirlwind Mar 12 '15 at 17:54
  • You mean i must store those sub arrays that exist in table in another array and update them separately ? – Farhan Mar 12 '15 at 18:06
  • 1
    Not exactly, you should build one long query based on that array's content. I can't figure out the whole logic, but i think it would be more performant if you run one query for updates if needed. Inserting can be done also using just one query, which is better than multiple query execution. – Whirlwind Mar 12 '15 at 18:31
  • 1
    So, what I said is just related to how to build single query which will update multiple rows (or insert multiple rows) How do you store/get data before building the query is not related to my comment. – Whirlwind Mar 12 '15 at 18:34

0 Answers0