[英]Specifying conditions on database results to array
In my database I have a field called "modules" - info data looks like this: 1, 4, 1, 3 I want to list/output all data via PHP with the numbers 1 - all other numbers have to be ignored. 在我的数据库中,我有一个名为“modules”的字段 - 信息数据如下所示:1,4,1,3我想通过PHP列出/输出所有数据,数字为1 - 所有其他数字都必须被忽略。
I want to check the output result via an array NOT via mySQL 我想通过数组NOT通过mySQL检查输出结果
Any suggestion how I can do that? 有什么建议我怎么做?
$list_modules = array();
$res_m = $db->Execute("SELECT modules FROM users u WHERE user_id = '".$user->id."'");
while ( $m = $res_m->GetNext() ) {
$list_modules = array($m['modules']);
}
print_r($list_modules); //Output below
Example (Output): 示例(输出):
Array
(
[0] => 1, 4, 1, 3
)
You can do that in you MySQL with a WHERE
clause. 您可以使用WHERE
子句在MySQL中执行此操作。 Depending on the column name in the database: 根据数据库中的列名称:
SELECT column_name FROM table WHERE column_name = 1;
Note: In your question it looks like you tried to list a range: 注意:在您的问题中,您似乎尝试列出范围:
with the numbers 1 - all other numbers have to be ignored. 数字1 - 所有其他数字必须被忽略。
If you meant to put a range (eg 1 - 4) then your WHERE clause would be: 如果您打算放置一个范围 (例如1 - 4),那么您的WHERE子句将是:
WHERE column_name BETWEEN 1 AND 4
You should test for that in your MySQL query: 您应该在MySQL查询中测试它:
SELECT * FROM `TABLE` WHERE `modules` = 1;
Or, alternatively, if that's not possible.. 或者,如果那是不可能的话......
Loop with foreach and test for 1? 用foreach循环并测试1?
$array = array(1,4,1,3);
foreach ($array as $element) {
if ($element == 1) { echo 1; }
}
You stated in your comment that the modules
field contains comma-separated values, is that right? 您在评论中声明modules
字段包含以逗号分隔的值,是吗? I reckon that the modules
field is VARCHAR
, CHAR
, or any other string. 我估计modules
字段是VARCHAR
, CHAR
或任何其他字符串。 If so, you could use a query like: 如果是这样,您可以使用如下查询:
SELECT * FROM `tableName` WHERE `modules` LIKE '%1,%';
There may be other solutions, probably more optimal, but this one should perform well, I think. 可能有其他解决方案,可能更优化,但我认为这个应该表现良好。
This should do it... there is really no other way seeing at the col is Varchar, you also need to eliminate strings like 15, 21, etc. so %1% will not work. 这应该这样做......真的没有其他方式在col上看到Varchar,你还需要消除15,21等字符串,所以%1%不起作用。
SELECT modules FROM users WHERE user_id = ".$user->id." AND modules LIKE % 1,%
Give it a shot and let me know if it works. 试一试,让我知道它是否有效。
Meh found the solution I could use. Meh找到了我可以使用的解决方案。
$list_modules = array();
$query = "SELECT modules FROM users WHERE user_id = ".$user->id."";
$res_m = $db->Execute($query);
while ( $m = $res_m->GetNext() ) {
$list_modules = array('id' => $m['modules']);
}
$modules = explode(",",$list_modules['id']);
foreach ($modules as $key => $value) {
if($value == 1){
// list data
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.