D
D
Denis2016-09-06 19:14:57
PHP
Denis, 2016-09-06 19:14:57

How to write a SQL query to update a non-existent record?

Hello!
Please tell me how to make a query to the database to add a certain value to the table if its value does not exist.
DB:

CREATE TABLE IF NOT EXISTS `sites` (
`id` int(11) NOT NULL,
  `site_url` varchar(255) NOT NULL,
  `site_size_bytes` int(100) NOT NULL,
  `site_platform` text NOT NULL,
  `site_status` text NOT NULL,
  `site_info_updated` datetime NOT NULL,
  `domain_paid_till` date NOT NULL,
  `additional_domains` text NOT NULL,
  `site_paid_till` date NOT NULL,
  `comment` longtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `sites`
 ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `site_url_2` (`site_url`), ADD UNIQUE KEY `id` (`id`), ADD KEY `site_url` (`site_url`);

ALTER TABLE `sites`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

query:
INSERT IGNORE INTO
    sites (site_url, site_size_bytes, site_platform, site_status, site_info_updated)
VALUES
    ('$val[site_url]', '$val[site_size]', '$val[site_platform]', 'just added', '$current_datetime')

ON DUPLICATE KEY UPDATE
    site_info_updated = '$current_datetime',
    site_size_bytes = '$val[site_size]',
    site_status = 'updated'

The bottom line: if site_url does not match (absent) with what is in the $val[site_url] array , write the empty value to site_status .
Thanks in advance for those who want to help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2016-09-06
@Rsa97

First set all sites in the table `site_status` = 'empty', then populate the data from $val.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question