Hi i want to create function:
public function findOneByAttributes($class, $attributes){}
This function will return first result from my query where atributes will be in array. So $attributes
is an array like this:
$data = array(
'id' => 45,
'name' => 'John',
.....
);
I want to build query but i dont know how to create WHERE
condition. I cant use $data['id']
because i dont know what attribute i will need. I want to create it flexibile. So i need to get something like that from array:
SELECT * FROM 'table' WHERE id = 45 AND name = 'John'
Thanks
$where_clausel = " WHERE ";
$start = true;
foreach($data AS key => $value){
if ($start === false){
$where_clausel .= " AND ";
}
$where_clausel .= $key . " = '" . $value . "' ";
$start = false;
}
It should look something like this, but you should use some kind of type casting for checking the id.
another solution
<?php
$data = array(
'id' => 45,
'name' => 'John',
);
$dataCondition = array();
foreach ($data as $key => $value) {
$dataCondition[] = "$key = '$value'";
}
$dataString = implode(" and ", $dataCondition);
$query = "select * from table where $dataString";
echo $query;
enjoy :)