views:

441

answers:

2

Hi, guys!

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.

A: 

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)) {
        ...
}
Tim Sylvester
+1  A: 

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.

acrosman
Thanks for your reply. I tried the first option and it returns something like:NothingNothingNothingNothing... Contains letter A... NothingNothing... That's why I wanted to separate my sql part and get somehow (if it's possible) one string with first letters. After that try to check if that string has certain letters like: if (preg_match ('/A/i', $value)) { ... if (preg_match ('/B/i', $value)) { ...