简体   繁体   中英

Checking for existence PHP

I'm trying to check for the existence of certain data in the database before performing a function, my code looks like this at the moment. I can't seem to figure this out.

One option you might want to be aware of is an "upsert": Insert a new row (of the column doesn't exist); otherwise, update the existing row:

EXAMPLE:

SET @id = 1,
    @title = 'In Search of Lost Time',
    @author = 'Marcel Proust',
    @year_published = 1913;
INSERT INTO books
    (id, title, author, year_published)
VALUES
    (@id, @title, @author, @year_published)
ON DUPLICATE KEY UPDATE
    title = @title,
    author = @author,
    year_published = @year_published;

Another caveat, since you're updating your database with respect to a PHP (possibly internet-facing) app: ALWAYS use a prepared statement (as opposed to a raw SQL "insert" or "update"):

This will help mitigate SQL injection attacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM