I have a query as follows :
$q1 = "
SELECT
*
FROM
tbl_profile
WHERE
admin_selected = 'y'
";
$res1 = mysql_query($q1);
$r1 = mysql_fetch_object($res1);
//print_r($r1);
$q2 = "
SELECT
*
FROM
tbl_profile
WHERE
admin_selected = 'n'
";
$res2 = mysql_query($q2);
$r2 = mysql_fetch_object($res2);
//print_r($r2);
?>
Now I want to add the two results $r1 and $r2 into a single array of object say $r. How can I do that ?
Why would you like to split it into 2 query statements? You can do it in just one statement.
SELECT * FROM tbl_profile WHERE admin_selected = 'y' OR admin_selected = 'n'
The fetch function will produce an array that holds values of both admin_selected.
you can user following
array_merge($r1,$r2)
Related
I have an associative array like
$where = array('name'=>'name','comp'=>'companyname')
This is my query
select * from tablename where = $where;
And i want to make a mysqli query generate
select * from tablename where name = 'name' and comp = 'companyname';
echo "select * from tablename where ".implode(' AND ' , preg_replace('/^(.*)$/e', ' "$1=\'". $where["$1"]."\'" ',array_flip($where)));
Try this. I set the conditions in a string and appended the string onto the end of the query. If you set the WHERE to be 1=1 +'yourstuff', you can build the query dynamically.
$queryappnd = '';
foreach($where as $i){
$column = array_key($i);
$value = $i;
$queryappnd .='AND'.$column.'='.$value;
}
$query = "SELECT *
FROM tablename
WHERE 1=1".$queryappnd;
I got an array of ids that I want to use inside an IN statement (sql). However this can only be done when it is written correctly, for example: IN ('12', '13', '14')
How can I change an array of ids into that format? This means adding quotes around every number, and after every number surrounded by quotes a comma, except for the last one in the array.
My code:
$parent = "SELECT * FROM `web_categories` WHERE `parent_id` = 13 AND published = 1";
$parentcon = $conn->query($parent);
$parentcr = array();
while ($parentcr[] = $parentcon->fetch_array());
foreach($parentcr as $parentid){
if($parentid['id'] != ''){
$parentoverzicht .= "".$parentid['id']."";
}
}
I later want to use it like this:
$project = "SELECT * FROM `web_content` WHERE `catid` IN ('".$parentoverzicht."') AND state = 1";
Do this as a single query! SQL engines have all sorts of optimizations for working with tables, and doing the looping in your code is usually way more expensive.
The obvious query for your purposes would be:
SELECT wc.*
FROM web_content wc
WHERE wc.catid IN (SELECT cat.id
FROM web_categories cat
WHERE cat.parent_id = 13 AND cat.published = 1
) AND
wc.state = 1;
Use implode()..
<?php
$a1 = array("1","2","3");
$a2 = array("a");
$a3 = array();
echo "a1 is: '".implode("','",$a1)."'<br>";
echo "a2 is: '".implode("','",$a2)."'<br>";
echo "a3 is: '".implode("','",$a3)."'<br>";
?>
output->>>>>>>
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''
Have you tried to implode()?
Use ", " as glue. You will have to edit the string yourself to add a " at the beginning and end.
More info: http://php.net/manual/en/function.implode.php
Alternatively you can use single join query, like this.
SELECT con.* FROM `web_content` as con LEFT JOIN `web_categories` as cat
ON con.catid=cat.id WHERE cat.parent_id=13 AND published = 1
If the column's type in the DB is integer you do not actually need to quote the values, but in case it isn't, you can use array_map to quote every item in the array, then implode to join them with commas:
<?php
$ids = [1, 2, 3, 4, 5];
$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$in_clause = array_map(function ($key) {
return "'$key'";
}, $ids);
$sql = str_replace('?', implode(',', $in_clause), $sql);
echo $sql;
Result:
SELECT * from mytable where id in ('1','2','3','4','5')
You can do something like this:
$ids = ['1','2','3','4']; //array of id's
$newArr = array(); //empty array..
foreach($ids as $ids)
{
$newArr[] = "'".$ids."'"; //push id into new array after adding single qoutes
}
$project = "SELECT * FROM `web_content` WHERE `catid` IN (".implode(',',$newArr).") AND state = 1"; /// implode new array with commaa.
echo $project;
This will give you :
SELECT * FROM `web_content` WHERE `catid` IN ('1','2','3','4') AND state = 1
$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[] ";
$query = "select * from table where `id1` in (" . implode(', ', $data) . ")";
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);
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) . ")";
You can use this:
$comma_separated = implode(",", $data);
if ($comma_separated != "")
$query = "select * from table where id1 IN($comma_separated)";
I want to use the result set of a query in the where statement of a subsequent query.
Running into a problem because the first query returns multiple results and I don't know how to convert these to a comma-separated string for use in an 'IN' () statement.
$Result1 = mysql_query ("
select id from Table1
where
upper('$Input') = Employee_number
")
or die(mysql_error());
$Result2 = mysql_query ("
Select * from table2 where ID in ($Result1)")
You can combine this into a single MySQL statement like this:
SELECT * FROM Table2 WHERE id IN
(SELECT id FROM Table1 where upper('$Input') = Employee_number);
But if you really want to do it like in your question, you will probably have to lookup how to work with the results from mysql_query, just look that up in a function reference.
$query1 = mysql_query("
select id from Table1
where upper('$Input') = Employee_number
") or die(mysql_error());
$ids = array();
while($Result1 = mysql_fetch_array($query1))
{
$ids[] = $Result1['id'];
}
if(sizeof($ids))
{
$n_ids = implode(',', $ids);
$query2 = mysql_query("
select * from Table2
where ID IN (" . $n_ids . ")
") or die(mysql_error());
}
I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.
Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
Any help would be greatly appreciated, thanks!
You want IN.
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
So the code changes to:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.
Use the SQL IN operator like so:
// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
$instr .= $friend['member_id'].',';
}
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");
$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
}
substr($query, -3);
$result = mysql_query($query);