additional results/note in search - php

wondering if it is possible, that when you search a list of pages and data from a site, if you can not only order them in the most related first, but to also show a value.
ex. you search for data you previously entered regarding lemonade you sold. you keep track of multiple factors like "time of day, temperature, month, etc." you want to know about how much you are going to sell a week later, so you punch in values to "time of day, temperature, month, etc."
In theory, i am hoping to be able to bring up all entered data in accordance to relevance, and it shows you an estimate of what you will sell based on previous records. Any ideas?
Thanks

It would require an algorithm. i wont write all the code, but i wont mind giving some guidance :).
The html to fetch the data would be the same as the html to set the data, except it will call a seperate .php script.
The example below can be used for guidance. It uses only temperature to calculated predicted sales:
//get todays temperature from form, and query database for all temperatures
$todaysTemp = $_POST['temperature'];
$tempRange = 20; //each temperature in the table must be within this range of todaysTemp to be included in calculation
$result = $connection->query("SELECT temperature, sales FROM myTable");
//calculate average temperature by adding this temp to total, then diving by total rows included
$temp_sales_array = array();
foreach($result as $row){
if( abs($todaysTemp - $row['temperature']) < tempRange){
$temp_sales_array[$row['temperature']] = $row['sales'];
}
}
//calculate predicted sales, by getting array value thats closest to todays temperature
$closest=key($temp_sales_array[0]);
foreach($temp_sales_array as $row){
if( abs($todaysTemp - key($row)) < closest ){
closest = key($row);
$predicted_sales = $row;
}
}
//show predicted sales
echo $predicted_sales;

Related

Compare php MySQL query result arrays to get assosciated value from one of the arrays

I have one set of results with selected player ID's, and another set of results of all playerID's and the price they will pay and I don't know how to combine the two.
I think the easiest way to explain is to show what I have done so far and what I'm trying to figure out.
I have an input form which gives a dropdown menu (event type) and a list of checkboxes for players:
Event type: Match
X = Player1 Junior
_ = Player2 Senior
X = Player3 Senior
Submitting this gets the player ID's which I can access with this:
foreach ($_POST as $key => $value) {
echo $value;
}
I can then using below query, retrieve the prices that each player within the club would pay for the event, based on the event type and the category of the player.
SELECT prices.price, book.id
FROM prices
JOIN book
ON prices.cat = book.pricecat
WHERE eventType = ?('$eventtype') AND clubID = ?('$clubID')
So now I have these two sets of results
One containing the ID's of selected players.
The other containing all of the clubs playerID's and the Price to be paid for each.
How can I compare the two to get the prices for only the players selected?
Very new to PHP & SQL (4 long days of it!). I'm building the app for personal use and to trial it, need it done when hockey season starts in a week, so not had chance to learn properly from the beginning as I'd want to. Solved many problems but now my head hurts so I'll be very grateful for some advice on how I can solve this one!
Put your two sets of results into two arrays, and then loop through them.
$resultA = (firstset, with selected player names only);
$resultB = (secondset, with all the player names [0] and prices [1]);
$resultC = array(); // our final array that we'll build below
foreach ( $resultA as $selected )
{
foreach ( $resultB as $player )
{
if ( $selected == $player[0] )
{
$resultC[] = $player; // the "[]" adds an element to an array
}
}
}
var_dump($resultC); // show us the final array

Calculating time difference between two db values for multiple rows

