Check if FK order is numbered correctly - php

I have some absences, and each absence has an FK to an employee, which I wanna display in a generated HTML table. However, if I delete an employee the order changes from 0, 1, 2 to 1, 2 (for example if the second employee got deleted).
This messed up my code, because I need the FK to check where I have to insert the leave (in which <tr>). Here I count the employees:
$result = mysql_query("select count(1) FROM employee");
$row = mysql_fetch_array($result);
$count_user = $row[0];
Later in my code I make a query in a loop. The loop runs as many times as there are users. And heres the problem: if an employee gets deleted it will not reach the other one ($i goes 0 and then 1 if there are 2 users, but if one is deleted the FK is 3, so it would need to go one further).
to
$result = mysql_query("select start, end, type_FK, employee_FK FROM absences where employee_FK = $i");
while ($row = mysql_fetch_assoc($result)) {
$array_absences[] = $row;
}
Has anyone an Idea that is not based on the FK order?
Also this topic needs a better title so feel free to edit it.
<html>
<head>
<title>Absence System</title>
</head>
<body>
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("absence_system", $con);
$result = mysql_query("select count(1) FROM employee");
$row = mysql_fetch_array($result);
$count_user = $row[0];
$result = mysql_query("select count(1) FROM absences");
$row = mysql_fetch_array($result);
$count_absences = $row[0];
$result = mysql_query("select name, surename, employee_ID FROM employee");
while ($row = mysql_fetch_assoc($result)) {
$array_user[] = $row;
}
for($i = 0; $i < $count_user; $i++){
echo '<table = border = 1px>';
echo '</tr>';
$result = mysql_query("select start, end, type_FK, employee_FK FROM absences where employee_FK = $i");
while ($row = mysql_fetch_assoc($result)) {
$array_absences[] = $row;
}
$count = count($array_absences);
echo $count;
print_r($array_absences);
for($j = 0; $j < 32; $j++){
$true = 0;
if($j == 0){
echo '<td>';
echo $array_user[$i]['name'], " ", $array_user[$i]['surename'] ;
echo '</td>';
}
for($k = 0; $k < $count; $k++)
{
$array_absences[$k]['start'] = substr($array_absences[$k]['start'], -2);
$array_absences[$k]['end'] = substr($array_absences[$k]['end'], -2);
$array_absences[$k]['start'] = ereg_replace("^0", "", $array_absences[$k]['start']);
$array_absences[$k]['end'] = ereg_replace("^0", "", $array_absences[$k]['end']);
if($j == $array_absences[$k]['start'] && $array_absences[$k]['employee_FK'] == $i){
$true = 1;
echo '<td>';
echo $array_absences[$k]['type_FK'];
echo '</td>';
}
}
if($j != 0 && $true == 0){
echo '<td>';
echo "$j";
echo '</td>';
}
}
echo '</tr>';
echo '</table>';
}
?>
</body>
</html>

If employee_ID corresponds to employee_FK, then you should not iterate over $count_user, but rather over $array_user - then your select would looke like this:
$result = mysql_query("select start, end, type_FK, employee_FK FROM absences where employee_FK = {$array_user[$i]['employee_ID']}");
while $i will still represent sequence number, because
$count_user == count($array_user)

Related

How can I make this code short and easy to read?

I have more than 10 lines like this and I want to echo just 5 rows per page this is my code.
$c = mysqli_fetch_field_direct;
$c1 = $c($result,2)->name;
$c2 = $c($result,3)->name;
$c3 = $c($result,4)->name;
//$cn,...;
echo "$row[2]" ; echo "$c1[2]";
echo "$row[3]" ; echo "$c1[3]";
//echo "$row[n]" , ...;
Before this code I have this:
$sql = "SELECT * FROM sheet1 WHERE id = '$_POST[text]'";
$result = mysqli_query($con,$sql);
If ($row = mysqli_fetch_array($result))
{
//the 10 lines of codes above
}
You may want to loop through these elements:
$sql = "SELECT * FROM sheet1 WHERE id = '$_POST[text]'";
$result = mysqli_query($con,$sql);
If ($row = mysqli_fetch_array($result))
{
for($i = 2; $i < 10; $i++){
$c = mysqli_fetch_field_direct($result,$i)->name;
echo $row[$i] ; echo $c[$i];
}
}

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

PHP Counting MYSQL rows issue?

I am trying to make it to if I have at least 1 team created for one person, it will display the team. If they don't have a team, it will say no teams. It works if the person has at least 1 team, but nothing shows if the person is not on a team. How do I fix this?
<?php
$sql = mysql_query("SELECT * FROM teams WHERE players LIKE '%$sessiongamt%'") or die("Could not allocate information!");
$num = 0;
while($row = mysql_fetch_assoc($sql)){
$num = ++$num;
$amount1 = mysql_num_rows($sql);
$name = $row["name"];
$teamrank = $row["rank"];
$teamlink = $row["link"];
$players = $row["players"];
$teamid = $row['id'];
if($amount1 < 1){
$teams = "No Teams";
echo "$amount";
}else{
$teams = "$name";
echo "<a href='$teamlink?id=$teamid'>$teams</a>";
}
}print "$amount1";
?>
Look at the third line of this code - put it in your code on the same place instead of your line.
if($amount1 < 1){
$teams = "No Teams";
echo $teams;
}else{
$teams = "$name";
echo "<a href='$teamlink?id=$teamid'>$teams</a>";
}
Put the counting outside the while... loop
$sql = mysql_query("SELECT * FROM teams WHERE players LIKE '%$sessiongamt%'") or die("Could not allocate information!");
$amount1 = mysql_num_rows($sql); //<---- this should fix it
$num = 0;
while($row = mysql_fetch_assoc($sql)){
$num = ++$num;
$name = $row["name"];
$teamrank = $row["rank"];
$teamlink = $row["link"];
$players = $row["players"];
$teamid = $row['id'];
$teams = "$name";
echo "<a href='$teamlink?id=$teamid'>$teams</a>";
}
if($amount1 < 1){
$teams = "No Teams";
}
print "$amount1";
?>

