putting variable into specific rows after math - php

i am trying to create a golf tourney scoreboard where i input the scores from each round and if i put in what course was played, it will go into the row of my sql database. how do i make a total score that is figured out in my php code go into a row that i specify on the form?
the form is built out like this:
<input name='name/handi/par/course/hole1/etc' type='text'>
to save space/time just short-handing the coding as much as possible. the php looks like this:
$name = $_POST['name/handi/par/course/hole1/etc'];
then i have the math broken out to figure the front 9, back 9, total score (with handicap [handi] worked in)
$totOut = ($hole1 + $hole2...etc)
$totIn = ($hole10 + $hole11 ... etc)
$total = ($totOut + $totIn) - $handi;
$o_u_total = $total - $par; (over/under for the week)
$o_u_today = $total - $par; (over/under for the day)
the total for today (b/c there are 4 rounds) and the total for the whole week. the totals for the whole week are worked out in a query on the display page:
$sql = "SELECT name,
SUM(total) AS Score,
SUM(o_u_total) AS Over_Under,
total AS Total_Today,
o_u_today AS Over_Under_Today
FROM matchplay
GROUP BY name
ORDER BY Score ASC";
$result = mysqli_query($conn, $sql);
and how i am trying to make the inputted value (course name) go into the specific row (designated in my sql dbase) is like this:
$ridge;
if ($_POST['course'] = 'The Ridge') {
($ridge = $total);
}
$cove;
if ($_POST['course'] = 'The Cove') {
($cove = $total);
} etc
i have a feeling that i am doing something terribly wrong with the if/else, but i don't know how else to choose what i want the $total to go into.
can anybody help me?

i figured it out ... thanks if anybody saw it and was in the middle of thumping me on the head with how easy it was
$ridge;
if ($_POST['course'] == 'The Ridge') {
($ridge = $total);
}
and not
$ridge;
if ($_POST['course'] = 'The Ridge') {
($ridge = $total);
}

Glad you did figure it out. To enhance your code and avoid multiple ifs, you can use a switch case statement.
$course_name = $_POST['course'];
switch($course_name){
case ('The Ridge'):
// your code here
break;
case ('The code'):
// an other code here
break;
}
Hope this help.

Related

Stopping a PHP loop when updating MySQL database

I'm creating a basic main menu for a stock market simulator where the price of a company will be updated periodically. For testing purposes, I need to make a loop to display the price of a share on the website five times (with the website automatically updating without refreshing) and to update the database at the same time.
I have successfully wrote some code which will both update the database with the current share price and will also update the website as well. However, when I have tried to include a loop I have come to a problem. I have included a loop to iterate five times but the problem that I am having is that the code continues to iterate even after five tries.
PHP:
<?php
$conn = mysqli_connect("localhost", "root", "", "prices");
if ($conn->connect_error)
{
die("Connection error: ". $conn->connect_error);
}
$result = $conn->query("SELECT `price` FROM `priceTable` WHERE `company` = 'Bawden'");
$x = 0;
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
echo $row['price'];
echo '<br><br>';
echo $x;
if ($x < 5)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
$x++;
}
}
}
?>
The above code will be displayed in a separate document with Javascript code and I can post this if required in the original post however I originally chose not to as I believe this is a PHP only problem. I have chosen to display $x to see if the value will increment. However, when running, the value of $x will stay at 0.
My expected result is that, on the website, there will only be five different updates and in the database, the database will only be updated five times.
However, my actual result is that the website and database are both continuously being updated, not stopping after five times.
I'm trying to limit the update command to only 5 updates yes. At the
moment, for testing purposes, there is only one company in my database
with one price only. So I'm updating this one company's price five
times
If you need to do the update 5 times for each row returned from the database, change your if statement to a for loop. Change this :-
if ($x < 5)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
$x++;
}
to this
for ($x = 0, $x < 5, $x++)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
}
This will repeat the process exactly 5 times and not rely on a separate counter (remove the other references to $x). Not sure why you would want to update the same record 5 times with different random values though.
The else will break the first loop, the second one will stop on the first while loop.
while ($row = $result->fetch_assoc())
{
echo $row['price'];
echo '<br><br>';
echo $x;
if ($x < 5)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
$x++;
}else{
break;
}
break;
}
What makes you think the loop should stop after 5 iterations?
You need to add the condition $x<5 in the while ($row = $result->fetch_assoc())
Edit following your comment
What you initially wrote is something like loop hundreds of times if need be and do something in the first 5 occurrences (starting loop 6, keep looping but do nothing).
Now for the 2nd half of your comment, I'm not sure what you mean.
What I see in your code is:
Select all prices for company = 'Bawden'
Update all the prices for company = 'Bawden' 5 times (loop) with a random value, the same one, on all the records.
Not enough information to tell for sure but I don't think it makes sense: on one hand, you except to have several records under company = 'Bawden (= reason why you created a loop), on the other hand, your update feels like it is written under the assumption there would be 1 record only...
Are you missing something like a price date from your table? What is the primary key of priceTable?
Try to post more technical details about your table (definition, sample of data) or it will be complicated to help further.

