Petkun
Petkun

Reputation:

SQL query and preg_match

Need your help with sql query and php.

I have to pieces of code here:
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...

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.

Upvotes: 1

Views: 7815

Answers (2)

acrosman
acrosman

Reputation: 12900

Two options come to mind: Do what you're doing now, or re-write the SQL to do both at once.

Option 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:

$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.

Upvotes: 1

Tim Sylvester
Tim Sylvester

Reputation: 23138

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)) {
        ...
}

Upvotes: 0

Related Questions