Doing a PHP While Loop Inside A While Loop - php

I am trying to do a php while loop inside another php while loop but when I get to the second loop it doesn't go back to the first one and reloop again Here is the code I am using:
Database connection string is in a separate module. The first while Loop should loop twice but what I think is happening when it gets to the second database while loop that loop returns positive and it affects the first loop so I only get 1 loop from the first loop. Can someone please tell me how I could change this to avoid this problem?
These are the two loops below from a database:
while($row = $result->fetch_assoc()) {
// Show/Hide Regions:
error_reporting(-1);
ini_set('display_errors', 'On');
//Access our class.
$db_Class = new db_Class;
$conn = ($db_Class->db_conn());
$sql = "SELECT id, region FROM tbl_region;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$counter = 0; //Set count to 1
while($row = $result->fetch_assoc()) {
$counter++; //Increment counter by 1's
$rID = $row["id"];
?>
Output Region Here!
<?php
//Output companies for this region.
$sql = "SELECT
tbl_company.company_name,
tbl_company.group_number,
tbl_region.region
FROM
tbl_region
INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
WHERE
$rID = tbl_company.region_id
ORDER BY
tbl_company.company_name ASC
";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["company_name"]."<br>";
}
}
echo "A";
echo '</div>';
}
} ?>

Change inner loop $row and $result with any other name..for example I have done $rowInner and $resultInner here.
<?php
while($row = $result->fetch_assoc()) {
if ($result->num_rows > 0) {
$counter = 0; //Set count to 1
while($row = $result->fetch_assoc()) {
$counter++; //Increment counter by 1's
$rID = $row["id"];
?>
Output Region Here!
<?php
$sql = "SELECT
tbl_company.company_name,
tbl_company.group_number,
tbl_region.region
FROM
tbl_region
INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
WHERE
$rID = tbl_company.region_id
ORDER BY
tbl_company.company_name ASC
";
$resultInner = $conn->query($sql);
if ($resultInner->num_rows > 0) {
while($rowInner = $resultInner->fetch_assoc()) { // Change $row to $rowInner
echo $rowInner["company_name"]."<br>";
}
}
echo "A";
echo '</div>';
}
}
}
?>

You should use a different variable for $result like $result2 for 2 while loops. That is causing the conflict.

You overwritten the first $row/$result with the second $row/$result. Try using a different name for the second set of results.
// Show/Hide Regions:
error_reporting(-1);
ini_set('display_errors', 'On');
//Access our class.
$db_Class = new db_Class;
$conn = ($db_Class->db_conn());
$sql = "SELECT id, region FROM tbl_region;";
$result =
$conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$counter = 0; //Set count to 1
while($row = $result->fetch_assoc()) {
$counter++; //Increment counter by 1's
$rID = $row["id"];
?>
Output Region Here!
<?php
//Output companies for this region.
$sql = "SELECT
tbl_company.company_name,
tbl_company.group_number,
tbl_region.region
FROM
tbl_region
INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
WHERE
$rID = tbl_company.region_id
ORDER BY
tbl_company.company_name ASC
";
$result2 = $conn->query($sql);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
echo $row2["company_name"]."<br>";
}
}
echo "A";
echo '</div>';
}
} ?>

You should use different variables for inner and outer while loops. Try the following:
<?php
// Show/Hide Regions:
error_reporting(-1);
ini_set('display_errors', 'On');
//Access our class.
$db_Class = new db_Class;
$conn = ($db_Class->db_conn());
$sql = "SELECT id, region FROM tbl_region;";
$resultOuter = $conn->query($sql);
if ($resultOuter->num_rows > 0)
{
// output data of each row
$counter = 0; //Set count to 1
while($rowOuter = $resultOuter->fetch_assoc())
{
$counter++; //Increment counter by 1's
$rID = $rowOuter["id"];
//Output companies for this region.
$sql = "SELECT tbl_company.company_name, tbl_company.group_number, tbl_region.region
FROM tbl_region
INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
WHERE
$rID = tbl_company.region_id
ORDER BY
tbl_company.company_name ASC ";
$resultInner = $conn->query($sql);
if ($resultInner->num_rows > 0)
{
// output data of each row
while($rowInner = $resultInner->fetch_assoc())
{
echo $rowInner["company_name"]."<br>";
}
}
echo "A";
echo '</div>';
}
}
?>

