MySQL run query inside a query - php

I have a query that gets 5 lines of data like this example below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
}
I want to run a query inside each results like this below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
but for some reason it's only display the first line when I add the query inside it. I can seem to make it run all 5 queries.

SELECT
t1.ref,
t1.user,
t1.id,
t2.domain,
t2.title
FROM
table AS t1
LEFT JOIN anothertable AS t2 ON
t2.domain = t1.ref
LIMIT
0, 5

The problem is that inside the while-cycle you use the same variable $result, which then gets overridden. Use another variable name for the $result in the while cycle.

You change the value of your $query in your while loop.
Change the variable name to something different.
Ex:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$qry = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$rslt = mysql_query($qry) or die(mysql_error());
if (mysql_num_rows($rslt) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}

Use the following :
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query_domain = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result_domain = mysql_query($query_domain) or die(mysql_error());
if (mysql_num_rows($result_domain) )
{
$row_domain = mysql_fetch_row($result_domain);
$title = $row_domain['title'];
} else {
$title = "No Title";
}
echo "$ref - $title";
}

This is a logical problem. It happens that way, because you are same variable names outside and inside the loop.
Explanation:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
// Now $results hold the result of the first query
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
//Using same $query does not affect that much
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
//But here you are overriding the previous result set of first query with a new result set
$result = mysql_query($query) or die(mysql_error());
//^ Due to this, next time the loop continues, the $result on whose basis it would loop will already be modified
//..............
Solution 1:
Avoid using same variable names for inner result set
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$sub_result = mysql_query($query) or die(mysql_error());
// ^ Change this variable so that it does not overrides previous result set
Solution 2:
Avoid the double query situation. Use joins to get the data in one query call. (Note: You should always try to optimize your query so that you will minimize the number of your queries on the server.)
SELECT
ref,user,id
FROM
table t
INNER JOIN
anothertable t2 on t.ref t2.domain
LIMIT 0, 5

Learn about SQL joins:
SELECT table.ref, table.user, table.id, anothertable.title
FROM table LEFT JOIN anothertable ON anothertable.domain = table.ref
LIMIT 5

You're changing the value of $result in your loop. Change your second query to use a different variable.

it is not give proper result because you have used same name twice, use different name like this edit.
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query1 = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result1 = mysql_query($query1) or die(mysql_error());
if (mysql_num_rows($result1) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}

Related

While loop showing only one record when i use nested while loop for fetch data from another table

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'];
}

Array to string conversion in mysql while loop

Following is my code,
$result1 = "SELECT emp_id FROM employee where manager_id=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
"emp_id: " . $row[0];
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
var_dump($myArrayOfemp_id);
$sql = "SELECT emp_id FROM emp_leaves WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
When I'am trying to use $myArrayOfemp_id variable in $sql query, It shows that error:
Array to string conversion in..
How can I fix it?
You are trying to convert an array into a string in the following line:
$sql = "SELECT emp_id FROM emp_leaves
WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";
$myArrayOfemp_id is an array. That previous line of code should be changed to:
$sql = "SELECT emp_id FROM emp_leaves
WHERE emp_id={$myArrayOfemp_id[0]} ORDER BY apply_date DESC";
I placed 0 inside {$myArrayOfemp_id[0]} because I'm not sure what value want to use that is inside the array.
Edited:
After discussing what the user wanted in the question, it seems the user wanted to use all the values inside the array in the sql statement, so here is a solution for that specific case:
$sql = "SELECT emp_id FROM emp_leaves
WHERE ";
foreach ($myArrayOfemp_id as $value)
{
$sql .= " emp_id={$value) || ";
}
$sql .= "1=2";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
$sql = "SELECT emp_id FROM emp_leaves WHERE emp_id in
(SELECT GROUP_CONCAT(emp_id) FROM employee where manager_id=".$userID.")
ORDER BY apply_date DESC";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
just change your query like above might solve your problem.
you can remove following code now. :)
$result1 = "SELECT emp_id FROM employee where manager_id=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
"emp_id: " . $row[0];
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
var_dump($myArrayOfemp_id);

PHP - Loop inside loop second loop runs only once

