1

I have a table call subject, having a field subject_name. Here I want to match subject_name with a value, which I have get from global GET.

Below shown is the code that I have tried. Here I have get list value from another page.

global $list;
if(isset($_GET['U']))
{
    $list=$_GET['U'];
}

Now for subject_name I have tried below code.

    $subject=mysql_query('SELECT * FROM subject');
    while($row=mysql_fetch_array($subject))
    if($list==$row["subject_name"])
    {
        //execute this
    }

Here how can I match $list value with subject_name list?

Alimon Karim
  • 4,354
  • 10
  • 43
  • 68

2 Answers2

0

If $list is an array which it might well be, you can use an array search like this:

while($row=mysql_fetch_array($subject))
{
    $key=array_search($row["subject_name"], $list);
}

If it isn't then:

while($row=mysql_fetch_array($subject))
{
    if($list==$row["subject_name"])
    {
    //execute this
    }
}
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
0

If you do not need rows not matching your filter array later in your script, then your should filter your results at query time (in SQL):

Below example provided for eduction purpose only. DO NOT USE IN PRODUCTION!

<?php

mysql_query('SELECT * FROM subject WHERE subject_name IN ("' . implode('","', $list) . ')');

... which produces a query like this :

SELECT * FROM subject WHERE subject_name IN ("subjectA", "subjectB"...)

Usual piece of advice:

  1. your code (as well as mine above) is begging for SQL injection, do not use it in a publicly accessible application
  2. do not use the obsolete mysql_* functions.

Here is a nice and safe solution with PDO prepared statements.

Community
  • 1
  • 1
RandomSeed
  • 29,301
  • 6
  • 52
  • 87