Related

how to get count(*) the right way in php

I tried to count() the data from database with php but it don't show me the total data but it show the datas.
this is how I count
$query = "SELECT
mitra.*,
user.username,
user.privilege,
user.name
FROM
mitra
INNER JOIN
user ON mitra.id_user = user.id "
$result = $connection->query($query);
if ($result->num_rows > 0) {
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = "" . $row["total_puas"] . "";
$privilege = "" . $row["privilege"] . "";
if ($privilege == 2) :
$calculate = $total / count($id);
var_dump(count($id));
endif;
endforeach;
}
===================
= id = total =
= 1 = 45.84 =
= 2 = 75.45 =
= 3 = 34.54 =
===================
when I var_dumb it it shows int(1)int(1)int(1) not int(3) that what I wanted.
actually I want to count $calculate with the data in $total that should be there is float and the amount from $total that I want to divided with count id
is there any solution that how to count the amount from $total and can be devided with count $id that should be 3?. please help
what I really trying to do from that table example is like 45.84 + 75.45 + 34.54 / 3
Sounds like you want a COUNT() with GROUP BY in your query. Doing count($id) in PHP will always yield one, as its not an array of values.
$query = "SELECT COUNT(id) as cnt, id, total_puas
FROM table
GROUP BY id";
$result = $connection->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$calculate = $row["total_puas"] / $row['cnt'];
echo $row['id']." has a count of ".$row['cnt'].", a total of ".$row['total_puas']." and calculated to ".$calculate."<br />\n";
}
}
From your updated question, the output becomes a bit more clear. Based on the output data and the result you desire, you want to calculate the sum of all total_paus, divided by the number of rows. You can do this directly in one query, like this
$query = "SELECT SUM(total_puas) / COUNT(u.id) as total
FROM mitra AS m
INNER JOIN user AS u
ON mitra.id_user = user.id";
$result = $connection->query($query);
$row = $result->fetch_assoc();
$total = $row['total'];
echo $total;
You can try this code:
<?php
$i = 0;
$total =0.00;
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()):
if ($row["privilege"] == 2) :
$total = $total + $row["total"];
$i++;
endif;
endwhile;
echo $total."<br>";
echo $i."<br>";
echo $calculate = $total / $i;
}
?>
output
=====================================
$total = 155.83;
$i = 3;
$calculate = $total/$i;
$ans = 51.943333333333;
=====================================
You can try this code:
$query = "SELECT * FROM table"
$result = $connection->query($query);
if ($result->num_rows > 0) {
$total = 0.0;
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = $total + $row['total'];
endforeach;
$calculate = $total / $result->num_rows;
echo $total.<br>;
echo $calclulate;
}

Repeating SQL insert statement in loop till id has certain value?

<?php
include ("db.php");
$id2 = "SELECT MAX(id) FROM osalejad;";
$id = $conn->query($id2);
if (id<= 8){
while($id<= 7) {
$min = 1;
$max = 20;
$suvanumber = rand($min, $max);
$bar = (string) $suvanumber;
$prii= "vaba2" . $bar;
$sql="INSERT INTO osalejad (name) VALUES ('$prii')";
$result = $conn->query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
else {
echo '8 osalejat on juba kirjas';
}
?>
I have a question, i want to insert data into MYSQl table, word with a random number, but problem is, it never work as it should - if i have 3 records in name column, then till, it adds 8 more records, instead of 5 records. Is something outside of scope atm?
I will use the DB in this code.
<?php
include("db.php");
$sql = "SELECT * FROM `osalejad`;";
$result = $conn->query($sql);
$var = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = mysqli_fetch_array($result)) {
$var[] = $row["name"];
}
} else {
/// echo "0 results";
}
//shuffle the array, and encode into json.
shuffle($var);
$brack=json_encode($var);
$testbrack= json_encode(array_chunk($var,2));
$final = '{';
$final .= '"teams":';
$final .= $testbrack;
$final .= ',"results":[[[[0,0],[null,null]],[[null,null],[null,null]]]]}';
//updating last tournament bracket.
$sql1 = "UPDATE lan_brackets SET json='$final' ORDER BY tid DESC LIMIT 1;";
$roundOne=$conn->query($sql1);
?>

