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
    }
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!