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粉4019012662024-03-29 09:21:29
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; }
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; }