0

My code is big and I can't just pull out few lines to show my problem so I am going to explain it by using imaginary code to simplify it.

Let's say I have to-do list as table and I've defined activity and time. I don't want to have duplicate rows so I created function to prevent it.

function check_date($day, $time) {
include 'db_connect.php';
$sql = "SELECT day, dan FROM todo ";
$sql .= "WHERE day = $day AND time = '{$time}'";

$result = mysqli_query($conn, $sql) or trigger_error(mysqli_error());

if(mysqli_num_rows($result) >= 1) {
    $row = mysqli_fetch_assoc($result);
    return 1;
} else {
    return 0;
}
}

Call on function in main file:

if(check_termin_sala($day, $time)) {
    $errors['busy'] = "You are busy.";
}   

And query:

if(empty($errors) {
    $query = "INSERT INTO todo (";
    $query .= "day, time, activity";
    $query .= ") VALUES (";
    $query .= "'{$day}', '{$time}', '{$activity}')";

    $result = mysqli_query($conn, $query);
    if(!$result) {
        die("Failed." . mysqli_error($conn));
    }
}

Now I want update my row by changing just activity field, but fields day and time are unchanged so when I submit update I get error because exact day and time are already inserted. What should I do to exclude this check function affecting current row date and time?

I hope you will understand me. :)

Boki
  • 1
  • 2
  • 1
    You are kind of reinventing the wheel here, MySQL already has a way to enforce a unique key with multiple columns, it is called a composite key with a unique index. It would be better to run the insert, then trap the error, rather than doing a select before each insert and update. https://stackoverflow.com/questions/635937/how-do-i-specify-unique-constraint-for-multiple-columns-in-mysql – ThatGuyInIT Apr 29 '18 at 01:53
  • @ThatGuyInIT thanks – Boki Apr 30 '18 at 11:59

0 Answers0