passing array of values in sql select statement of where condition - php

$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)";

Related

Return all rows from an array

I'm trying to return a comma separated list of location names from a database.
So far I have the SQL statement that I know works because it returns the correct results when tested in phpMyAdmin.
I'm now trying to get the results returned and printed on screen in php.
The code I have bellow only seems to return the first result.
$sql = "SELECT user_locations.location_id, location.name AS LocName FROM user_locations INNER JOIN location ON user_locations.location_id=location.id WHERE user_id = '" . $id . "'";
$query = mysqli_query($conn, $sql);
while ($row = $query->fetch_assoc()) {
$array[] = $row['LocName'];
$comma_separated = implode(",", $array);
return $comma_separated;
}
You need to remove the implode and return outside your while loop, otherwise your loop will stop after the first value:
$sql = "SELECT user_locations.location_id, location.name AS LocName
FROM user_locations
INNER JOIN location ON user_locations.location_id=location.id
WHERE user_id = '" . $id . "'";
$query = mysqli_query($conn, $sql);
while ($row = $query->fetch_assoc()) {
$array[] = $row['LocName'];
}
$comma_separated = implode(",", $array);
return $comma_separated;
Note that you can achieve this result directly in your query using GROUP_CONCAT:
$sql = "SELECT GROUP_CONCAT(location.name) AS LocName
FROM user_locations
INNER JOIN location ON user_locations.location_id=location.id
WHERE user_id = '" . $id . "'";
$query = mysqli_query($conn, $sql);
$row = $query->fetch_assoc();
$comma_separated = $row['LocName'];
return $comma_separated;
Note that dependent on the source of your $id value, you may need to look into prepared statements to protect yourself from SQL injection.

Unable to get key value from a mysql multi-dimensional array

I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}

PHP Mysqli trigger a query one after other

I am trying to fetch first id from one table and later after all the ids are fetched i am trying to fetch number of all that id's.
My Problem is
As i want to select the value of first query completion result
I am unable to trigger second query after the first query is completed both are triggerid at a time
First Query
$query ="SELECT * FROM abc WHERE xyz='xyz' And Standard='xyz' ";
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
$ID = array();
while($row=mysqli_fetch_array($data)){
$ID[] = $row['ID'];
}
$IDall = "'" . implode("','", $ID) . "'";
Second Query
$query="SELECT mobno FROM euser WHERE UserId IN ($IDall)" ;
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
$mobiles = array();
while($row=mysqli_fetch_array($data)){
$mobiles[] = $row['MobileNum'];
}
$mobilesStr = implode(',', $mobiles);
echo $mobilesStr;
}
Try this
SELECT mobno FROM euser WHERE UserId IN (SELECT ID FROM abc WHERE xyz='xyz' And Standard='xyz');
You don't need 2 queries. Only 1 is enough
SELECT mobno FROM euser WHERE UserId IN (
SELECT ID FROM abc ...
)
Try this
$query ="SELECT * FROM abc WHERE xyz='xyz' And Standard='xyz' ";
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
if(mysqli_num_rows($data) > 0) {
$ID = array();
while($row=mysqli_fetch_array($data)){
$ID[] = $row['ID'];
}
$IDall = "'" . implode("','", $ID) . "'";
$query2="SELECT mobno FROM euser WHERE UserId IN ($IDall)" ;
$data2=mysqli_query($mysqli,$query2)or die(mysqli_error());
$mobiles = array();
while($row=mysqli_fetch_array($data2)){
$mobiles[] = $row['MobileNum'];
}
$mobilesStr = implode(',', $mobiles);
echo $mobilesStr;
}
In this the second query will execute when the first query has a result.

How to query a database with an array? WHERE = 'array()'

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);

Using result of query to another query with IN()

I want to using result of query to another query with IN():
foreach($result as $key=>$value){
$id .= $value['id'];}
$sql2 = 'SELECT * FROM table where id IN($id)';
but the $id must be in 'id1, id2, id3' format. With $id .= $value['quiz_id'].' , ';
there is one comma after last id. How can I convert $id value to 'id1, id2, id3'.
Thanks in advance
Use an array:
$ids = array();
foreach($result as $key=>$value){
$ids[] = $value['id'];}
if (count($ids) > 0) // to avoid mySQL error on empty array
{
$ids_string = implode(",", $ids);
$sql2 = 'SELECT * FROM table where id IN($ids_string)';
}
foreach($result as $key=>$value){
$idArr[] = $value['id']
}
$idStr = implode(',', $idArr);
$sql2 = 'SELECT * FROM table where id IN($idStr)';
This will give you a comma separated string of ids that you can use in your IN() query.
Hope that helps

Categories