Reputation: 13
$sql = "select id from table_name ";
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row[id];
}
/* $data contains id's fetched from sql query from db.now i want to pass this id's(array of values) in $data array one by one to below select query in where condition and obtain desired result for each id.My question is how to pass an array of values to the below select statement I dont know how to do this.Any help is greatly appreciated.*/
$query = "select * from table where id1 = $data[] ";
Upvotes: 0
Views: 2289
Reputation: 10241
You should use the cross database function in Moodle called get_in_or_equal()
list($where, $params) = $DB->get_in_or_equal($data, SQL_PARAMS_NAMED);
$sql = "SELECT *
FROM {table}
WHERE $id {$where}"
$records = $DB->get_records_sql($sql, $params);
Upvotes: 1
Reputation: 442
You can use this:
$comma_separated = implode(",", $data);
if ($comma_separated != "")
$query = "select * from table where id1 IN($comma_separated)";
Upvotes: 0
Reputation: 2335
You can use the IN
clause.
When you are totally sure you only have numeric values in your $data
array. You can do the following:
$query = "select * from table where id1 IN(" . implode(',', $data) . ")";
Upvotes: 0
Reputation: 6066
$query = "select * from table where `id1` in (" . implode(', ', $data) . ")";
Upvotes: 1