-1

I am trying to check three elements are already present in a database. The elements are room, timers and dates. I want to check if what I am entering is already present in the database groom. The below code compares what I am entering with what is already present and if its the same it tells me to enter different data, but if it is not it enters my data. The only problem is that it checks them individually rather than collectively and then it enters my data numerous times up until it notices that my data was in fact present and should not have been entered.

Is it possible to compare my entry with the data already present and then once all the data has been entered decide whether my data can be added rather than adding it every time it gets to if. Hopefully this question comes across clear and thank you in advance!!

 $sql = "SELECT id, room, timers, dates FROM groom"; 
 $result = $conn -> query ($sql);
 if ($result -> num_rows >0){
    while($row = $result -> fetch_assoc()){
        if($room == $row["room"] AND $timers == $row["timers"] AND $dates == $row["dates"] ){
            echo "This booking is not available";
        }else{ 
            //book 
            //here it books every time even though it has not checked all the data above in the if statement
        }
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Steven
  • 15
  • 3

2 Answers2

0

Instead of processing every row in the table and then looking for a match in a PHP IF, get MYSQL to do the heavy lifting for you.

You know what you want to find in the table, so add it to a WHERE clause

$sql = "SELECT id FROM groom WHERE room=? AND timers=? AND dates = ?"; 

$stmt = $conn->prepare($sql);

// you might need to check the data types `sss` are correct for your schema
$stmt->bind_param('sss', $room, $timers, $dates);

$stmt->execute();

if ( $stmt->num_rows > 0 ){
    // we found a row so that stuff already exists
    // you can use the id if you need it
}else{
    //book 
    // Do whatever you were doing here to save this data
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

you can try this

   $sql = "SELECT id, room, timers, dates FROM groom where room = '$room' and  timers ='$timers' and  dates='$dates'"; 
   $result = $conn -> query ($sql);
  if ($result -> num_rows >0){
        echo "This booking is not available";
    }else{ 
        //your alternative code here !
    }
M. Alim
  • 153
  • 16
  • Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Jan 26 '17 at 16:53