Multiple while loop in two queries - php

I have 2 queries.
and 2 while loops.
my problem is that When I call out the values. only one query and one loop is correct. the other loop is displaying duplicate values.
here is what I have :
$query1=mysql_query("SELECT * FROM table1");
$query2=mysql_query("SELECT * FROM table2");
while($row1=mysql_fetch_array($query1)){
while($row2=mysql_fetch_array($query2)){
echo $row1['nameofattribute'] ;
echo $row2['nameofattribute'] ;
}
}
the output of query 1 is correct. but the output of query 2 is duplicate values.
for example :
query 1= $row1=2 $row1=3 $row1=4
query 2= $row2=3 $row2=3 $row2=3
instead it should be
query 1= $row1=2 $row1=3 $row1=4
query 2= $row2=1 $row2=2 $row2=3
on top is my simple translation of the code. here is my real code :
$query1 = mysql_query("SELECT remarks FROM passed_deliverable WHERE user_id=$uid && deliverable_category_id=4");
$query2=mysql_query("SELECT
deliverable_id, deliverable_title, deliverable_desc, adviser_id ,deliverable_category_id
FROM deliverable d
WHERE d.deliverable_category_id=4
&& EXISTS (
SELECT 'X'
FROM passed_deliverable pd
WHERE pd.deliverable_id = d.deliverable_id && user_id='".$_GET['edit']."' && adviser_id='".$_SESSION['user_id']."' ) ");
while($x=mysql_fetch_array($query1)){
while($deliverable=mysql_fetch_assoc($query2)){
echo "
{$deliverable['deliverable_desc']}
{$x['remarks']}
";

try this :
other answer or loop from mr. hellcode
it shows that you can also use array values instead of just using array
$a1 = 0[];
$a2 = 0[];
while($x=mysql_fetch_array($query1)) {
$a1[] = $x['remarks'];
}
while($deliverable=mysql_fetch_assoc($query2)) {
$a2[] = $deliverable['deliverable_desc'];
}
for($i=0; $i < count($a1) and $i < count($a2); $i++) {
echo "\n\n".$a2[$i]."\n".$a1[$i];
}

Assuming that you just want to combine the resulting rows of both tables in their appearing order (ignoring results that exceed the other table):
$a1 = array();
$a2 = array();
while($x=mysql_fetch_array($query1)) {
$a1[] = $x['remarks'];
}
while($deliverable=mysql_fetch_assoc($query2)) {
$a2[] = $deliverable['deliverable_desc'];
}
for($i=0; $i < count($a1) and $i < count($a2); $i++) {
echo "\n\n".$a2[$i]."\n".$a1[$i];
}

Deprecation of mysql_ functions . Please avoid mysql_ function . Anyway your query seems to unusual. because we don't see any WHERE clause in your queries . That means it will return duplicate value. Table1 each row will be check all rows of Table2 .

Related

Undefined variable array

I get an error on line 15 that says "Undefined variable: row2". How can I resolve this?
$limit = 20;
$res1 = mysql_query('SELECT *
FROM contact
WHERE name = "Greg"');
$res2 = mysql_query('SELECT name
FROM contact c, passport p
ON c.idNum = p.iNum
WHERE date >= "2015-03-03" AND t< "2015-03-21');
if(!$res1 && !$res2) {
die('Query no valid: ' . mysql_error());
}
else {
while(($row1 = mysql_fetch_array($res1)) || ($row2 = mysql_fetch_array($res2))) {
$sub = $row1['num'] - $row2['num'];
if($sub <= $limit) {
echo '<br>row name is: ', $row2['name'];
}
}
}
What I'm trying to do is get a number from the first table (it only results to just Greg's row). Then subtract it with the numbers from the results of the second table. The result of this is placed into the sub variable and it's check to see if it's <= 20. If yes, it prints out the row. If not, it goes back to while loop to check another row. Am I going about the right way so far?
You need to change the while() loop's condition. Consider this example:
$a = 1;
if ($a == 1 || $b = 2) {
var_dump(isset($b));
}
Output of var_dump() will be boolean false because $b does not exist, which is the same case why your $row2 is undefined.
The thing is, while evaluation conditions with ||, PHP will stop evaluating other conditions once the match is found, so other comparisons or assignments on the right side will not be performed.
Change your while to be like this, you need both $row1 and $row2 anyway:
while(($row1 = mysql_fetch_array($res1)) && ($row2 = mysql_fetch_array($res2))) {
(note the && instead of ||)
Also, looks like you may want to use SELECT c.* in your second query, too, because you're only selecting the name column, and trying to use num too.
Note : Select all columns in your 2nd Query if num is already available in your columns so your problem will be solved then.!
Note : Try to replace || with && and you will be good to go.
By using || or OR as in conceptional language as I would say it.You are making the code like in a way that either and only one will pass but if you are passing both ones so then you should replace || with && so that's why your $row2 will be already created then so it will be available for more operation.!
$limit = 20;
$res1 = mysql_query('SELECT *
FROM contact
WHERE name = "Greg"');
$res2 = mysql_query('SELECT *
FROM contact c, passport p
ON c.idNum = p.iNum
WHERE date >= "2015-03-03" AND t< "2015-03-21');
if(!$res1 && !$res2) {
die('Query no valid: ' . mysql_error());
}
else {
while(($row1 = mysql_fetch_array($res1)) && ($row2 = mysql_fetch_array($res2))) {
$sub = $row1['num'] - $row2['num'];
if($sub <= $limit) {
echo '<br>row name is: ', $row2['name'];
}
}
}

PHP duplicate staffID

staff table
code
<?php
//db configuration
$q = "select * from staff";
$r = mysqli_query($dbc, $q);
$num_rows = mysqli_num_rows($r);
$staffID = array();
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$staffID[] = $row['staffID'];
}
for($i = 0; $i < $num_rows; $i++)
{
if($staffID[$i] == $staffID[$i+1])
{
$remark = "Not OK. Multiple staff ID selected.";
$i++;
}
else
{
$remark = "OK.";
}
$data[$i] = $staffID[$i].','.$remark.'<br />';
}
$list = array($data);
print_r($list);
?>
From above code, I want to check whether the staffID got duplicate.
Expected output
0001, OK.
0002, Not OK. Multiple staffID.
0003, OK.
0004, OK.
However, I get another error as below:
Undefined offset: 5 in play.php on line X.
How do I solve it?
By performing the correct query in the first place.
SELECT staffID
FROM staff
GROUP BY staffID
HAVING COUNT(staffID) > 1
Or if you need to know about all staff IDs:
SELECT staffID, COUNT(staffID) as qty
FROM staff
GROUP BY staffID
Just updating your code and i think you have to check the existence first :
if (isset($staffID[$i]) && isset($staffID[$i+!])) {
if($staffID[$i] == $staffID[$i+1])
{
$remark = "Not OK. Multiple staff ID selected.";
$i++;
}
else
{
$remark = "OK.";
}
$data[$i] = $staffID[$i].','.$remark.'<br />';
}
You get the error at this line:
if($staffID[$i] == $staffID[$i+1])
Say for example your $num_rows variable is 3. Then the $staffID array would have indexes 0, 1 and 2. But what happens at this line I noted is that once $i reaches 2 (which is a valid since it's less than 3) you go and do $i+1 which equals 3. And, as you can see, the index 3 is out of the bounds of the array.
If you wish to do this like you wrote your for loop should be like this:
for($i = 0; $i < $num_rows-1; $i++)
But, there is a better way without even doing the for loop. You can do it all in the while loop by making use of the in_array function. Or as Ignacio pointed out, you could do it all on the SQL level.
Not a good way to solve this problem. You should use GROUP BY query for this.
SELECT staffID, COUNT(staffID) as count
FROM staff
GROUP BY staffID
HAVING count > 1
And also about your error. It's because of
if($staffID[$i] == $staffID[$i+1])
on last iteration $i is equal 4 and $i+1 is 5. But $staffID array has no element with such key

How to sum up values in a php column

Im trying to sum up all the values in this data base but for some reason i cant do i, I looked all over stack overflow and tried multiple methods but none seem to work. My current code is
<?php
error_reporting(0);
//INCLUDES//
include 'config.php';
//INCLUDES//
//DATA FETCH//
$rank=$_POST['R'];
$drank=$_POST['DR'];
//DATA FETCH//
//MYSQL STUFF//
$con=mysqli_connect($ip,$login,$password,$dbname);
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i'");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
echo $row[0];
}
?>
It connects to the database no problem. When I use echo $row[0]; it prints all the values of the column in order. Ive tried putting it into an array and printing it but it seems that doesnt work either. The only way it seems to work is when I add ALL the values in the column by removing WHERE rank='$i' in the SQL code which I dont want to do. Please help !
Try the following query :
$rankarr = array();
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$rankarr[] = $i;
}
$rankarr = implode(',', $rankarr);
$s=mysqli_query($con, "SELECT sum(rankprice) As myrank FROM cost WHERE rank in ($rankarr)");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
You now want to get the sum value of rankprice in one same rank. So the result of sum() will differ from the rank in one sql. You should tell mysql by adding group by clause, which group the table by rank and get the sum() of each group.
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i' GROUP BY rank ");

Php how to check for duplicate results?

Hi I'm currently querying from a database base user ids for a contest, However I want to avoid choosing duplicates in my results_array, this function getrandomspecies receives a array_result, this array results iterates 7 times. How test that I don't put duplicates in my results_array? I have gotten several duplicates.
function getrandomspecies($array_result){
//database connection
$dbn = adodbConnect();
foreach($array_result as $possible){
//query the results
$querys= "select * from taxonomic_units where tsn = $possible";
$resultss = $dbn -> Execute($querys);
while($rowss=$resultss->FetchRow()){
$id = $rowss['tsn']; //there ID
$ranksss = $rowss['rank_id']; //ranking id, I choose 220 and 230
if($ranksss == 220 || $ranksss == 230){
$prelimary_array[] = $id;
}
}
//grab random index
$index = array_rand($prelimary_array,1);
//put result id into a variable
$newspecies = $prelimary_array[$index];
//put that variable in an array
$results_array[] = $newspecies; //there is 7 newspecies/winners at the end, I dont want duplicates
}
return $results_array;
}
MySQL should be the following :
select distinct tsn, rank_id from taxonomic_units where tsn = $possible
But you should ideally use prepared statements.
what about this? You may do it with one query:
$querys= "select DISTINCT tsn from taxonomic_units where tsn IN (".implode(",",$array_result).") AND rank_id IN (220,230) ORDER BY RAND() LIMIT 7 ";
Loop your result array and if it does not exists add it. If you end up with less than 7, do your big loop again.
replace this line :
$results_array[] = $newspecies;
by:
$loop_1_more_time=0;
if (isset($results_array)){
foreach($results_array as $result){
if ($result == $new_specie){
$loop_1_more_time=1;
}
}
}
if ($loop_1_more_time == 0){
$results_array[] = $newspecies;
}
//there, if $loop_1_more_time equals 1, start again. To start again and be sure you have seven instead of 6 or less, You could replace your big first "foreach" loop with a "for" loop that depends of the count() of the $array_result, and the $array_result would be array_result[$i] instead of $possible. $i would start at 0 and increment at each end of loop. It would not be incremented if ­­$loop_1_more_time==1;.
Example :
for ($i = 0; $i < count($array_result); $i++) {
//stuff
//if ($loop_1_more_time=1;) { $i--; }
}
Why don't you try shuffling the array, and then picking the first X numbers?
That way, rather than having to check the results array for duplicates, it will never come up in the first place

PHP while loop to get values from mysql data base if it equals the $i value

I'm trying to get a value to be inserted into a table on a webpage if the value equals $i.
$i starts at a number and decreases every loop. i can get it to work but it outputs multiple lines for each $i equivalent to the results in the table
I've reworked the code using everyones feedback to get this.
Echo "<tr><th colspan='3'><center>$rackname</th> </tr>" ;
for ($i=$RUtotal; $i > 0; $i--)
{
echo" <tr class='rackbg'><td class='i'><center>$i</td>" ;
$sql1 = "SELECT racks.rackID, racks.rackname, devices.deviceID, devices.deviceName, racks.rackRU, devices.deviceRU, devices.RUcount
FROM racks LEFT JOIN devices ON racks.rackID = devices.rackID
WHERE devices.rackID = '$rackID'";
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_assoc($query1))
{
$deviceru = $row['deviceRU'];
$deviceID = $row['deviceID'];
$device = $row['deviceName'];
$deviceRUC = $row['RUcount'];
if ($deviceru == $i)
{
echo '<td class="device" rowspan='.$deviceRUC.'><a onclick=window.location="/devices.php?id='.$deviceID.'">'.$device.'</a></td><td rowspan='.$deviceRUC.'></td></tr>';
}
else
{
;
}
}
}
Echo "<tr class='rackb'><th colspan='3'>a</th></tr> " ;
This works to a degree (picture1) but when i add echo "" to the else statement it displays all wrong. (picture 2)
Any help would be greatly appreciated
Picture1 - http://imageshack.us/photo/my-images/263/examplewq.png/
Picture2 - http://imageshack.us/photo/my-images/269/example2jp.png/
I can't quite see what you're trying to do but what it looks like to me is that you want all the items from racks joined with their relevant device and displayed in order of deviceRU. Does this help:
echo "<tr><th colspan='3'><center><b>$rackname</th></tr>" ;
$sql1 = "SELECT racks.rackID, racks.rackname, devices.deviceID, devices.deviceName, racks.rackRU, devices.deviceRU, devices.RUcount
FROM racks LEFT JOIN devices ON racks.rackID = devices.rackID
WHERE racks.rackID = '$rackID' AND devices.deviceRU <= ".intval($RUtotal)."
ORDER BY devices.deviceRU;"
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1))
{
$deviceru = $row['deviceRU'];
$deviceID = $row['deviceID'];
$device = $row['deviceName'];
$deviceRUC = $row['RUcount'];
echo'<tr class="rackbg"><td class="i">'.$i.'</td><td class="device">'.$device.'</td><td></td></tr>';
}
I've used a LEFT (inner) JOIN in the SQL instead of the outer join that was there before as it'll return less results and might solve your problem. I've ordered the results by deviceRU and only returned results which have deviceRU less than or equal to $RUtotal (as I think the example was showing).
I've also removed the tags, these should be replaced by using CSS to centre either all td elements or centering class="device" and class="i" e.g.:
.device, .i {
text-align: center;
}
I've also swapped your abc to abc which is the correct format for a link.
Could you describe more of the context as it's difficult to see your intention from your post.
Mat
As Peetz said, you don't need nested loop. You need something like:
$i = $RUtotal;
// ...
while ($row = mysql_fetch_array($query1)) {
// ...
if ($deviceru == $i) {
// ...
} else {
// ...
}
// ...
$i--;
}
This is looping $i times, within the outer while loop. This means you are getting the table repeated over and over again.
I suggest you remove the outer while loop.

Categories