简体   繁体   English

如果不存在,则将多个值插入表 MySQL

[英]Insert Multiple Value into table MySQL if not exists

I have a table with 3 columns (ID, username, full name), I want the ID to be AUTOINCREMENT.我有一个包含 3 列(ID、用户名、全名)的表,我希望 ID 为 AUTOINCREMENT。 I want to insert into the table only if it does not already exist in the table.只有当表中不存在时,我才想插入到表中。

This is my Code:这是我的代码:

$fullName = $_POST['fullname'];
$username = $_POST['username'];
$dbhost = "localhost";
  $dbname = "databasename";
  $dbusername = "root";
  $dbpassword = "";

  $link = new PDO("mysql:host=$dbhost;dbname=$dbname","$dbusername","");

  $statement = $link->prepare('INSERT INTO accounts (username, fullname)
      VALUES (:username, :fname)');

  $statement->execute([
      'fname' => $fullName,
      'username' => $usernameget,
  ]);

If your id is already autoncrement then you no need to mention in query.如果您的id已经是 autoncrement,那么您无需在查询中提及。

You can simply write below query您可以简单地编写以下查询

insert into accounts (username,fullname) values( $username , $fullname )

There's several things to fix here.这里有几件事需要解决。

  • Don't specify column values if you don't need to, or don't care about the value.如果不需要或不关心值,请不要指定列值。 Only specify if necessary or relevant.必要或相关时指定。 In this case id should be omitted.在这种情况下,应该省略id
  • Always use placeholder values for your user data.始终为您的用户数据使用占位符值。 Never put $_GET or $_POST data directly in a query.切勿$_GET$_POST数据直接放入查询中。
  • To avoid duplication add a UNIQUE constraint on the table.为了避免重复,在表上添加一个UNIQUE约束。

To fix that you do adjust your code:要解决该问题,请调整代码:

// Enable exceptions, avoiding the need for manual error checking
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Try and keep the order of things like this consistent through your code
$username = $_POST['username'];
$fullname = $_POST['fullname'];

// Here using a short, common name for the database handle $db    
$db = new mysqli("localhost","root","","database");

// Prepare your insert first as a query with no data, only placeholders
$db->prepare("insert into accounts (username,fullname) values(?,?)");

// Bind the data to the placeholders, here two string ("s") values.
$db->bind_param('ss', $username, $fullname);

// Execute the query
$db->execute();

To add the UNIQUE constraints useCREATE INDEX :要添加UNIQUE约束,请使用CREATE INDEX

CREATE INDEX idx_accounts_username (username);
CREATE INDEX idx_accounts_full_name (full_name);

That has to be run in your MySQL shell, not PHP.那必须在你的 MySQL shell 中运行,而不是 PHP。

When a UNIQUE constraint is in place MySQL will not allow duplicate data.UNIQUE约束到位时,MySQL 将不允许重复数据。 Note that NULL values don't count, and can be "duplicated".请注意, NULL值不计算在内,可以“复制”。 Set NOT NULL on your columns to force them to be completely unique.在您的列上设置NOT NULL以强制它们完全唯一。

由于您的id是自动增量主键,因此您可以使用以下命令创建或更新它:

insert into accounts (username,fullname) values( $username , $fullname ) on duplicate key update username = '$username',fullname = '$fullname'

you can do this with if else condition in PHP您可以使用 PHP 中的 if else 条件执行此操作

$fullname = $_POST['fullname'];
$username = $_POST['username'];

$chk = mysqli_query("select * FROM `accounts` where fullname='$fullname' and username='$username'");
$rs = mysqli_fetch_array($chk);
if($rs == "")
{
    $ins = mysqli_query("INSERT INTO `accounts`(fullname,username) VALUES ('$fullname','$username'))";
} 
else{
    echo "Duplicate entry";
}   

or you can do this by SQL Query also.或者您也可以通过 SQL 查询来执行此操作。

INSERT INTO accounts(username,fullname)
SELECT * from (SELECT '$username', '$fullname') AS tmp
WHERE NOT EXISTS
(SELECT username FROM accounts WHERE username='$username')

To get correct answers, a question must be asked with as much explanation as possible.为了得到正确的答案,必须尽可能多地解释问题。 you should atleast tell what have you done and then what are you getting.你至少应该告诉你做了什么,然后你得到了什么。
As far as i have understood, to achieve your goal, the table structure must be changed and inserting query also.据我所知,要实现您的目标,必须更改表结构并插入查询。
Remember to accept the answer and click the upvote button if the answer satisfies you,记得接受答案,如果答案让你满意,请点击upvote按钮,
else give more information in the question, so that members here, can give right answers.否则在问题中提供更多信息,以便在这里的成员可以给出正确的答案。

If you understand table creating queries go to bottom of this answer or else do as follows:如果您了解表创建查询,请转到此答案的底部,否则请执行以下操作:
if you use gui to create table,如果您使用 gui 创建表,
1. click on create new table. 1.点击创建新表。

在此处输入图片说明
2. in the right pane give table name and column names as shown. 2. 在右窗格中给出表名和列名,如图所示。 (dont give space in 'full name' instead give 'full_name' or 'fullname') (不要在“全名”中给出空格,而是给出“全名”或“全名”)

在此处输入图片说明 3. scroll the winow to the right till you see A_I column as shown. 3. 向右滚动窗口,直到看到如图所示的 A_I 列。

在此处输入图片说明 4. tick the first line (which we have used as id), 'add index' box will appear. 4. 勾选第一行(我们已用作id),将出现“添加索引”框。
just click here go (at the bottom).只需点击这里(在底部)。
you will be redirected to table list as shown.您将被重定向到表列表,如图所示。

在此处输入图片说明 6. open (click) your table again. 6. 再次打开(单击)您的表。

在此处输入图片说明 7. click on structure. 7.点击结构。
在此处输入图片说明 now suppose you don't want duplicates in 'username' column, click this column and click on 'unique' as shown现在假设您不想在“用户名”列中出现重复项,请单击此列并单击“唯一”,如图所示

在此处输入图片说明 if you don't want duplicate when both the columns' value together, click both the columns and then click 'unique' as shown如果您不想在两列的值在一起时重复,请单击两列,然后单击“唯一”,如图所示

在此处输入图片说明



if you understand create table commands:如果您了解创建表命令:

here is the sql for above: CREATE TABLE accounts ( id int(11) NOT NULL AUTO_INCREMENT, username varchar(25) NOT NULL, fullname varchar(55) NOT NULL, PRIMARY KEY ( id ), UNIQUE KEY username ( username ) ) ENGINE=MyISAM DEFAULT CHARSET=latin1这是上面的 sql:CREATE TABLE accounts ( id int(11) NOT NULL AUTO_INCREMENT, username varchar(25) NOT NULL, fullname varchar(55) NOT NULL, PRIMARY KEY ( id ), UNIQUE KEY username ( username ) ENGINE =MyISAM 默认字符集=latin1


with above table structure records will be autoincremented and duplicate names will not be added.具有上述表结构的记录将自动递增,并且不会添加重复的名称。 (remember to handle duplicate entries error in you inserting querie with (记住在插入查询时处理重复条目错误
INSERT IGNORE INTO插入忽略
with this your query will be:有了这个,您的查询将是:

$statement = $link->prepare('INSERT IGNORE INTO accounts (username, fullname)
      VALUES (:username, :fname)');


or you can also use或者你也可以使用
ON DUPLICATE KEY)在重复密钥上)

First set your primary key (eg. id) if not set as auto increment如果未设置为自动增量,请先设置您的主键(例如 id)

Second use multiple insertion value第二个使用多个插入值

INSERT IGNORE INTO accounts (username,fullname) VALUES ("p","k"),("c","s");

IGNORE keyword is use to duplicate IGNORE 关键字用于复制

IF you want to see with PDO如果你想用PDO 看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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