how do I traverse rows in a table

I have a table named members with 3 rows. The following code attempts to display all the rows in the members table. It displays the 1'st record 3 times instead of displaying each record once.
<?php
$con = new mysqli("localhost", "root", "jce123", "profile");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
$keysarray = array_keys($array);
$valuearray = array_values($array);
for ($i=0; $i < $num; $i++) {
for($j = 0; $j < count($array); $j++) {
echo "<table>";
echo "<tr><td>".$keysarray[$j].": </td><td>".$valuearray[$j]."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
mysqli_close($con);
?>
I've updated this per suggestions:
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
while ($row = mysqli_fetch_assoc($res)) {
foreach($array as $key => $value){
echo "<table>";
echo "<tr><td>".$key.": </td><td>".$value."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
That's because, your $num = 3, count($array) = 3 and the outer for loop has no bearing on inner for loop.
Where you have $array = mysqli_fetch_assoc($res);, you will only receive one row from your database. You need something like:
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
}
Any basic tutorial will tell you this. Even the PHP docs provide an example.
you can use do something like this..
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
e.g
echo $row['id'];
echo $row['name'];
etc
}
try this... this peace of code is not tested but just to give you an idea...
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
echo "<table>";
echo '<tr><td> id = "'.$row['id'].'":
</td><td> name = "'.$row['name'].'"</td></tr>";
echo "</table>";
}

PHP paging, viewing a certain page first

This is my script for the paging on my site when the user clicks on a league.
The league is then echoed to the screen, and if the league is over 3 rows then it splits it up in to several pages.
What I am doing after is depending on where the user is in the league (the SQL query is using ORDER BY the total points column in the table), e.g if the user is on page one of the league table then for it to display that page first, but if the user is on page 3 of the league table then for that page to displayed first.
Does anyone know a way in order for me to achieve this?
//Recently updated from answer
$sql="SELECT members.username, members.total_points FROM members, members_leagues WHERE members.username = members_leagues.username AND
members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC";
$result=mysql_query($sql);
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row($result)){
if ($row[username] == $_SESSION[username]) {
$team_position = $i;
$found = true;
}
$i++;
}
$rowsPerPage = 3;
$pageNum = ceil($i/$rowsPerPage);
//end of recently updated
if(isset($_GET['page']))
$pageNum = $_GET['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$counter = $offset + 1;
$query = " SELECT members.username, members.teamname, members.total_points, FROM members, members_leagues WHERE members.username = members_leagues.username AND members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC " . " LIMIT $offset, $rowsPerPage";
$result = mysql_query($query) or die('Error, query failed');
echo "<h3 style=\"color:red;\">$chosenleague</h3>";
echo "<table>";
echo "<tr><th>Position</th>";
echo "<th>Team</th>";
echo "<th>Points/Overall</th>";
echo "<th>Points/Last Race</th>";
echo "<th>Team Setup</th></tr>";
while($row = mysql_fetch_array($result))
{
if($row[username] == $_SESSION[username])
echo "<tr style=\"color:red;\"><td>";
else
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $row[teamname];
echo "</td><td>";
echo $row[total_points];
echo "</td><td>";
echo "</td><td>";
echo "</td></tr>";
$counter++;
}
echo "</table>";
$query = "SELECT COUNT(members.username) AS numrows FROM members, members_leagues WHERE members.username = members_leagues.username
AND members_leagues.sub_league = '$chosenleague'";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxPage = ceil($numrows/$rowsPerPage);
$self = $_SERVER['PHP_SELF'];
$nav = '';
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " << Prev ";
$first = " First ";
}
else
{
$prev = '';
$first = '';
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " Next >> ";
$last = " Last ";
}
else
{
$next = '';
$last = '';
}
echo "<div id=\"pagenum\">Page $pageNum of $maxPage ". $first . $last . $prev . $next ."</div>";
You can do it via mysql or php:
With PHP:
Found the position of the requested record in the array, then calculate the page you have to extract and execute the corresponding query. Something like.
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row) {
if ($row['team'] == 'team_your_searching_for') {
$team_position = $i;
$found = true;
}
$i++;
}
//calculate $top and $bottom
...
$sql = "SELECT * FROM members LIMIT $top, $bottom;";
...
With MySQL:
You can create a query that generates an autoincrement value and another that selects from the other's result. I mean
-- get the the selected member's position
SELECT team, pos FROM (SELECT team, points, #position = #position + 1 AS pos FROM members ORDER BY points) WHERE team = #the_team_your_searching_for;
-- get the nr of members
SELECT COUNT(*) FROM members;
...
-- calculate the page you wanna extract (#top, #bottom), and extract it
SELECT * FROM members LIMIT #top, #bottom;

Categories