简体   繁体   English

PHP / MySQL:如何仅在满足特定条件时使用 INSERT INTO

[英]PHP / MySQL: How to use INSERT INTO only if certain condition is met

I am new to MySQL and hope someone can help me with this.我是 MySQL 的新手,希望有人能帮我解决这个问题。

I currently use the following as part of a longer statement in PHP in order to write something to a db table which works as intended:我目前使用以下内容作为 PHP 中较长语句的一部分,以便向按预期工作的 db 表写入一些内容:

$stmt = $conn->prepare("INSERT INTO History (email, year, halfYear, language, content) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("siiss", $email, $year, $halfYear, $language, $content);
$stmt->execute();
$result = $stmt->get_result();

How can I check if the corresponding email address ( $email ) already has 3 entries in the db and only write in the db when it has 2 or less entries (otherwise I just want to echo something) ?如何检查相应的电子邮件地址( $email ) 是否已经在数据库中有 3 个条目,并且仅在数据库中有 2 个或更少条目时才写入数据库(否​​则我只想回显一些内容)?

I was thinking I could use something like $result->num_rows but wasn't sure how to apply this here.我想我可以使用类似$result->num_rows东西,但不确定如何在这里应用它。

Can someone help me with this ?有人可以帮我弄这个吗 ?

Many thanks in advance, Mike提前非常感谢,迈克

As per requested by the OP.根据 OP 的要求。

You first need to count the results in a SELECT all set inside a conditional statement.您首先需要计算条件语句内 SELECT all 集合中的结果。

If the query matches the criteria, perform the next one.如果查询符合条件,则执行下一个。

Example using num_rows:使用 num_rows 的示例:

if($result->num_rows == 3){ 

  // do something 
}

else { 
  // do something else 
}

or num_rows >= 3 should you want to check if equal and/or more than 3 also.num_rows >= 3如果您还想检查是否等于和/或大于 3。

Reference:参考:

Sidenote:边注:

Be careful with your use of year it is a MySQL reserved keyword:使用year时要小心,它是 MySQL 的保留关键字:

You can still use it, but just as long as you wrap it in ticks.您仍然可以使用它,但只要您将其包裹在刻度中即可。

Ie: IE:

(email, `year`, halfYear, language, content)

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

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