Update statement in MYSQL from PHP - php

I have a table as shown below
The output from said table
Green, is where a winner has been announced, whereas yellow means they have submitted a report, but a winner hasn't been decided yet. (winner field not populated)
$roundBound = Array();
$query = "SELECT MIN(id), MAX(id) FROM $tablename GROUP BY round";
if($result = $Login->mysqli->query($query)) {
while ($row = $result->fetch_row()) {
$roundBound[] = $row[0];
$roundBound[] = $row[1];
}
}
for($i = 0; $i < count($roundBound); $i = $i + 2) {
$match = 0;
for($j = $roundBound[$i]; $j < $roundBound[$i + 1]; $j = $j + 2) {
$id1 = $j;
$id2 = $j+1;
$query = "SELECT t1.winner, t2.winner FROM $tablename as t1, $tablename as t2 WHERE t1.id=$id1 AND t2.id=$id2";
$result = $Login->mysqli->query($query);
$row = $result->fetch_row();
$win1 = $row[0];
$win2 = $row[1];
if (isset($win1) && isset($win2)) {
if (isset($roundBound[$i + 2])) {
$id = $roundBound[$i + 2] + $match;
$query = "UPDATE $tablename SET
username = '$win1',
username2 = '$win2'
WHERE id = $id";
$Login->mysqli->query($query);
} else {
//Tourneydonneee yeeee
}
}
$match++;
}
}
Does anyone have a improvement, or an all-around different idea? This will be running quite often and could be potentially running on large record sets, so optimization would also be welcome.

as far as i understand you problem, i can suggest you to try
for ($i = 0; $i < count($arr); $i = $i + 2) {
$win1 = mysql_query("SELECT winner FROM tableName WHERE id=".(int)$i);
$win2 = mysql_query("SELECT winner FROM tableName WHERE id=".(int)$i+1);
$qry = "INSERT INTO tableName SET
username = $win1,
username2 =$win2,
....";
mysql_query($qry);
}

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

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

Check if FK order is numbered correctly

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)

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