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.
Related
I have case manager table where i have inserted court table id as foreign key. i want to fetch record from both tables. when using nested while loop it shows only one row data.
$id = $_SESSION['id'];
$query1 = "SELECT * from `case_manager` where user_id = '$id' ";
$result1 = mysqli_query($conn, "$query1");
while($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$Status = $row['status'];
$id = $row['id'];
$case_type = $row['case_type'];
$court_id = $row['court_id'];
$query2 = "SELECT * from `case_type` where case_id = '$case_type'";
if($result1 = mysqli_query($conn, "$query2")) {
while($row2 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
echo $row2['case_name'];
}
}
}
Because you are overwritting you $result1 change inner query result to $result2 then try
$id = $_SESSION['id'];
$query1 ="SELECT * from `case_manager` where user_id = '$id' ";
$result1 = mysqli_query($conn , "$query1");
while ($row = mysqli_fetch_array($result1 ,MYSQLI_ASSOC)) {
$Status=$row['status'];
$id = $row['id'];
$case_type = $row['case_type'];
$court_id = $row['court_id'];
$query2 ="SELECT * from `case_type` where case_id = '$case_type'";
if($result2 = mysqli_query($conn , "$query2")){;
while ($row2 = mysqli_fetch_array($result2 ,MYSQLI_ASSOC)) {
echo $row2['case_name'];
}
}
}
1st : Because you are overwriting the variable $result1 In second query execution.
if($result1 = mysqli_query($conn , "$query2")){;
^^^^^^^^ ^^
Note : And remove that unnecessary semicolon .
2nd : No need multiple query simple use join
SELECT cm.*,c.* from `case_manager` cm
join `case_type` c
on cm.cas_type=c.case_id
where cm.user_id=$id;
You can use below query to fetch your record:
$query = SELECT case_manager.* ,case_type.case_name FROM case_manager Left JOIN case_type ON case_manager.case_type=case_type.case_id where case_manger.user_id = $id;
While($row = mysql_fetch_array()){
echo $row['case_name'];
}
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
}
Apologies if I have the terminology wrong.
I have a for loop in php which operates a mysql query...
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '$user_id_pc[$i]'";
$job_data = mysqli_query($dbc, $query2);
$job_results = array();
while ($row = mysqli_fetch_array($job_data))
{
array_push($job_results, $row);
}
}
The results that are given when I insert a...
print_r ($job_results);
On screen -> Array()
If I change the query from $user_id_pc[$i] to $user_id_pc[14] for example I receive one set of results.
If I include this code after the query and inside the for loop
echo $i;
echo $user_id_pc[$i] . "<br>";
I receive the number the counter $i is on followed by the data inside the array for that counter position.
I am not sure why the array $job_results is empty from the query using the counter $i but not if I enter the number manually?
Is it a special character I need to escape?
The full code
<?php
print_r ($user_id_pc);
//Select all columns to see if user has a profile
$query = "SELECT * FROM user_profile WHERE user_id = '" . $_SESSION['user_id'] . "'";
//If the user has an empty profile direct them to the home page
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 0)
{
echo '<br><div class="alert alert-warning" role="alert"><h3>Your appear not to be logged on please visit the home page to log on or register. <em>Thank you.</em></h3></div>';
}
//Select data from user and asign them to variables
else
{
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$cw_job_name = $row['job_description'];
$cw_rate = $row['hourly_rate'];
$job_mileage = $row['mileage'];
$job_postcode = $row['postcode'];
$response_id = $row['user_profile_id'];
}
}
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '{$user_id_pc[$i]}'";
$job_data = mysqli_query($dbc, $query2);
$job_results = array();
while ($row = mysqli_fetch_array($job_data))
{
array_push($job_results, $row);
}
echo $i;
?>
<br>
<?php
}
print ($query2);
print $user_id_pc[$i];
?>
This is primarily a syntax error, the correct syntax should be:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '{$user_id_pc[$i]}'";
Note that this is correct syntax but still wrong!! For two reasons the first is that it's almost always better (faster, more efficient, takes less resources) to do a join or a subquery or a simple IN(array) type query rather than to loop and query multiple times.
The second issue is that passing parameters in this manner leave your vulnerable to sql injection. You should use prepared statements.
The correct way
if(count($user_id_pc)) {
$stmt = mysqli_stmt_prepare(" SELECT job_title, job_info FROM job_description WHERE postcode_ss = ?");
mysqli_stmt_bind_param($stmt, "s", "'" . implode("','",$user_id_pc) . "'");
mysqli_stmt_execute($stmt);
}
Note that the for loop has been replaced by a simple if
You have to check the query variable, instead of:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '$user_id_pc[$i]'"
have you tried this:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '" . $user_id_pc[$i] . "' ";
And another thing, try something different like this:
while ($row = mysqli_fetch_array($job_data))
{
$job_results[] = array("job_title" => $row["job_title"], "job_info" => $row["job_info");
}
Then try to print the values.
Sorry but I like foreach(), so your working code is:
<?php
// To store the result
$job_results = [];
foreach($user_id_pc as $id ){
// selecting matching rows
$query2 ="SELECT job_title, job_info FROM job_description WHERE postcode_ss = '".$id."'";
$job_data = mysqli_query($dbc, $query2);
// checking if query fetch any result
if(mysqli_num_rows($job_data)){
// fetching the result
while ($row = mysqli_fetch_array($job_data)){
// storing resulting row
$job_results[] = $row;
}
}
}
// to print the result
var_dump($job_results);
I am trying to get data from database then fetch it again with different mysql_query using while() in both query , but the problem it is producing results more than one time because i used while in first query . So any answer to get all data without while() for first query ?
$AllFrnd = "SELECT friend , followers FROM frndlist WHERE userid = '".$_SESSION[' user_id ']."' ORDER BY id DESC";
$getfrnd = mysql_query($AllFrnd);
while($frnd = mysql_fetch_array($getfrnd)) {
$query2 = "SELECT * FROM post WHERE (userid ='".$frnd['friend']."') OR (userid = '".$frnd['followers']."') OR (userid = '".$_SESSION[' user_id ']."') ORDER BY id DESC";
$rs = mysql_query($query2);
while($row = mysql_fetch_array($rs)) {
echo ''.$row['content'].'';
you can try this :
// Associative array
$frnd =mysql_fetch_array($getfrnd,MYSQL_ASSOC);
then get your data as like :
echo $frnd ["friend"]
echo $frnd ["followers"]
And you should use mysqli_fetch_array instead of mysql_fetch_array
Hope it helps
You can use a query just like this :
SELECT *
FROM post
WHERE userid IN (
SELECT followers
FROM frndlist
WHERE userid = '" . $_SESSION['user_id'] . "'
)
OR userid IN (
SELECT friend
FROM frndlist
WHERE userid = '" . $_SESSION['user_id'] . "'
)
OR userid = '" . $_SESSION['user_id'] . "'
ORDER BY id DESC
You can easyly handle by using this function
function sel($table,$field="*", $condition="1",$sort="" ){
if($sort!='') $sort="order by $sort ";
//echo "select $field from $table where $condition $sort ";
$sel_query=mysql_query("select $field from $table where $condition $sort ");
//$sel_result=array();
while($temp_res=#mysql_fetch_array($sel_query))
{
$sel_result[]=$temp_res;
}
return isset($sel_result)?$sel_result: 0;
}
while($frnd = mysql_fetch_array($getfrnd)) {
$temp_res=sel("post","*"," (userid ='".$frnd['friend']."') OR (userid = '".$frnd['followers']."') OR (userid = '".$_SESSION[' user_id ']."') ORDER BY id DESC");
if($temp_res)foreach($temp_res as $row){
echo $row['content'];
}
}
$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)";