我正在寻找一种可靠的方法来检查数据库条目是否与php中的等效对象类匹配。
我目前的方法不可靠,我希望有人可以提供更好的解决方案。
我目前的解决方案似乎大部分时间都有效,但在大约600个条目中,我会随机返回大约5个误报的条目。
这是一个简化的对象类Im使用
class MemberData
{
public $AccountID;
public $AccountName;
public $Website;
}
然后我使用反射循环遍历类中的每个属性,并以以下形式构建我的查询字符串:
SELECT 1 WHERE `Property1` = value1 AND `Property2` = value2 AND `Property3` = value3
但是就像我提到的那样,我的代码只能在大部分时间内工作,并且我无法确定为什么我会得到误报的常见链接。它似乎是随机的。
以下是我的全部功能。
//Pass in a member class and see if there is a matching database entry
function SqlDoRowValuesMatch($memberData)
{
//declare global vars into this scope
global $host, $user, $password, $dbname, $tableName;
//initiate the connection using mysqli
$databaseConnection = new mysqli($host, $user, $password, $dbname);
if($databaseConnection->connect_errno > 0)
{
die('Unable to connect to database [' . $databaseConnection->connect_error . ']');
}
//Get all the properties in the MemberData Class
//Using Reflection
$reflect = new ReflectionClass($memberData);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
//Build the query string
$sql = "SELECT 1 FROM `".$tableName."` WHERE ";
foreach($props as $prop)
{
if(!is_null($prop->getValue($memberData)))
{
$sql = $sql.$prop->getName()."=".addSingleQuotes(addslashes($prop->getValue($memberData)))." AND ";
}
}
//Cut Trailing operator
$sql = rtrim($sql, " AND ");
if(!$result = $databaseConnection->query($sql))
{
die('There was an error creating [' . $databaseConnection->error . ']');
}
$databaseConnection->close();
//Check for a value of 1 to indicate that a match was found
$rowsMatch = 0;
while($row = $result->fetch_assoc())
{
foreach($row as $key => $value)
{
if($value == 1)
{
$rowsMatch = 1;
break;
}
}
}
return $rowsMatch; //0 = false, 1 = true
}