Improve performance when copying records from table to another one

Hi buddies :) I was required to create a php code to handle some workers' data stored in DB. I got the desired result but it takes seconds and seconds (seconds and seconds! >.<) to finish, so I'm afraid I'm not doing something in a right way :(
The workers' data is stored in a mysql table (table1), something like this:
I'm given a pair of dates: initial_date (a) and final_date (b), so my goal is to copy the given workers' data in a new table (table2), day by day from a to b. The expected table should be as shown below (this table will be used later as a basis for further operations, which is not part of the question)
It's a requirement to overwrite any existing data between a and b dates, and 'jump' weekends and holidays.
To get my goal, I'm coding this (let's assume that the connection and all that is done and the checkworkingday function is given):
$initialdate = '2016-10-10';
$finaldate = '2016-10-12';
$x = $initialdate;
do {
if (checkworkingday($x) == true) {
$query = mysqli_query($connection,"SELECT name,task FROM table1");
while($row = mysqli_fetch_array($query)) {
$task = $row['task'];
$worker = $row['name'];
$query2 = mysqli_query($connection,"SELECT task FROM table2 WHERE name = '$worker' AND date = '$x'");
$row2 = mysqli_fetch_array($query2);
$existingtask = $row2['task'];
if (!isset($existingtask)) {
mysqli_query($connection,"INSERT INTO table2 (date,name,task) VALUES('".$x."','".$worker."','".$task."')");
} else {
mysqli_query($connection,"UPDATE table2 SET task = '".$task."' WHERE date = '".$x."' AND worker = '".$name."'");
}
}
}
$x = date('Y-m-d', strtotime($x . "+1 day"));
} while ($x <= $finaldate);
Just for 3 days as shown in the example, it takes a long to end; and for several weeks or months it takes very, very long (even max execution time is exceeded depending on dates range!).
I'm a newbie and I know the code is quite 'rustic', but I've revised and checked the code and info out there without getting a better performance. What am I doing wrong? Thanks :)
Instead of looping through the enitre data, try INSERT.. SELECT :
INSERT INTO table2 (date,name,task)
SELECT date,name,task
FROM Table1
WHERE < >;

Renaming and Inserting Array results into a different table

