August 25, 2013
How would you check if a row has x of the same value before adding to a table?
Zach Godin’s Question:
Basically I want to limit four of the same dates to the Date row of my table, and return an error if someone tries to pick a date that already has four instances. How would you check for this before querying the form results to a table?
Since you are allowing duplicated 4 times, you cannot define a unique index. You have to query to get the number of rows. Like
SELECT COUNT(*) FROM yourtable WHERE dDate = 'xxxx-xx-xx'
After you query with similar you can check the number of rows it returns and then only send the query again.
Simple example of this code
// Create a connection like this
$db = new mysql("localhost", "yourusernaem", "yourpassword", "yourdatabasename");
// Prepare your query like this
$stmt= $db -> prepare("SELECT COUNT(*) FROM yourtable WHERE dDate = 'xxxx-xx-xx'");
// ^ I am omiting
the bind param
here
//Execute the query
$stmt -> execute();
$result = $stmt -> bindResult($totalDate);
while($stml -> fetch()) {
if($totalDate == 4) {
//Do not entere
} else {
// Insert Statement and query it
}
}