简体   繁体   中英

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.

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:

$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) ?

I was thinking I could use something like $result->num_rows but wasn't sure how to apply this here.

Can someone help me with this ?

Many thanks in advance, Mike

As per requested by the OP.

You first need to count the results in a SELECT all set inside a conditional statement.

If the query matches the criteria, perform the next one.

Example using 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.

Reference:

Sidenote:

Be careful with your use of year it is a MySQL reserved keyword:

You can still use it, but just as long as you wrap it in ticks.

Ie:

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

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