MySQL Unique test

I am testing for unique page entry in my database. The logic is working. My understanding is not:)

My problem is if the page already exists in the database, then it will also have an id. In the sql query:
$sql .= “AND id != '” . db_escape($db, $current_id) . “’”;
It will search all entries that is not current id, then it will not get a match on menu_name. It will return true from function: has_unique_page_menu_name. This is not happening and I don’t know why?
It seems that the test is working fine even if I omit the AND clause.

If the page does not exist in the database then it will be given default $current_id =0. Because no id is zero it will search thru the complete database. This one is okay.

function validate_page($page){
 $current_id = $page['id'] ?? '0';
    if(!has_unique_page_menu_name($page['menu_name'], $current_id)) {
      $errors[] = "Menu name must be unique.";

function has_unique_page_menu_name($menu_name, $current_id="0") {
    global $db;

    $sql = "SELECT * FROM pages ";
    $sql .= "WHERE menu_name='" . db_escape($db, $menu_name) . "' ";
    $sql .= "AND id != '" . db_escape($db, $current_id) . "'";

    $page_set = mysqli_query($db, $sql);
    $page_count = mysqli_num_rows($page_set);

    return $page_count === 0;

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.