tags:

views:

41

answers:

3

Hello,

I have a query $sqlStr4 that "selects" these fields from a MySQL database:

loginid
username
created

The query $sqlStr4 is limited to 10 rows / results.

I also have the following variable:

$u = $_SESSION['username'];

I would like to assign another variable $topten a value of 1 if $u equals any of the ten username fields returned by the query $sqlStr4, and a value of 0 if it does not.

How can I do this?

Thanks in advance,

John

A: 

If you had pasted the query, we'd be able to provide a fixed version. You can do this multiple ways, but one would be to add a column to your query and use a CASE statement.

select *, CASE WHEN username = '$u' THEN 1 ELSE 0 END as topten
from ...

This is just an example.. obviously to prevent SQL injection you should parameterize it, or use mysql_real_escape_string(), or a stored procedure, etc etc...

EDIT: I see you want the variable to be in PHP... so you would need to loop through the array to check each one. What is the problem you're having?...

$topten = 0;
if ($result) {
   while ($record = mysql_fetch_array($result)) {
      if ($record['username'] == $u) $topten = 1;
   }
}
Fosco
A: 

Use:

<?php

$u = $_SESSION['username'];
$topten = 0;

$result = mysql_query($sqlStr4);

while ($row = mysql_fetch_assoc($result)) {
  if ($row['username'] == $u) {
    $topten = 1;
    break;
  }
}

mysql_free_result($result);
?>
OMG Ponies
A: 

Could try something like this...

while ($row = mysql_fetch_assoc($sqlStr4))
{
    $topten = ($u == $row['username']) ? 1 : 0;
    // the rest of your processing code here
}

There may well be better solutions for your situation. Would be easier if you posted some code!

chigley
That will reset the `$topten` value to zero if subsequent records don't match.
OMG Ponies
@OMG - it totally depends on what the OP wants it for. If they're simply checking this, then they can just use `mysql_num_rows()` on a query. I've made the assumption that he wants to loop through and do something with the rows, therefore he'd want the value to be reset each time. A simple `if ($topten) break;` could be added if this check was all the OP wanted to do, but in that case I'd recommend he rethought his query!
chigley