join query not working properly

I want to select two table values so I am using join query see below, from this code I stored one session variable like $_SESSION['emp_id'], I want select query like who are in te.emp_id='".$_SESSION['emp_id']."', From this code $count will return 0 but in my database I have one row.
$q = mysql_query("SELECT *
FROM task_employee te
JOIN task t
ON te.emp_id = t.t_assign_to
WHERE t.t_status = '0'
AND t.t_delete_on != '1'
AND te.emp_id = '" . $_SESSION['emp_id'] . "'");
$data = array();
while($r = mysql_fetch_assoc($q))
{
$data[] = $r;
}
$count = sizeof($data);
if($count > 0)
{
$return = array('status'=>'success', 'count'=>sizeof($data), 'data'=>$data);
echo json_encode($return);
}
else
{
$return=array('status'=>'not-found', 'count'=>sizeof($data), 'data'=>$data);
echo json_encode($return);
}
I am writing like this means I can get but using join query that time I can't get values
<?php
$sql = mysql_query("SELECT *
FROM task
WHERE t_delete_on !='1'
AND t_assign_to = '$emp_id'");
for ($i = 1; $row = mysql_fetch_assoc($sql); $i++)
{
$assign_to = $row['t_assign_to'];
$mysql = mysql_query("SELECT *
FROM task_employee
WHERE emp_id = '$assign_to'");
while ($r = mysql_fetch_assoc($mysql))
{
$emp_name = $r['emp_firstname']; // here i got value
}
}
?>

Nested Navigation

I want to make a Navigation with 2 levels.
My Code so far
<?php
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='' ORDER BY name");
$result = mysql_query($sql);
$list = array();
while ($row = mysql_fetch_assoc($result)) {
$list[] = $row;
}
foreach ($list as $kat) {
echo '<li>' . $kat['name'] . '</li>';
}
?>
Nested Sets are at the moment too tricky for me.
I want at the end this.
<li>$kat['name']
<li>$kat['name'] from PID</li>
</li>
MySQL:
http://i46.tinypic.com/35052m0.png - IMG
No I want to get the things our of the MySQL DB see the image Link.
MySQL:
id—–pid——name
1——0——–name1
2——0——–name2
3——0——–name3
4——3——–name3.1
5——3——–name3.2
<?php
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='' ORDER BY name");
$result = mysql_query($sql);
$list = array();
while ($row = mysql_fetch_assoc($result)) {
$list[$row['id']] = $row;
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='".$row['id']."' ORDER BY name");
$res = mysql_query($sql);
while($rw = mysql_fetch_assoc($res)){
$list[$row['id']]['sub'][] = $rw;
}
}
echo "<pre>";
print_r($list);
?>

Why does this query show only one result?

The query I have below will only show me one result even if there are multiple matching entries (completely or partially matching). How do I fix it so it will return all matching entries:
//$allowed is a variable from database.
$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM
`users` LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name`
LIKE '%$q%' ) LIMIT $startrow, 15";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$num_rows1 = mysql_num_rows($result);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$person = htmlspecialchars($row['full_name']);
}
}
}
print $person;
Because your overwriting $person on each iteration.
Hold it in a $person[] array if your expecting more then one. Then loop through it with a foreach loop when you intend to output.
Not related but your also querying twice, you only need 1 $result = mysql_query($sql);
Update (Simple Outputting Example):
<?php
$person=array();
while($row = mysql_fetch_array($query)){
$person[] = array('full_name'=>$row['full_name'],
'email'=>$row['email'],
'somthing_else1'=>$row['some_other_column']);
}
//Then when you want to output:
foreach($person as $value){
echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>
Or an alternative way to is to build your output within the loop using concatenation.
<?php
$person='';
while($row = mysql_fetch_array($query)){
$person .= '<p>Name:'.$row['full_name'].'</p>';
$person .= '<p>Email:'.$row['email'].'</p>';
}
echo $person;
?>
Or just echo it.
<?php
while($row = mysql_fetch_array($query)){
echo '<p>Name:'.$row['full_name'].'</p>';
echo '<p>Email:'.$row['email'].'</p>';
}
?>

Categories