loop through query string

Trying to read through this query string to get a list of subjects (sub) and products (pro)

sub2=pro73&sub2=pro76&sub2=pro79&sub2=pro90&sub2=pro92&sub3=pro73&sub3=pro74&sub3=pro87&sub3=pro90

so i need

2 -73, 2-76, 2-79, 3-73, 3-74 etc.

What am i missing in this code.

    foreach($_POST as $key => $val) {
            $sub = substr($key, 3);
            $pro = substr($val, 3);

            // $links = "SELECT * FROM table WHERE sub='".$sub."' AND pro='".$pro."';";

    }

You are only going to get the last one. You are repeatedly overwriting sub2 and sub3 in the query string. You can use the same key names over and over again. You need to POST an array, not use GET.

How about telling us about the real problem instead of asking about your attempted solution to it. What is the high level overview of what you have going on.

Basically my form variables get sent via an ajax query (post).

sub2=pro73&sub2=pro76&sub2=pro79&sub3=pro73&sub3=pro74

I need to query the database to find a match for each of the posted form fields.

so using the query string it would be;
WHERE subject=2 AND product=73
WHERE subject=2 AND product=76
WHERE subject=2 AND product=79
WHERE subject=3 AND product=73
WHERE subject=2 AND product=74

and so on.

Show your form and ajax code.

Its okay I’ve changed the form so the varables are unique

Well just based off first example you can build array of conditions then implode to query. Just saying…

$pre_search_conditions = array(); 
foreach($_POST as $key => $val){
	$sub = substr($key, 3);
	$pro = substr($val, 3);	 
	$pre_search_conditions[] = "sub='".$sub."' AND pro='".$pro."'";	 
}	

if(!empty($pre_search_conditions)):
	$links = "SELECT * FROM table WHERE ".implode(" OR ",$pre_search_conditions);
endif;

I dont know why the query string would be formatted that way, it seems rather cumbersome. that beign said, I recommend the following:

        $or = $where ='';
	    foreach($_POST as $key => $val) {
            if (substr($key, 0,3) !='sub') { continue;}
            $data[]= substr($key, 3);
            $data[]= substr($val, 3);
            $where. ="$or( sub = ? AND pro = ?)";
            if (!$or && $where) { $or = ' OR ' ; }
         }
         $sql = "SELECT * FROM table WHERE '. $where
         // USE PDO-> exec($data) to query the DB


Hope that helps. also DO USE PDO, never trust user input.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.