我有一个如下所示的 mysql 数据库
+----+----------+---------+----------------------------------+---------------------+
| id | field_id | user_id | value | last_updated |
+----+----------+---------+----------------------------------+---------------------+
| 1 | 1 | 1 | admin | yyyy-mm-dd hh:mm:ss |
| 3 | 5 | 1 | a:1:{i:0;s:2:"18";} | yyyy-mm-dd hh:mm:ss |
| 4 | 1 | 2 | testuser1 | yyyy-mm-dd hh:mm:ss |
| 5 | 5 | 2 | a:2:{i:0;s:2:"19";i:1;s:2:"18";} | yyyy-mm-dd hh:mm:ss |
+----+----------+---------+----------------------------------+---------------------+
我知道普通的 sql 查询不适合,所以我需要将所有数据提取到 php 中,然后对其进行排序。
我想要的是获取任何具有数字的 user_id,例如 field_id
5 中的“19”。在该示例中,数组应读取“2”。或者我可以在 field_id
5 中搜索“18”,数组将返回“1,2”。
为了获取数据库,我使用以下内容
<?php
global $wpdb;
$table_name = $wpdb->prefix . "bp_xprofile_data";
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name" );
$strDB = maybe_unserialize( $retrieve_data);
echo print_r($strDB, true);
?>
返回结果:
Array ( [0] => stdClass Object ( [id] => 1 [field_id] => 1 [user_id] => 1 [value] => admin [last_updated] => 2017-09-21 12:38:20 ) [1] => stdClass Object ( [id] => 3 [field_id] => 5 [user_id] => 1 [value] => a:1:{i:0;s:2:"18";} [last_updated] => 2017-09-21 12:38:20 ) [2] => stdClass Object ( [id] => 4 [field_id] => 1 [user_id] => 2 [value] => testuser1 [last_updated] => 2017-09-23 01:43:50 ) [3] => stdClass Object ( [id] => 5 [field_id] => 5 [user_id] => 2 [value] => a:2:{i:0;s:2:"19";i:1;s:2:"18";} [last_updated] => 2017-09-23 01:43:50 ) )
我不知道如何对这些数据进行排序。我试图找到字符串的各个部分,但这不起作用。
最佳答案
您应该能够在“值”字段上使用 LIKE 比较,例如
SELECT * FROM $table_name AND value LIKE '%9%'
搜索数字的困难在于 LIKE 也会返回部分匹配,因此查询 9 也会返回 19、91、192 等。
但是,根据序列化字符串中双引号包围的值,您应该能够通过在搜索字符串中包含双引号来搜索确切的值,例如“9”
。
将其添加到您问题的代码中,我们得到:
global $wpdb;
$num_to_find = 19; /* or change to whatever number you need */
$field_id_to_check = 5; /* or change to whatever number you need */
$table_name = $wpdb->prefix . "bp_xprofile_data";
$user_ids = $wpdb->get_results(
$wpdb->prepare(
"SELECT user_id FROM $table_name
WHERE field_id = %d AND value LIKE '%%\"%d\"%%'",
$field_id_to_check, /*this param replaces the 1st %d in the query */
$num_to_find /*this param replaces the 2nd %d in the query */
)
);
print_r($user_ids);
注意:因为查询包含一个变量,并且我不知道它来自哪里,所以我使用 $wpdb->prepare 来清理该变量。
这尚未经过测试,但我相信它应该有效!
关于php - 反序列化wordpress数据库来查询数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46405711/