I'm running one while inside another while but the second one is running only one time why and how can I fix it. I have also try with for but running again only once.
$sql = "SELECT DISTINCT season FROM search WHERE link = '$getid' Order by id asc";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($list = mysql_fetch_assoc($result))
{
$season = $list['season'];
$sql = mysql_query("SELECT * FROM search WHERE link = '$getid' and season = '$season'");
$episodes = mysql_num_rows($sql);
echo '1st';
$sqls = "SELECT * FROM search WHERE link = '$getid' and season = '$season' Order by id asc";
$results = mysql_query($sqls, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($lists = mysql_fetch_assoc($results))
{
$episode = $lists['episode'];
echo'2nd';
}
}
You are overriding the variables, use different ones:
$sql = "SELECT DISTINCT season FROM search WHERE link = '$getid' Order by id asc";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($list = mysql_fetch_assoc($result))
{
$season = $list['season'];
$sql2 = mysql_query("SELECT * FROM search WHERE link = '$getid' and season = '$season'");
$episodes = mysql_num_rows($sql2);
echo '1st';
$sqls = "SELECT * FROM search WHERE link = '$getid' and season = '$season' Order by id asc";
$results2 = mysql_query($sqls, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($lists2 = mysql_fetch_assoc($results2))
{
$episode = $list2['episode'];
echo'2nd';
}
}

Random row selection using MySQL returns NULL

I am trying to get a random row from MySQL table but all three attemps:
$query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
give a NULL result in mysql_query($query).
Higher up my PHP code I obtain a row from the same table OK by specifying WHERE, so I don't understand why I can't retrieve a random one.
Here is the code snippet:
$query = "SELECT uid,clu FROM uable WHERE un = '$un'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$resultid = mysql_fetch_assoc($result);
$uid = $resultid['uid'];
file_put_contents('debugging.txt',__LINE__.' - $uid = '.var_export($uid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE uid = $uid AND cn = '$cn'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$cr = mysql_fetch_assoc($result);
$cid= $cr['cid'];
file_put_contents('debugging.txt',__LINE__.' - $cid= '.var_export($cid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM fable WHERE cid= '$cid'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
file_put_contents('debugging.txt',__LINE__.' - $result = '.var_export($result,true).PHP_EOL,FILE_APPEND);
$fr = mysql_fetch_assoc($result);
file_put_contents('debugging.txt',__LINE__.' - $fr = '.var_export($fr,true).PHP_EOL,FILE_APPEND);
echo '<form action="'.$_SERVER['PHP_SELF'].’" method="post">';
if (!$fr) {
$o= $cn;
while ($o= $cn) {
// $ac = mysql_query("SELECT * FROM table") or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
// $num_rows = mysql_num_rows($ac);
//file_put_contents('debugging.txt',__LINE__.' - $num_rows = '.$num_rows.PHP_EOL,FILE_APPEND);
// --$num_rows;
// $query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
// $query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
$resultid = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($resultid);
$o= $opr['cn'];
}
file_put_contents('debugging.txt',__LINE__.' - $query = '.$query.PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $resultid = '.var_export($resultid,true).PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $op[\'cid\'] = '.$op['cid'].PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE cid= ".$op;
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($opr);
$o= $opr['cn'];
$od= $opr['description'];
echo '<p>'.$op;
if ($od<> '') {
echo ','.$odesc;
}
echo '</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
} else {
echo '<p>'.$fr['p'].'</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
}
echo '</form>';
The resulting debugging.txt:
24 - $uid = '4'
29 - $cid = '21'
32 - $result = NULL
34 - $fr = false
These queries look OK, but I think you're starting at the wrong place. When you're uncertain how to frame something in SQL, open up a SQL client like SequelPro or Navicat and try writing a few queries by hand until you get the result you want. (Also this gives you a chance to double-check the contents of relevant tables and ensure the expected data are there.) Then you can go back into the PHP with full confidence that the SQL code is correct, so if there's a problem it must be with the PHP (either the variables you inject into a Mysql statement, or the way you call that statement).

PHP set variable value again for sql query not working

Hello my question is quite simple, yet I can not understand why it works like this.
When I have set the varialbe $query once and then set it again it does not work.
Only when using an other name for the variable, for example $query2 it works.
WORKS :
$connect = mysql_connect("","","") or die(mysql_error());
mysql_select_db("");
$query = "select post_title,id from wp_posts where post_status='publish'";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
WHILE 1
$query2 = "SELECT meta_key FROM `wp_postmeta` WHERE post_id='$id'";
$result2 = mysql_query($query2);
while($row2 = mysql_fetch_row($result2))
{
WHILE 2
}
}
NOT WORKS :
$connect = mysql_connect("","","") or die(mysql_error());
mysql_select_db("");
$query = "select post_title,id from wp_posts where post_status='publish'";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
WHILE 1
$query = "SELECT meta_key FROM `wp_postmeta` WHERE post_id='$id'";
$result = mysql_query($query);
while($row2 = mysql_fetch_row($result))
{
WHILE 2
}
}
You are not only changing the $query variable, but also the $result. Which is in your while, screwing up the first result set. You just have to assign a new result set.
This will work:
$query = "select post_title,id from wp_posts where post_status='publish'";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
WHILE 1
$query = "SELECT meta_key FROM `wp_postmeta` WHERE post_id='$id'";
$result2 = mysql_query($query);
while($row2 = mysql_fetch_row($result2))
{
WHILE 2
}
}
$result is a HANDLE representing the results of the query. Your second query is OVERWRITING the result of the first query, effectively killing the first query's results:
$result = mysql_query($query1);
while($row = mysql_fetch_row($result)) {
$result = mysql_query(...);
^^^^^^^---- overwrite occurs here
You run query #1, start the loop, run query #2. That query's results replaces the result from the first query, and gets completely consumed by the inner while() loop. When the inner loop finishes and control goes back up to the outer loop, there's no more data in this new $result handle, so the outer loop terminates as well.
Its because you are using while in while, it means yours second while:
$result = mysql_query($query);
while($row2 = mysql_fetch_row($result))
will overwrite yours first $result.

Categories