Madan Gurung Madan Gurung - 1 year ago 53
PHP Question

check if data already exist inside mysql database

i am new in PHP so i am struggling to solve this issue.

here is my code which stores the variable values in specific table rows inside the table "booked".

i want to make sure mysql rejects the insertion of the value inside the database table "booked" if all the variable values already exist inside the database.

note: all the values have to be identical to be rejected. for example: if all the values are identical except for one value, the system should still accept the insertion.

the code i wrote below first checks if the data is already present inside the database. if it is present it echos "data already exists", if not then it inserts the new value inside the database.

however this code doesn't seem to work, so i was wondering if you guys could check my code to see what i am doing wrong?


$servername = "localhost";
$name = "root";
$password = "root";
$dbname = "my computer";

// Create connection
$conn = mysqli_connect($servername, $name, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());

$query = "SELECT * FROM `booked` WHERE

`name` = '{$username}'
`date` = '{$date}'
`computer_id` = '{$select3}'
`start_time` = '{$select1}'
`end_time` = '{$select2}'
`room` = '{$room}'


$result = mysqli_query($conn, $query);

if ( mysqli_num_rows ( $result ) > 1 )

echo "data already exists";


$sql = "INSERT INTO booked (date, computer_id, name, start_time, end_time, room)
VALUES ('$date', '$select3', '$username', '$select1', '$select2', '$room')";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);



Answer Source

Your forgot to put AND keyword inside SQL query. Update your query like this,

$query = "SELECT * FROM `booked` WHERE 
        `name` = '{$username}' AND 
        `date` = '{$date}' AND 
        `computer_id` = '{$select3}' AND 
        `start_time` = '{$select1}' AND 
        `end_time` = '{$select2}' AND 
        `room` = '{$room}'

We used AND here to match all the conditions, if all the conditions are matched only then it will return result.

There is another keyword called OR which is also used in WHERE clause. If OR is applied within two conditions (WHERE column1=1 OR column2=2) either of the condition should match to get the results.

You can also use mix of AND and OR.