Does "select exists" still return true in my function?
P粉236743689
P粉236743689 2024-03-28 10:14:58
0
1
449

I slightly modified the Select Exists function I found on stackoverflow, but no matter what I try, my function below always returns $sqlResult as true. Even though I only keep two entries in the database. Is Select exists still valid?

None of the answers suggested by the stackoverflow system answered my question, instead suggesting using a method that checks the number of rows returned instead of using exists. (Or the link they gave doesn't really explain what the exists result represents.)

function uniquedoesexist($dbHandle,$tablename,$fieldname,$value) 
{
    $sql = 'SELECT EXISTS(SELECT * FROM `' . $tablename .
         '` WHERE `'.$fieldname.'` = ? 
            LIMIT 1
    )';
    $stmt = mysqli_prepare($dbHandle, $sql);
    mysqli_stmt_bind_param($stmt, 's',$value);  
    $sqlResult = mysqli_stmt_execute($stmt);

    echo '$sqlResult: ' . $sqlResult.$br;
    return $sqlResult;
}

Use: username Index varchar(255) utf8_german2_ci

I'm sorry for my beginner question. Entries for field names are set to be unique.

P粉236743689
P粉236743689

reply all(1)
P粉401901266

You need to get the query results in the following way:

function uniquedoesexist($dbHandle, $tablename, $fieldname, $value) {
    $sql = 'SELECT EXISTS(SELECT * FROM `'.$tablename.'` WHERE `'.$fieldname.'` = ? LIMIT 1)';
    $stmt = mysqli_prepare($dbHandle, $sql);
    mysqli_stmt_bind_param($stmt, 's',$value);  
    
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $data);
    mysqli_stmt_fetch($stmt);


    echo "SqlResult for $value: " . $data . PHP_EOL;
    return $data;
}

PHP mysqli online test

Another way is to get the number of rows returned instead of using SELECT EXISTS:

<?php

    function uniquedoesexist($dbHandle, $tablename, $fieldname, $value) {
        
        $sql = 'SELECT * FROM `'.$tablename.'` WHERE `'.$fieldname.'` = ? LIMIT 1;';
        $stmt = mysqli_prepare($dbHandle, $sql);
        mysqli_stmt_bind_param($stmt, 's',$value);  
        
        mysqli_stmt_execute($stmt);
        mysqli_stmt_store_result($stmt);
        
        $found = mysqli_stmt_num_rows($stmt);
    
    
        echo "SqlResult for $value: " . $found . PHP_EOL;
        return $found;
    }

PHP mysqli num_rows

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template