开发者

Comparing array in PHP vs SQL database table

I've been thinking for a long time but am not able to come up with an efficient solution. Currently, I have an array in PHP which is obtained by the user. It is an array of objects, and each object have 10 variables.

I need to check if this array matches the data of the S开发者_高级运维QL EXACTLY, meaning that all the variables of each object must match each other. Index doesn't matter.

1) How do I check? Right now the only way I can compare is the number of elements in array vs number of rows in database. If I want to check in-depth, do I really need to check variable by variable? Meaning if i have 10 objects, I need 10*10 variable checks?

2)The only viable solution I can think of is erasing the database table and insert the object one by one according the array, but I'm worried if there is like 100 objects, won't it be too heavy for the sql database?


A relatively primitive way would be:

$fields = array();

$object = new STDClass();
$object->name = "My Name";
$object->status = "My Status";
$object->level = "My Level";

foreach ($object as $key => $value)
 {
   $fields[]="`$key` = '$value'";
  }

$sql = implode(" AND ", $fields);

$query = "SELECT * FROM tablename WHERE $sql"; 

this would generate a query that checks for a row with exactly the values in your object.

How exact this is depends on your table's collation and character set. You can always do a BINARY comparison if you need 100% exact results.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