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,137
  • 10
  • 41
  • 66
  • What is the problem now?? – Jenz May 17 '14 at 05:44
  • Why dont you try getting the match list from the query itself b putting a where condition.? – Deepu May 17 '14 at 05:44
  • He is trying to implement linear search. Thats why.. – Jenz May 17 '14 at 05:45
  • Here nothing is happening.If I apply this code like if($list='php') { } this is working.But after using $row["subject_name"],nothing is happening. – Alimon Karim May 17 '14 at 05:46
  • Try to echo `$row["subject_name"]` and check what you are getting. – Jenz May 17 '14 at 05:47
  • 1
    Based on your past comment (hope it was a typo) you need to use `==` and not `=` to perform a comparison. – Fluffeh May 17 '14 at 05:47
  • ops sorry. Here mistake in comment not in my code.I have tried like this $subject=mysql_query('SELECT * FROM subject'); while($row=mysql_fetch_array($subject)) if($list==$row["subject_name"]) { ///execute this } – Alimon Karim May 17 '14 at 05:53

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
  • 32,630
  • 16
  • 65
  • 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
  • 28,589
  • 6
  • 48
  • 86