I have a database which holds two timestamps (date_ticket_reported, date_ticket_resolved), I want to caluclate the average time difference between these times for each resolved_by user_id.
Each row has a (resolved_by) column which corresponds to a user_id.
There will be multiple rows, for each user_id.
I have tried various approaches including the following.
ticket_model.php code
public function get_resolved_time_by_user($user_id){
$query1 = $this->db->select('resolved_date')->from('tickets')->where('resolved_by',$user_id)->get();
$resolved1 = $query1->row();
$query2 = $this->db->select('ticket_date_reported')->from('tickets')->where('resolved_by',$user_id)->get();
$reported1 = $query2->row();
$resolved2 = $resolved1->resolved_date;
$reported2 = $reported1->ticket_date_reported;
foreach($resolved2 as $row){
//Convert them to timestamps
$reported_dateTimestamp = strtotime($resolved2);
$resolved_dateTimestamp = strtotime($reported2);
$diff = $resolved_dateTimestamp - $reported_dateTimestamp;
return $diff;
}
}
Ticket view code
<p> Average Resolve Times <?php echo $this->ticket_model->get_resolved_time_by_user($user_id); ?> </p>
So to summarise; I want to display the average time between date_ticket_reported, date_ticket_resolved. For each user_id specified.
Any help would be awesome!
I have tried Malkhazi Dartsmelidze answer,
$this->db->query("SELECT
AVG(TIMESTAMPDIFF(SECOND, resolved_date, ticket_date_reported)) as timediff,
resolved_by as user
FROM tickets
GROUP BY resolved_by");
I get an error saying Object of class CI_DB_mysqli_result could not be converted to string
Where you say resolved_by as user. Should "user" be the user_id? ie should it say "resolved_by as user_id"?
You Can run only One Query With Myqsl:
SELECT
AVG(TIMESTAMPDIFF(SECOND, resolved_date, ticket_date_reported)) as timediff,
resolved_by as user
FROM tickets
GROUP BY resolved_by
This returns Average Time Difference in Seconds for Each User
Try this
$resolved2 = $resolved1->resolved_date;
$reported2 = $reported1->ticket_date_reported;
$diff = $resolved2 - $reported;
And then echo $diff and check what you are getting in $diff,

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

I need some help creating a query and a database table to retroactively assign numbers to existing table

As my info states, I inherited the job of statistician for a local dart league. (Woohoo $20 a season)
I would love to implement an ELO rating system.
The current database table has over 100,000 entries.
There are 3 different games that are played. Singles, Doubles, and Team.
The originator of the database has the games entered as such:
Index Player1_num Player2_num Opp_Player1_num Odd_Player2_num H_team V_team Season Week W L Game_type
A singles game is entered twice.
values(1,20,null,30,null,200,300,11,2,1,0,301_singles)
and
values(2,30,null,20,null,200,300,11,2,0,1,301_singles)
It was done this way to facilitate easier look-ups of individuals.
A doubles game would have values such as
(3,20,21,30,31,200,300,11,2,1,0,501_doubles)
(4,21,20,30,31,200,300,11,2,1,0,501_doubles)
(5,30,31,20,21,200,300,11,2,0,1,501_doubles)
(6,31,30,20,21,200,300,11,2,0,1,501_doubles)
There again, it is built for easier queries for looking up wins and losses across seasons and with different partners.
A team game is:
(7,null,null,null,null,200,300,11,2,1,0,team_game)
So I added a match_num column to the table to help lump the games under 1 number.
However, I am unsure how best to assign the numbers, understandably, I don't feel like going through all 90k entries by hand.
Note: The early seasons were modified by hand and not all double matches have 4 entries (some only have 1). Some matches may be out of order as well (Instead of indexes: 1,2 they could be 1,9).
I don't know if you need more info for this, and I am unsure of how to post larger examples of the table.
Current code:
<body>
<?php
include "inc.php";
// Select Max Match Number
$sqlMatch="select max(match_num) from stats_results";
$match =mysql_query($sqlMatch);
$m= $match ? mysql_result($match,0):mysql_error();
$matchno= $m+1; // First Match number
$game=array("'301_singles'","'cricket_singles'","'501_singles'","'301_doubles'","'cricket_doubles'");
// selects max season
$sqlSeason="select max(season_index) from stats_season";
$season =mysql_query($sqlSeason);
$smax= $season ? mysql_result($season,0):mysql_error();
# $smax=2;
// for each season up to max season
for($s=1;$s<=$smax;$s++)
{
// Selects max week within the current season
$sqlWeek="select max(week) from stats_results where season=$s ";
$Week =mysql_query($sqlWeek);
$wmax= $Week ? mysql_result($Week,0):mysql_error();
# $wmax=2;
// for each week within current season up to the max week
for ($w=1;$w<=$wmax;$w++)
{
// each singles game
foreach($game as $g)
{
###########################################################################################################
$result = mysql_query("SELECT * FROM stats_results where season=$s and week=$w and game_code=$g ;") or die(mysql_error());
// Put them in array
for($i = 0; $rows[$i] = mysql_fetch_assoc($result); $i++) ;
// Delete last empty one
array_pop($rows);
//******************************************************
$matches=array();
foreach($rows as $record)
{
// Get a unique match code for this match
$matchid= getMatchID($record);
// Have we seen this ID before? If yes add this record index to the existing array
// otherwise create an array with just this value
if (!isset($matches[$matchid])) $matches[$matchid]= array($record['index_results']); // No
else $matches[$matchid][]= $record['index_results']; // Yes, add this Index
}
// Now $matches is an array of arrays of Index values, grouped by "match" so...
/* Sort $matches by key (see getMatchID for why!) */
ksort($matches);
// Update the table
foreach($matches as $match)
{
// Create SQL instruction to set the match_num for all the Index values in each entry
$sql= "UPDATE stats_results SET match_num = $matchno WHERE index_results IN (".implode(",", $match).")";
echo "<br>";
echo $sql;
/* Execute the SQL using your chosen method! */
// Move the match count on
$matchno++;
}
// End our loops
}
}
}
function getMatchID($gamerecord)
{
$index= "{$gamerecord['season']}-{$gamerecord['week']}-{$gamerecord['game_code']}-";
$players= array(
$gamerecord['player1_num'],
empty($gamerecord['player2_num'])?0:$gamerecord['player2_num'],
$gamerecord['opp_player1_num'],
empty($gamerecord['opp_player2_num'])?0:$gamerecord['opp_player2_num']
);
// Sort the players to get them in a consistent order
sort($players);
// Add the sorted players to the index
$index.= implode('-', $players);
return $index;
}
?>
</body>
(I'm putting this into an Answer so I can get it to layout a bit better - but it's not really a "solution" as such!)
I think what I'd do is try and build an array of arrays of Index values grouped by game - you can then use that to create SQL to update the table.
So, if $rows is an array of all records we'd do something like the following pseudo-code:
$matches= array();
foreach($rows as $record)
{
// Get a unique match code for this match
$matchid= getMatchID($record);
// Have we seen this ID before? If yes add this record index to the existing array
// otherwise create an array with just this value
if (!isset($matches[$matchid])) $matches[$matchid]= array($record['Index']); // No
else $matches[$matchid][]= $record['Index']; // Yes, add this Index
}
// Now $matches is an array of arrays of Index values, grouped by "match" so...
/* Sort $matches by key (see getMatchID for why!) */
ksort($matches);
// Update the table
$matchno= 1; // First Match number
foreach($matches as $match)
{
// Create SQL instruction to set the match_num for all the Index values in each entry
$sql= "UPDATE games SET match_num = $matchno WHERE Index IN (".implode(",", $match).")";
/* Execute the SQL using your chosen method! */
// Move the match count on
$matchno++;
}
So all that leaves is the getMatchID function - if we give each match a temporary ID based on it's season, week and a sorted list of it's participants (and use the Season and Week first) that should be unique for each game and we can sort by this index later to get the games in the right order. So again in rough pseudo-code, something like:
function getMatchID($gamerecord)
{
$index= "{$gamerecord['Season']}-{$gamerecord['Week']}-{$gamerecord['H_Team']}-{$gamerecord['V_Team']}-";
$players= array(
empty($gamerecord['Player1_Num'])?0:$gamerecord['Player1_Num'],
empty($gamerecord['Player2_Num'])?0:$gamerecord['Player2_Num'],
empty($gamerecord['Opp_Player1_Num'])?0:$gamerecord['Opp_Player1_Num'],
empty($gamerecord['Opp_Player2_Num'])?0:$gamerecord['Opp_Player2_Num']
);
// Sort the players to get them in a consistent order
sort($players);
// Add the sorted players to the index
$index.= implode('-', $players);
return $index;
}
So all being well $index would come back with something like 11-2-200-300-0-0-20-30 for the first singles match in your example - no matter which of the game records we were looking at.
Does that make sense/help at all?

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());

Categories