[英]SQL query and preg_match
Need your help with sql query and php. 需要您的SQL查询和PHP帮助。
I have to pieces of code here: 我必须在这里编写代码:
1. 1。
$sql = "SELECT SUBSTR(n.`title`, 1,1) FROM node n WHERE n.`type` = 'type1'";
$results = db_query($sql);
while ($fields = db_fetch_array($results)) {
foreach($fields as $key => $value) {
echo $value;
}
}
The code above returns first letters of my article titles (table - node, columns - type, title) like this - NHDKFLF... 上面的代码返回我文章标题的首字母(表格-节点,列-类型,标题),就像这样-NHDKFLF ...
2. 2。
if (preg_match ('/A/i', $string)) {
echo ('Contains letter A'); //
}
else {
echo ('Nothing'); //
}
And the second part checks if the string contains certain letters. 第二部分检查字符串是否包含某些字母。
Now, the question is how to combine these two pieces of code? 现在,问题是如何结合这两段代码? I mean how to pull data from DB and check if it has certain letters. 我的意思是如何从数据库中提取数据并检查其是否具有某些字母。
Thanks in advance. 提前致谢。
Two options come to mind: Do what you're doing now, or re-write the SQL to do both at once. 我想到了两个选择:做您现在正在做的事情,或者重新编写SQL以同时做这两个事情。
Option 1: 选项1:
$sql = "SELECT SUBSTR(n.`title`, 1,1) FROM node n WHERE n.`type` = 'type1'";
$results = db_query($sql);
while ($fields = db_fetch_array($results)) {
foreach($fields as $key => $value) {
if (preg_match ('/A/i', $value)) {
echo ('Contains letter A'); //
} else {
echo ('Nothing'); //
}
}
}
Option 2: 选项2:
$sql = "SELECT SUBSTR(n.`title`, 1,1) FROM node n WHERE n.`type` = 'type1' AND SUBSTR(n.`title`, 1,1) = 'A' ";
Depending on the rest of the details of your project there is probably a better way to handle this. 根据项目的其余细节,可能有更好的方法来处理此问题。
Why wouldn't you just query for the ones you want? 您为什么不只是查询想要的?
... where SUBSTR(n.`title`, 1,1) = 'A' ...
If you must filter in your code, outside the query, then: 如果必须在查询之外过滤代码,则:
foreach($fields as $key => $value) {
if (preg_match ('/A/i', $value)) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.