php mySQL是检查行是否与对象类匹配的可靠方法
我正在寻找一种可靠的方法来检查数据库条目是否与php中的等效对象类匹配 我目前的方法不可靠,我希望有人能提供更好的解决方案 我目前的解决方案似乎大部分时间都有效,但在大约600个条目中,我会随机返回大约5个误报条目 下面是我使用的一个简化的对象类php mySQL是检查行是否与对象类匹配的可靠方法,mysql,sql,database,Mysql,Sql,Database,我正在寻找一种可靠的方法来检查数据库条目是否与php中的等效对象类匹配 我目前的方法不可靠,我希望有人能提供更好的解决方案 我目前的解决方案似乎大部分时间都有效,但在大约600个条目中,我会随机返回大约5个误报条目 下面是我使用的一个简化的对象类 class MemberData { public $AccountID; public $AccountName; public $Website; } 然后,我使用反射遍历类中的每个属性,并以以下形式构建查询字符串
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
}
使用
select AccountID
而不是select 1
,并在while
循环中打印出来,这样您就可以看到哪些行导致了误报。我从对象类和数据库并排打印出了误报的所有数据,而且数据似乎与数据库完全匹配。那么,如果数据匹配,为什么会是假阳性?它报告它们不匹配…假阴性?addslashes()
escapes“单引号(')、双引号(“)、反斜杠()和NUL(空字节)。”,mmysqli\u real\u escape\u string()
escapes“NUL(ASCII 0)”,\n、\r、\,“,和Control-Z”功能上的细微差别向我建议,您可能需要使用为转义提供的实际工具。