Page 1 of 1

Help with calling data

Posted: Thu Apr 09, 2009 11:38 am
by unkempt
Hi - i am new to php, so excuse me if I'm being stupid.... but could you help with the following....

OK, so i want to grab data from a database, based on several criteria, say haircolor, eyecolor, gender, height

I am passing an object array to php "$data" as follows....

Code: Select all

public function myFunction($data){
//
}
The $data array could have all criteria, but most likely one or two, let' say i am passing the following only

haircolor = brown
gender = female

so... to my problem... i want to check through the $data and then SELECT * FROM myTable WHERE haircolor = brown AND gender = female

but my $data array may have many more fields etc

so can i do something like...

Code: Select all

foreach($data as $field => $value) {
//
}
so the SELECT FROM works with any amount of data??

This is what i usually do...

Code: Select all

public function getSomething($live,$name)
    {
        $result = mysql_query(sprintf("SELECT * FROM myTable WHERE live = '%s' AND name = '%s';", $live, $name));
        $t = array();
        
        while($row = mysql_fetch_assoc($result))
        {
            array_push($t, $row);
        }
        
        return $t;
    }
Your help would be much appreciated
Thanks

Re: Help with calling data

Posted: Thu Apr 09, 2009 1:09 pm
by nyoka
How about something similar to this:

Code: Select all

$data = array(
"name" => "abc",
"company" => "xyz"
);
$sql = "SELECT * FROM myTable WHERE ";
foreach ($data AS $key => $value)
    $sql .= "$key = '$value' AND ";
$sql = substr($sql, 0, -5);
$result = mysql_query($sql);
$t = array();
while($row = mysql_fetch_assoc($result))
{
    array_push($t, $row);
}

Re: Help with calling data

Posted: Thu Apr 09, 2009 4:00 pm
by unkempt
Thanks for your reply,
ok so i tried that exactly as you supplied, but it brings me every row in the table.

Any ideas??

Code: Select all

public function getVaried($data)
    {
        $sql = "SELECT * FROM testTable WHERE ";
        foreach ($data AS $key => $value)
            $sql .= "$key = '$value' AND ";
        $sql = substr($sql, 0, -5);
        $result = mysql_query($sql);
        $t = array();
        while($row = mysql_fetch_assoc($result))
        {
            array_push($t, $row);
        }
        return $t;
    }
$data is passed via flash and is set up as follows

Code: Select all

var mydata:Array = new Array();
mydata["id"] = 1;
mydata["name"] = "Name1";

Re: Help with calling data

Posted: Fri Apr 10, 2009 11:08 am
by nyoka
It will bring you every record that matches the criteria passed via the variable data. Can you show me an example of your database data and what is being passed as the variable data?