//First I'm assigning a $variable ($emailzipmatch) to query a database table called(repzipcodes) and having it pull and display 1 to 3 records based on matching up a customer's zip code (RepZipCode = $CustomerZipMatch) with 1 to 3 other people (GROUP BY RepId HAVING COUNT(1) <= 3") that want that customer's information from that particular zip code.
// CODE WORKS BELOW
$emailzipmatch = mysql_query("SELECT * FROM repzipcodes WHERE RepZipCode = $CustomerZipMatch GROUP BY RepId HAVING COUNT(1) <= 3") or die(mysql_error());
$recipients = array();
while($row = mysql_fetch_array($emailzipmatch))
{
$recipients[] = $row['RepEmail'];
echo "Agent's Email Address: ";
echo 'font color="#FF7600"',$row['RepEmail'], '/font';
echo '<br />';
echo "Rep's ID: ";
echo '<br />';
echo 'font color="#FF7600"',$row['RepId'], '/font';
echo '<br />';
echo 'hr align="left" width="50%" size="2" /';
}
//MY PROBLEM BELOW
// For the NEXT step of the process above I would take $row['RepEmail'] and $row['RepId'] which can have 1 to 3 results and assign the 1 to 3 results a new $variable so it can be inserted into a different db table so I can track the results of the query ($emailzipmatch = ) from the top of the page: ie..
<New Variable> <Listed from above>
$SentRepId 0 = RepId (results from above echo area)
$SentRepId 1 = RepId (results from above echo area)
$SentRepId 2 = RepId (results from above echo area)
// Below I'd like to insert the above results into a new database
$?Variable??? = mysql_query("INSERT INTO sentemail
(SentRepId0, SentRepId1, SentRepId2,SentDateTime
) VALUES (
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', // ?????
NOW()
)") or die(mysql_error());
//Thank ahead of time for any help you guys can give me. Please respond with ANY question if my coding or request isn't clear or if I've been confusing due to my lack of experience with PHP and MySQL.
I think I know what you are going for here. I have done something similar before where I needed to keep a record for a while so I gave each search result an id on output and placed them in separate rows of a table along with a time stamp so it could be cleaned up at a later time or if you wish to search by time (mysql has a timestamp of it's own also but that's another thing to look in to if you haven't already)
So to make a 'log table' for example you might want to design something that works like the following:
<?php
$search_id = md5(uniqid()).rand(100,999); //// MAKE AN ID FOR THE SEARCH;
$timestamp = time(); // IN CASE YOU WANT TO CLEAN UP AT A LATER DATE, MUST BE AN INTEGER IN MYSQL (so you can use a less than $timestamp in the delete query)
$emailzipmatch = mysql_query("SELECT * FROM repzipcodes WHERE RepZipCode = $CustomerZipMatch GROUP BY RepId HAVING COUNT(1) <= 3") or die(mysql_error()); // if you are just wanting to limit the results look at LIMIT in a mysql tutorial somewhere.
$recipients = array();
while($row = mysql_fetch_array($emailzipmatch))
{
//// THE REST OF YOUR CODE HERE (and at the end of the while loop insert in to a table, in your case 'sentemail')
mysql_query("INSERT INTO sentemail (search_id, rep_email, rep_id, zip_code, timestamp) VALUES ('$search_id', '{$row['RepEmail']}', '{$row['RepId']}', $CustomerZipMatch, $timestamp);") or die(mysql_error()); // or what ever details you are after
}
?>
This should leave you with a reference table that you can search for by different criteria. Not the most perfect way of doing it but it will get the job done.
Hope that gives you a different perspective on it :)
In regards to "due to my lack of experience with PHP": As you develop your skills, and you will I'm sure, take some time to look at Object Oriented PHP in the future. For more server heavy or complicated things it can be worth knowing. I'm saying this to you now because I wish someone had told me earlier.
Good luck.
As long as you have user access, you can do:
$?Variable??? = mysql_query("INSERT INTO db1.sentemail (SentRepId0, SentRepId1,SentRepId2,SentDateTime) VALUES (
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', NOW())") or die(mysql_error());

PHP List Menu Boxes - Best way to do the cycle?

This is part of code from my backoffice page. ( is an edit.php page for a user to edit / modify )
// first query to get cats from user table
$query = "select * from user where name='".$_SESSION['username']."' order by id ASC limit 1";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row=mysql_fetch_array($result)){
$cat1 = $row['cat1'];
$cat2 = $row['cat2'];
$cat3 = $row['cat3'];
$cat4 = $row['cat4'];
$cat5 = $row['cat5'];
$cat6 = $row['cat6'];
$cat7 = $row['cat7'];
$cat8 = $row['cat8'];
$cat9 = $row['cat9'];
$cat10 = $row['cat10'];
}
}
// now i want to build 10 select boxes with selected according the user table $cats
// below is what i can build to first box $cat1
// is there a way i can produce this for the 10 select boxes whitout having to make 10 cycles of bellow code
<select name="theme" id="theme">
<?php
$q1 = 'SELECT * FROM cats ORDER BY title ASC';
$r1 = mysql_query($q1);
while( $row = mysql_fetch_array($r1)) {
if ( $cat1 == $row['id'] ) {
print "<option class=\"cssoption\" selected=\"selected\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
else {
print "<option class=\"cssoption\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
}
?>
</select>
I am not a coder so this might not be effective code.
Hope someone can help me here and understands what i am trying to do.
Many Thanks.
The code is fine. This 10 cycles as you name it is a almost zero cost.
This is the usual way we do it, we fetch sequentialy the records one by one.
In addition it makes no sense to ask not to do the 10 cycles because you are applying an if else condition in the same time, this means that you check every record if the cat id is the same with the row so you need the loop.
On the other hand if for some reason you want to skip some records, you can use the mysql seek function to start fetching from the desired record.
for($i=0;$i<99999;$i++)
(9999*9999);
echo 'This time the cost of this loop was:',(microtime()-$start),' seconds.';
?>

How to make a "distinct" detection on a foreach loop

At this time I have this very complex query that I loop through and I get something like this:
List of Challenges:
TEAM A
- Challenge 1
TEAM A
- Challenge 4
TEAM A
- Challege 6
And I want to change to something like:
TEAM A
- Challenge 1
- Challenge 4
- Challenge 6
My question is, since the query is a very complex one, maybe I could do this inside the loop but, if that's the case, how can we achieve something like that?
Can I ask an example case so that I can use, in order to solve this issue?
Thanks a lot,
MEM
UPDATE:
The query is something like this:
Translated:
public function listachallengesPendentes()
{
$select = $this->getAdapter()->select();
$select->from(array("e"=>"teams"),array('name'));
$select->join(array("de"=>"challengeperteam"),"e.cod_team = de.cod_teamFk",array());
$select->join(array("d"=>"challenges"),"d.cod_challenge = de.cod_challengeFk",array('title'));
$select->columns(array("e.cod_team"
,"name_team"=>"e.name"
,"d.cod_challenge"
,"name_challenge"=>"d.title"
,"d.details"
,"d.score"
,"category"=>"d.cod_categoryFk"
,"de.proof"
,"de.date_concluded"
,"de.cod_challenge_team"
));
$select->where("de.status = 0");
$select->order(array('e.cod_team DESC', 'de.cod_challenge_team DESC'));
return $this->getAdapter()->fetchAll($select);
}
So I need to add a distinct some part :s :D ?
The foreach actually is pretty basic:
foreach ($challenges as $d){
//display the name:
echo $d['name_team'];
...
}
UPDATE 2
The clean query (not tested):
SELECT e.name
,d.cod_team
,d.cod_challenge
,d.title
,d.details
,d.score
,de.proof
,de.date_concluded
,de.cod_challenge_team
FROM teams e
INNER JOIN challengeperteam de ON de.cod_teamFk = e.cod_team
INNER JOIN challenges d ON d.cod_challenge = de.cod_challengeFk
WHERE de.status = 0
ORDER BY e.cod_team DESC, de.cod_challenge_team DESC;
Something along the lines of:
$current_team = null;
foreach($challenges as $challenge){
if($current_team != $challenge->team){
$current_team = $challenge->team;
echo $current_team, "\n";
}
echo $challenge->challenge_name, "\n";
}
At a very basic level, ie in the loop, you can just detect if the TEAM A variable is equal to the current (previous) value, and if so, don't print it a second time. This relies on the result set being sorted on the TEAM A column.
However, you can also do this in the SQL query, so if you can provide the current SQL Query, I can explain how you'd update it.
you could store the array results in a multi-dimensional array like so:
$query_Challenges = "SELECT `Team`,`Challenges` FROM YourTable";
$Challenges = mysql_query($query_Challenges, $dbconnection) or die(mysql_error());
$row_Challenges = mysql_fetch_assoc($Challenges);
$challengeResults = array();
do{
if(!array_key_exists($row_Challenges['cod_team'])){
$challengeResults[$row_Challenges['cod_team']] = array();
}
$challengeResults[$row_Challenges['cod_team']][] = $row_Challenges['cod_challenge_team'];
}while($row_Challenges = mysql_fetch_assoc($Challenges));
EDIT
looking at your query statement, the data should be already sorted properly by your ORDER clause, so if you just need not repeatedly print the team as shown in codeblock 2, then something like:
$team = '';
do {
if($team != $row_Challenges['cod_team']){
echo "TEAM $row_Challenges['cod_team']<br/>";
$team = $row_Challenges['cod_team'];
}
echo " - $row_Challenges['cod_challenge_team']<br />";
}while($row_Challenges = mysql_fetch_assoc($Challenges));
you could easily substitute a foreach for the do loop, as long as there is a variable used as the "current team" and an if statement used to say "dont print the next team name unless its different than the current team name"

Categories