MySQL update query not working - php

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

Related

PHP different results for mysql_query and pdo

I am trying to convert a mysql_query to pdo equivalent
My table structure is (removed unrelated columns - the one needed for my question is other_id) :
CREATE TABLE `temp_table` (
`id` int(12) NOT NULL DEFAULT '0',
`other_id` int(12) NOT NULL DEFAULT '0',
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
And the data it has:
-----------------
| id | other_id |
-----------------
| 1 | 123 |
-----------------
| 2 | 0 |
-----------------
| 3 | 456 |
-----------------
| 4 | 0 |
-----------------
The previous database query was :
$sql = "SELECT id FROM temp_table WHERE other_id = '{$other_id}'";
$result = mysql_query($sql, $db)
return mysql_fetch_assoc($result);
The query is called with $other_id as NULL ("null" in php and not string or anything).
Result mysql_query : This gives my values 2,4
PDO equivalent code :
$sql = "SELECT id FROM temp_table WHERE other_id = :other_id";
$sth = $dbConnection->prepare($sql);
$sth->bindValue(":other_id", $other_id);
$sth->execute();
return $sth->fetchAll(PDO::FETCH_COLUMN);
Result PDO : This gives no values at all.
This is weird issue which I have not encountered before (since I am more java developer and recently touched PHP after few years).
As a workaround I had to put below line to return 2,4 as result from pdo output, but want to understand more about the difference mentioned above.
$sth->bindValue(":other_id", empty($other_id) ? 0 : $other_id);
I also tried $sth->bindValue(":other_id", $other_id, PDO::PARAM_INT); which did not help
This is not an issue with the mysql_ vs PDO difference, but rather with type-juggling.
In the first non-PDO example, $other_id is being converted to a string in the query, so your query looks like this:
SELECT id FROM temp_table WHERE other_id = '';
MySQL treats an empty string the same as 0 for fields of numeric type during queries, so your query is actually correctly matching two records.
In the PDO example since you're passing $other_id (which is null), your query is bound as follows:
SELECT id FROM temp_table WHERE other_id = NULL;
MySQL does not treat 0 as NULL, so the queries that you're sending are actually not the same.
This is weird issue which I have not encountered before.
There is nothing weird here.
When $other_id is NULL the first query becomes:
SELECT id FROM temp_table WHERE other_id = ''
Because the type of the other_id column is numeric, the provided value (the empty string) is converted to the number 0 and there are two matching rows.
On the other hand, the query sent through PDO is equivalent to:
SELECT id FROM temp_table WHERE other_id = NULL
Not only that there are no NULLs in the table, but this query never returns any row, even if there are rows having NULL in the column other_id. (The correct way to select the rows having NULL in other_id is to use the IS NULL operator).

Merge records in mysql table using Laravel (or not)?

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
.');'
));

PHP MySQL Result Set

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

MySQL SUM() in step by step column for incomes

Database: name_ allmoney
Table name: MONEY
+-----+--------+------------+---------+---------+
| id | name | date | income | account |
+-----+--------+------------+---------+---------+
| 1 | Ann | 01.01.2012 | 100 | 100 |
| 2 | Matt | 02.01.2012 | 100 | 200 |
| 3 | Tom | 03.01.2012 | 100 | 300 |
| 4 | Peter | 04.01.2012 | 100 | 400 |
+-----+--------+------------+---------+---------+
Hello Stackoverflowers! ;)
I'm newbie for MySQL... Last week I've spend searchin for solution for above situation. I'm tryin to create script summing income column, but not only showing the sum of the column like
SELECT *, SUM(kasa) from MONEY GROUP BY id;
but I have to add new column called account, which has the option like my excel sheet:
accout1st row =income1+account1
accout2nd row =income2+account1
accout3rd row =income3+account2
accout4th row =income4+account3
Is there any code or possibility to create column like account in MySQL or PHP?
CREATE TABLE money (
id INT(11) NOT NULL AUTO_INCREMENT,
date DATE DEFAULT NULL,
income DECIMAL(11,4) DEFAULT NULL,
numer_kluczyka INT(11) DEFAULT NULL,
name CHAR(255) CHARACTER SET utf8 COLLATE utf8_polish_ci DEFAULT NULL,
za_co CHAR(255) CHARACTER SET utf8 COLLATE utf8_polish_ci DEFAULT NULL,
account INT(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
You can do it using a user variable -
SELECT #m := 0;
SELECT
id,
name,
date,
income,
#m := #m + income AS balance
FROM money
ORDER BY date ASC, id ASC;
The order by should use the primary key for the table.
Splitting the two queries in your PHP should fix the problem -
<?php
$connection = mysql_connect('host', 'user', 'pass') or die('failed to connect');
mysql_select_db("album", $connection) or die('failed to select db');
mysql_query("SELECT #m:=0;");
$result = mysql_query("SELECT id, imie_i_nazwisko, data_wplaty, kasa, #m := #m + income AS balance FROM money ORDER BY data_wplaty ASC , id ASC");
while($row = mysql_fetch_array($result)) {
echo $row['income'] . " " . $row['balance'];
echo "<br />";
}
If I understand your question correctly, you simply need to store the sum computed so far in your php loop.
Something like:
$account = null;
while(($result = /* read mysql result */)) {
if (is_null($account)) { // Handle first row
$account = $result['income'];
}
// Show first columns
echo $result['id'], $result['income'], $account;
$account += $result['income'];
}
Your question seems a bit unclear, but if I've guessed what you want correctly, you could do this with a subselect that sums the income column over all rows up to the current row:
SELECT id, name, date, income,
( SELECT SUM(income) FROM money AS b
WHERE b.id = a.id
AND b.date <= a.date
) AS balance
FROM money AS a
You could also do the same with a join:
SELECT a.id, a.name, a.date, a.income, SUM(b.income) AS balance
FROM money AS a
JOIN money AS b ON (b.id = a.id AND b.date <= a.date)
GROUP BY a.id, a.name, a.date, a.income
(The GROUP BY is supposed to be on the primary key of the money table. It's not entirely clear from your question what the primary key is supposed to be, since it doesn't seem to be id.)
Also note that both of these answers assume that the date columns are unique for each id and sort in ascending order by time, so that the condition b.date <= a.date can find all rows up to and including the current row. If that's not the case, you should either fix your table so that it is, or adjust the query accordingly.
Edit: S0pra's PHP solution will work too. However, the way I read your question, what you want is to sum the past income for each id separately. If so, you can use S0pra's code with a few modifications:
$balance = array();
while ( $result = mysql_fetch_assoc( $res ) ) { // or equivalent
$id = $result['id'];
if ( array_key_exists( $id, $balance ) ) {
$balance[$id] += $result['income'];
} else {
$balance[$id] = $result['income']; // handle first row for this id
}
$result['balance'] = $balance[$id];
// do something with $result here
}

PHP & MySQL Update Database Problems

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

Categories