如果不存在则插入到 MYSQL 数据库中

编程入门 行业动态 更新时间:2024-10-26 06:33:05
本文介绍了如果不存在则插入到 MYSQL 数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将客户添加到我创建的 MySQL 数据库中.每当有人在网上商店订购商品时,客户就会被添加到数据库中(我不想重复).这是我的php代码:

I'm trying to add a customer to the MySQL database I created. Whenever somebody orders an item on the online store, the customer is added to the database (I dont want duplicates). Here is my php code:

$sqlInsert = "INSERT INTO Customers (FirstName, Address, Phone) VALUES (".$userName.",".$address.",".$phone.")"; if(mysqli_query($conn, $sqlInsert)) { echo "new member registered successfully!"; } else { echo "Error: " . $sqlInsert . "<br>" . $mysqli_error($conn); }

我研究了诸如 INSERT INTO... WHERE NOT EXISTS 之类的查询.但我不明白我的情况的语法,也不知道它是否有效.这是我的 MYSQL 客户表代码:

I have looked into queries such as INSERT INTO... WHERE NOT EXISTS. But I don't understand the syntax for my case, and don't know if it would work. here is my MYSQL customer table code:

CREATE TABLE IF NOT EXISTS Customers ( PersonID INT(11) NOT NULL AUTO_INCREMENT, Email VARCHAR(100), FirstName VARCHAR(100) NOT NULL, LastName VARCHAR(100), City VARCHAR(90), Zip INT(10), CustomerState VARCHAR(50), Address VARCHAR(200), Country VARCHAR(20), Phone VARCHAR(50) NOT NULL, PRIMARY KEY (PersonID) );

推荐答案

INSERT INTO Customers (FirstName, Address, Phone) SELECT * FROM (SELECT '$firstName', '$address', '$phone') AS tmp WHERE NOT EXISTS ( SELECT FirstName from Customers WHERE FirstName= '$firstName' ) LIMIT 1;

这将防止基于名字,您可以使用所有这些列进行检查,我假设匹配的列应该是电子邮件,您可以使用它.

This will prevent based on the first name, you may use all these columns for checking, I assume the matching column should be email, you can use that.

我只是在查询中添加了参数给你一个想法,使用参数绑定来避免sql注入.

select * from customers where .... //

获取结果集的大小,如果size >0 表示已经有一行了,所以不要插入.

Get the size of result set and if size > 0 that means there is a row already, so do not insert it.

Sql 语句取自 MySQL:如果表中不存在则插入记录 和修改.

Sql statement taken from MySQL: Insert record if not exists in table and modified.

更多推荐

如果不存在则插入到 MYSQL 数据库中

本文发布于:2023-10-19 18:15:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   数据库中   MYSQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!