I am definitely stumped on how to arrange a result set.
I have a table which currently contains strictly dates.
DATES
ID Dates
1 2015-05-26
2 2015-05-27
3 2015-05-28
4 2015-05-29
5 2015-05-30
each of those dates are also the name of the table for that day which keeps track which user/agent was present for training.
2015-05-26
ID Attendance
101 Present
201 N/A
301 Present
401 Present
501 Present
The end goal for this is to create the following table:
Now here is what I have accomplished for the table header.
$data_date = true;
$list = "SELECT * FROM list ORDER BY id DESC LIMIT 5";
$result = mysql_query($list);
while ($row = mysql_fetch_assoc($latest)){
$dates[] = $row['date'];
}
foreach($dates as $x){
$data_date .= "<th>$x</th>";
}
By simply echoing out the $data_date I am able to display the headers like the following.
<table>
<tr>
<th>AGT</th>
<?php echo $data_date; ?>
</tr>
<tr>
</tr>
</table>
So far so good. The final step of taking the array and creating new row for each and querying each day from the dates array has me at a loss.
I've been trying for over an hour and cant seem to wrap my head around the array needed to query a new row for each agent.
Any pointers or help would definitely be appreciated.
perhaps this is a start. date-math routines can grab 5 day attendance results
consider the following
create table agent
(
agentid int NOT NULL PRIMARY KEY, -- use AUTO_INCREMENT, whatever
agentname varchar(60)
);
insert agent (agentid,agentname) values (109,'Guy Smiley');
insert agent (agentid,agentname) values (110,'Susie Chapstick');
-- select * from agent
create table class_session
( -- a session is say Monday to Friday, captures a start date
sessionid int not null PRIMARY KEY, -- the week session #
startdate datetime not null,
location varchar(40) -- etc etc
);
insert class_session (sessionid,startdate,location) values (1001,'10/1/2014','Ritz London');
create table session_signup
( -- the list of agents who should be present
sessionid int not null, -- the week session #
agentid int not null
);
create table agent_present
(
sessionid int not null, -- the week session #
agentid int NOT NULL,
thedate datetime not null,
thestatus varchar(40) -- present, present but sleeping, etc
);
Related
I am tracking a users activity while not logged in with a cookie_id and grouping these by date. When the user logs in I want to transfer all records from their cookie_id to their user_id. The cookie_id and user_id dates can overlap if the user is using different machines throughout the day.
For example, a user with a user_id of 1 logs in from work, but from home she doesn't so we assign her a cookie_id of 123.
The table data could look like this.
id user_id cookie_id date
2 1 NULL 2015-09-07
18 1 NULL 2015-09-10
19 NULL 123 2015-09-10
21 NULL 123 2015-09-11
22 1 NULL 2015-09-11
24 NULL 123 2015-09-12
Finally, one fine Saturday, she decides to log into her account from home.
What I would like to do is merge all of the records that have a coresponding user_id / date record, and update the row with a cookie_id of 123 with the user_id of 1 grouping by date creating any new records that are needed. I'd also like the related bananas table to be updated apprpriately as well.
id user_id cookie_id date
2 1 NULL 2015-09-07
18 1 NULL 2015-09-10
22 1 NULL 2015-09-11
24 1 NULL 2015-09-12
I am using Laravel and would like to use query builder. I have all of the code except the database query working. I am happy to post it up, if anybody thinks it is useful.
My table structure is below and I have made a SQLFiddle.
banana_groups
id int(10),
user_id int(10),
cookie_id varchar(255),
date date NOT NULL,
bananas
id int(10),
banana_group_id int(10),
monkey_id int(10),
EDIT
To embrace the spirit of SO and in response to vho's comment (which mysteriously disappeared), here is my attempt to write this SQL. Needless to say, it is incomplete and doesn't work.
Select *
FROM banana_groups AS m
WHERE EXISTS
(SELECT 1 FROM banana_groups WHERE m.user_id = 2)
AND NOT EXISTS
(SELECT 1 FROM banana_groups WHERE ...
I ended up writing a stored procedure to do this. I will leave the question unanswered so if anybody knows how to do this without a stored procedure I mark their answer correct.
CREATE PROCEDURE `transfer_bananas`(IN _cookieId VARCHAR(255), IN _userId INT)
BEGIN
DECLARE v_id INT;
DECLARE v_user_id INT;
DECLARE v_date DATE;
DECLARE v_done INT DEFAULT 0;
DECLARE cur_banana CURSOR FOR
SELECT id, `date`, (SELECT id from banana_groups
WHERE user_id = _userId AND
`date` = q.date) AS userId FROM banana_groups AS q
WHERE cookie_id = _cookieId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = 1;
OPEN cur_banana;
loop_banana: LOOP
FETCH cur_banana INTO v_id,v_date, v_user_id;
IF v_done = 1 THEN
LEAVE loop_banana;
END IF;
IF(v_user_id IS NULL) THEN
UPDATE
banana_groups
SET
user_id = _userId,
cookie_id = NULL
WHERE
id = v_id;
ELSE
UPDATE
bananas
SET
banana_group_id = v_user_id
WHERE
banana_group_id = v_id;
DELETE FROM
banana_groups
WHERE
id = v_id;
END IF;
END LOOP loop_banana;
CLOSE cur_banana;
END
I call it from Laravel with
DB::statement(DB::raw('CALL transfer_bananas(\''
. $cookie_id
. '\', '
. $user->id
.');'
));
I need help building a SQL query which searches for an user_id (let's say user_id = 5), but this user_id has multiple row entries, but I need to update each row differently though.
I have an array with data which I want to assign to that user_id. Here is a table example:
id user_id amount txn_id
1 5 10 foo_unique
2 5 5 bar_unique
3 7 15 xyz_unique
4 5 10 123_unique
My array would look something like this:
Array (
[0] => 14
[1] => 6
[2] => 9
)
As you see I have three array values and three rows for user_id 5, now I want to add each value of that array, to the corresponding user_id (5). Note that I have an UNIQUE column named txn_id
After updating the table, it would look like this:
id user_id amount txn_id
1 5 14 foo_unique
2 5 5 bar_unique
3 7 6 xyz_unique
4 5 9 123_unique
Any ideas how I could achieve this?
Thanks.
P.S: I cannot use SQL CASE on this issue.
If you want to update one row with a value, you have to be able to have a unique condition for that row.
Without adding some extra field, or condition to uniquely identify a row, you are out of luck.
You can use the following query:
UPDATE MyTable
SET
amount =
CASE id
WHEN 1 THEN 14
WHEN 2 THEN 6
WHEN 3 THEN 9
ELSE amount -- just in case user_id 5 has records not covered above.
END
WHERE
user_id = 5
The problem is, there is nothing on your array that says which array entry belongs to which database row. If you want to rely just on the orders (of the array indices, and the database ids,), you have to SELECT all rows for the user first, then loop and update a row at a time. Something like this on PHP (and PDO):
$values = array(14, 6, 9);
$dbh = new PDO('mysql:host=localhost;dbname=yourdbname', 'username', 'password');
$selectQuery = 'SELECT id FROM yourtable WHERE user_id = 5 ORDER BY id';
foreach($dbh->query($selectQuery) as $row) {
$id = $row['id'];
$sth = $dbh->prepare("UPDATE yourtable SET amount = :val WHERE id = :id");
$sth->execute(array(
'val' => array_unshift($values),
'id' => $id
));
}
(Code above assumes the number of values on your arrays matches the number of database rows for user_id = 5).
Looking at the problem you only need to have SQL statements.
First is to create two tables:
CREATE TABLE users
user_id int(11) PRIMARY KEY NOT NULL,
username varchar(25),
) Engine = InnoDB;
CREATE table userbalances (
balance_id int(11) PRIMARY KEY NOT NULL,
user_id int(11),
amount decimal(10,2),
CONSTRAINT userid_fk FOREIGN KEY userid_fk(user_id) REFERENCES users(userid)
) Engine = InnoDB;
Then, after you have INSERT(ed) all of the users and userbalances inside the table, all you need to do is create an UPDATE statement to update the amount:
UPDATE userbalances SET amount=? WHERE user_id=? AND balanceid=?
The update should be in a loop. And you should use mysql_query() function to update it with the assigned arrays that you have.
Note:
Both userid and balanceid should be in the WHERE clause of your UPDATE statement because you have multiple transactions inside the userbalances table. Otherwise, it's going to change all of the balances of all the transactions of that user.
Problem update:
If you don't use any SQL Cases on this problem, then your problem is just PHP. You need to find out what is the function for UPDATE(ing) - to update the amounts. As long as your tables are all prepopulated. There might be a function on the program you use to update it.
I have a MySQL table which has the following columns
urlByCustomer table
----------------------------------------------
|customerID | TeamID | date | numUrlsConsumed|
----------------------------------------------
| | | | |
----------------------------------------------
urlmapping
Column Type Null Default Comments MIME
urlMappingID bigint(20) No
customerID int(11) Yes 0
activityID int(11) Yes 0
contactID int(11) Yes 0
fullURL mediumtext Yes NULL
lastModified timestamp No CURRENT_TIMESTAMP
developerSandbox varchar(25) Yes
I've got this code that is being executed to update the table
$start = strtotime(date('Y-m-d 00:00:00'));
$end = strtotime(date('Y-m-d 23:59:59'));
$countAllThisGuysVals = "SELECT COUNT( DISTINCT`customerID`,`fullURL`)
FROM `urlmapping`
WHERE `urlMappingID` >= $ORIGINAL_COPY
AND `customerID` = $currentCustomerID";
$countTheVals= $conn->query($countAllThisGuysVals);
$countedfinal =0;
foreach ($countTheVals as $countRow) {
$countedfinal = array_sum($countRow)/2;
}
$tableUpdateQuery = "UPDATE `urlByCustomer`
SET `date` = NOW()
WHERE `customerID`= $currentCustomerID AND
UNIX_TIMESTAMP(`date`) BETWEEN '{$start}' and '{$end}'";
$conn->exec($tableUpdateQuery);
$tableUpdateQuery = "UPDATE `urlByCustomer`
SET `numUrlsConsumed` = $countedfinal
WHERE `customerID`= $currentCustomerID AND
UNIX_TIMESTAMP(`date`) BETWEEN '{$start}' and '{$end}'";
$conn->exec($tableUpdateQuery);
echo "update path <br>";
$tableModified = true;
$originalLPID++;
Variables are pretty much all declared, but the declarations are spread out, so I'm just posting this part to shorten it. The update query to the date column seems to be working, but the second update isn't. It worked 17 minutes ago though, so I'm confused since the only thing that changed between the next test was that I added some new values that should be causing it to update that column.
Idk. I guess one possiblity could be the UNIX_TIMESTAMP. I'm running this in Parallels on a Mac, so I'm not sure what that translates to for timestamps.
It looks like you're changing the value of "date" in your first update, without considering the fact that your second update will now not find the same rows in the WHERE clause (as you've just changed the date).
You can do the updates in a single statement: :
UPDATE urlByCustomer
SET `date` = NOW()
, numUrlsConsumed = $countedfinal
WHERE customerID= $currentCustomerID
AND UNIX_TIMESTAMP(`date`) BETWEEN '{$start}' and '{$end}'
I'm trying to change my rating system which only used one table before but now I'm changing it to use multiple tables and I really dont no how to
update or insert a new rating into the database and was wondering how to do this using my MySQL tables structure?
Also how do I do this by adapting the new code to my current PHP code which I want to change which is listed below.
First let me explain what my tables do they hold the information when students rate there own teachers I listed what the tables will hold in the
examples below to give you a better understanding of what I'm trying to do. Students are only allowed to rate there teachers once.
I provided the two MySQL tables that should be updated which are listed below.
My MySQL tables
CREATE TABLE teachers_grades (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
grade_id INT UNSIGNED NOT NULL,
teachers_id INT UNSIGNED NOT NULL,
student_id INT UNSIGNED NOT NULL,
date_created DATETIME NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE grades (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
letter_grade VARCHAR(2) NOT NULL,
grade_points FLOAT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (id)
);
What the database will hold.
teachers_grades
id grade_id teachers_id student_id date_created
1 3 2 32 2010-01-23 04:24:51
2 1 32 3 2010-01-23 12:13:58
3 2 32 103 2010-01-23 12:24:45
grades
id letter_grade points
1 A+ 10
2 D 3
3 B 5
Here is the old PHP code.
// function to insert rating
function rate(){
$text = strip_tags($_GET['rating']);
$update = "update vote set counter = counter + 1, value = value + ".$_GET['rating']."";
$result = mysql_query($update);
if(mysql_affected_rows() == 0){
$insert = "insert into vote (counter,value) values ('1','".$_GET['rating']."')";
$result = mysql_query($insert);
}
}
Old table.
CREATE TABLE vote (
`counter` int(8) NOT NULL default '0',
`value` int(8) NOT NULL default '0'
);
first , do mysql_escape_string to the parametrs when inserting like :
mysql_real_escape_string($_GET['rating']);
second
you need to get all parameters (from GET or POST) and insert it to the db ,
the teacher_id ....
now i only see the rating.
Your old table was bit confusing as it seems like it only rates 1 teacher or teachers as a whole.
Now it seems like your new design process requires you to:
- store rating and averages of teachers
- track historical ratings from students
rating table should look something like
Table: rating
rating_id student_id teacher_id grade_id date_created
1 101 21 1 2010-01-23 04:24:51
2 102 21 1 2010-01-23 04:26:51
3 102 22 2 2010-01-23 04:28:51
4 103 24 1 2010-01-23 04:44:51
Your code usage:
$rating_value = $_GET['rating']; // Remember to sanitize your inputs
$student_id = $_GET['student_id'];
$teacher_id = $_GET['teacher_id'];
rate_a_teacher($teacher_id, $student_id, $rating_value);
Your method:
function rate_a_teacher($teacher_id, $student_id, $rating_value)
{
// Find the corrosponding to specified rating value
$grade_id = find_grade_id($rating_value); //TODO
$sql = "
INSERT INTO rating
('student_id', 'teacher_id', 'grade_id', 'date_created')
VALUE
($student_id, $teacher_id, $grade_id, NOW);
";
mysql_query($sql);
}
I skipped implementation for find_grade_id() for you to fill it in yourself.
The purpose of splitting your calcualted values to individual records is so that you can start do interesting reports,
like such:
Find average rating value of each teacher for the past 3 months:
SELECT teacher_id, (SUM(points)/COUNT(rating_id)) AS average_score
FROM rating
LEFT JOIN grades ON grades.id = rating.grade_id
WHERE date_created > SUBDATE(NOW(), INTERVAL 3 MONTH)
GROUP BY teacher_id
I currently have a query
$query = "SELECT * FROM routes ORDER
BY id DESC LIMIT 8;";
And that works all wonderfully.
I have table columns
id int(10)
name varchar(45)
base varchar(16)
econ int(6)
location varchar(12)
x int(2)
y int(2)
galaxy int(2)
planet int(2)
comment varchar(100)
ipaddress varchar(45)
and on the page when this segment of php is called i will have
the econ,X,Y,Galaxy,and planet of another entry
then i want to display the entry is the database(like i do at the moment) BUT
i want a new column to be displayed that is not in the DB, this new column is to be the output of a calculation..
the calculation is to be
Sqrt(min. Economy) x ( 1 + Sqrt(Distance)/75 + Sqrt(Players)/10 )
Sqrt(88) x ( 1 + Sqrt(23)/75 + Sqrt(23)/10 ) = 15 cred./h
players is another variable that is already available in my page
Distance is a function of the 2 galaxys unless there the same when its a function of the 2 x's and y's unless there the same and then its a function of the 2 planet integers
here is the page i talk of..i will add a new button to compare.. thats the new function that i want to compare the given value with existing values.
http://www.teamdelta.byethost12.com/trade/postroute2.php
You can just calculate in your query like this:
$query = "SELECT (Sqrt(min. Economy) x ( 1 + Sqrt(Distance)/75 + Sqrt(Players)/10 ) Sqrt(88) x ( 1 + Sqrt(23)/75 + Sqrt(23)/10 ) = 15 cred./h) as `Distance`, * FROM routes ORDER BY id DESC LIMIT 8;";
Use as for naming your calculation so its become a column and use * to get the other fields.
After the query you store the results into an array. You could parse the array adding an item containing the calculation that you wrote.
If you want more details you should past here the array
--
dam