Update database query - php

What I want to achieve is to add 30 days to a customers subscription if the payment has been made
So I am using this code
$set = "REPLACE into CLIENTS where USR_PAID = '1' and USR_EXPIRATION = DATE(DATE_ADD(NOW(), INTERVAL 0 DAY)) values ('USR_EXPIRATION','" . $due . "')";
$update = $conn->update($set, $db);
I am getting the following syntax error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where USR_PAID = '1' and USR_EXPIRATION = DATE(DATE_ADD(NOW(), INTERVAL 0 DAY)) values ' at line 1
Statement:
REPLACE into CLIENTS where USR_PAID = '1' and USR_EXPIRATION = DATE(DATE_ADD(NOW(), INTERVAL 0 DAY)) values ('USR_EXPIRATION', '09-05-2013')
I should tell you that I am using the same function to update the db in different parts of the website and is working just fine.
Also the following query is working and gives me all the clients that have paid and expire today:
$request = "select * from CLIENTS where USR_PAID = '1' and USR_EXPIRATION = DATE(DATE_ADD(NOW(), INTERVAL 0 DAY))";
$result = $conn->query($request, G_NORMDB);
I guess it is only a syntax error that I can't figure out.

On a side note,I think this won't work anyway, you can't use replace into to selectively change columns.
Here's the manual's explanation:
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT. You cannot refer to values from
the current row and use them in the new row.
So you muse include the whole user row.
I think it's easier to just use this query:
$q = "UPDATE CLIENTS SET USR_EXPIRATION = '$due' WHERE `USR_PAID = '1' AND USR_EXPIRATION = DATE(DATE_ADD(NOW(), INTERVAL 0 DAY))";
$update = $conn->update($q, $db);
let me know how that works for you, if it does at all.

Your REPLACE syntax is wrong. VALUES, then WHERE.
$set = "REPLACE into CLIENTS (the two columns here) VALUES ('USR_EXPIRATION','" . $due . "') where USR_PAID = '1' and USR_EXPIRATION = DATE(DATE_ADD(NOW(), INTERVAL 0 DAY))";
Read up more on enter link description here for more information.
Edit: I was curious about not seeing WHERE in the documentation. According to this answer, REPLACE does not have a WHERE clause. Use UPDATE instead.

What about following the very advice from the error message - to check Mysql manual on the syntax for the REPLACE query?

Related

Looping a sql statement if more than 1 record found

I'm trying to check if a certain record meet the following condition: status is "File Closed", not_visible = "0" and status_date is earlier by 14 days or more.
If condition met, to update not_visible "0" to "1".
This is invoke whenever a user logs in.
Problem:
The sql only run once even if 10 records found. How do I loop it to complete updating all records found and exit the statement once done?
global $conn;
$strSQLExists = "select lead_id as a, status_date as b, not_visible as c from tbl_progress where status = 'File Closed' and not_visible = '0' and status_date <= DATE_ADD(CURDATE(), INTERVAL -14 DAY) ";
$rsExists = db_query($strSQLExists,$conn);
$data=db_fetch_array($rsExists);
if($data)
{
$sql = "UPDATE tbl_progress SET not_visible = '1' WHERE lead_id = '".$data["a"]."'";
CustomQuery($sql);
return false;
}
else
{
// if dont exist do something else
}
Was adviced to just update:
so here we are:
UPDATE tbl_progress SET not_visible = '1' WHERE status = 'File Closed' and not_visible = '0' and status_date <= DATE_ADD(CURDATE(), INTERVAL -14 DAY)
Doing it using update statement only (as per your edit) should fix the issue. Actually, using update fixes
the looping issue, as it updates all records that match, not just one
the sql injection issue, as there are no parameters passed around and no string concatenation of the sql statement
the race condition issue that might occur if something was changed between select and update
It will also be slightly more efficient, as it pushes the logic to db.
In short: using an update instead of select + update will fix the looping issue and some other issues you didn't know you had, so use that.

Displaying amount of users on a webpage

I am trying to write a PHP script that will count the amount of users that have visited the page within the last 10 minutes. This is my script right now:
function getOnlineUsers($database, $main_connection){
$database;
$visitor_id = session_id();
$timestamp = time();
$timeOut = $timestamp - 6000;
mysql_query("INSERT INTO online (m_time, ip) VALUES ('$timestamp', '$visitor_id')", $main_connection);
mysql_query("DELETE FROM online WHERE m_time < $timeOut");
$result = mysql_query("SELECT * FROM online");
mysql_fetch_assoc($result);
if(!$result){
$online_users = 1;
}else{
$online_users = mysql_num_rows($result);
}
return $online_users+1;
}
The problem is that nothing is being inserted into the database and the database remains empty and therefore the count is null. Can someone please assist me in this?
First, better use PDO or MySQLi. In your database, the 'm_time' column must be integer type, and pass the $timestamp value as number, not within quotes.
"INSERT INTO online (m_time, ip) VALUES ($timestamp, '$visitor_id')"
1) Change '$timestamp' to NOW(), mysql can't understand php's time() function ( assuming m_time is a datetime field) .
ie:
INSERT INTO online (m_time, ip)
VALUES ( NOW(), '$visitor_id')
2) Your delete suffers the same problem
3) You can use something a little more clever to get the users in the last 10 minutes, try something like:
select count(*) AS OnlineUserCount
from online
WHERE
m_time > DATE_SUB( NOW(), INTERVAL 10 MINUTE ) ;
Your code looks fine .. what i suggest you do is echo out the query when it runs and cope and paste it and run it directly from phpmyadmin and check if it gives you any error and if the row is inserted succesfully i suggest you check your connection file with the database.
And also try what's suggested by CoursesWeb

php code for checking current date is newer than date in database

iam developing a webSite using php and mysql and am really beginner in this area.. Now iam stuck in a place where i have to check the current date is newer than the date in my database
so i have written a code like this but it's not working
$SQL = "UPDATE adverts SET active='0' WHERE enddate<NOW()";
$result = mysqli_query($con,$SQL);
in the above code 'advert' is my table name and 'enddate' is where the column containing date in database
can anybody please help me?
As Anthony described in comments, it's a good idea to check if your query is working in PHPMyAdmin at all, by going to PHPMyAdmin -> SQL -> Run Query. This way you can distinguish if it's an MySQL Error or an PHP Error.
UPDATE adverts SET active = 0 WHERE ( enddate < NOW() )
I've set active '0' to 0, simply because I believe it'll be an Integer field - secondly, there's a small but important difference in your enddate:
is it a date field or a datetime field? See below:
SELECT NOW(); // You will get 2010-12-09 17:10:18
SELECT CURDATE(); // You will get 2010-12-09
Source: MySQL Curdate() vs now()
You can use affected_rows() to see if you query did work, but just didn't meet any criteria
$sql = "UPDATE adverts SET active = 0 WHERE ( enddate < NOW() )";
$queried = mysqli_query( $con, $sql );
if ( mysqli_affected_rows( $con ) >= 1 ) {
//We know some rows were effected.
}
Did you tried
UPDATE adverts SET active='0' WHERE enddate<DATE(NOW())
also, is it adverts or advert?
Or you can try with CURDATE()
UPDATE adverts SET active='0' WHERE enddate<CURDATE()

Result conflict in mysql and PHP

i am facing a strange issue, if i am checking the mysql query with PHP then i didn't get the exact result according to mysql query.
But the same query if i run then i get the expected result, here is mysql query:
SELECT id, follow_up_datetime, followed_by, follow_up_status, case_time_zone, description, case_id
FROM case_note
WHERE TYPE LIKE '%follow-up-open%'
AND (
follow_up_datetime LIKE '%2013-01-08%'
OR date( follow_up_datetime ) < '2013-01-08'
)
AND follow_up_status <= '1'
GROUP BY case_id
ORDER BY case_id DESC
LIMIT 0 , 30
the result of this query is :
but when i use the same query with php then i get the the wrong ids:
PHP
//current date is "2013-01-08";
$follow_q = "SELECT id, follow_up_datetime, followed_by, follow_up_status, case_time_zone, description, case_id
FROM case_note
WHERE `type` LIKE '%follow-up-open%'
AND (
follow_up_datetime LIKE '%$current_date%'
OR date(follow_up_datetime) < '$current_date'
)
AND follow_up_status <= '1'
GROUP BY case_id
ORDER BY case_id DESC";
$follow_r = mysql_query($follow_q) or die('Error in Query!<br />' . mysql_error());
this query providing me the id's like 53, 84, 47, 36.
last three id's are correct but the first is not correct. i want first id is 139. Can anyone please help to find out the exact problem?
UPDATE: here i have update the result of id 53
A few tips concerning your query itself:
Your follow_up_datetime should be a type timestamp or datetime
You don't need the LIKE operator in your date condition.
DATE( `follow_up_datetime` ) = '2013-01-08'
OR
DATE( `follow_up_datetime` ) < '2013-01-08'
This can be shortened into
DATE( `follow_up_datetime` ) <= '2013-01-08'
If you always compare to the current date, you can use CURRENT_DATE
DATE( `follow_up_datetime` ) <= CURRENT_DATE
Don't compare a col of type int to a string which will force MySQL to cast all values of the col follow_up_status to string.
`follow_up_status` <= 1
Are you sure you need LIKE for the type condition?
`type` = 'follow_up_open'
Would be much faster.
PHP documentation about the MySQL extension:
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
EDIT:
Just realized you GROUP BY case_id.
If both, id 53 and id 139 have the same case_id MySQL needs to know which row can be discarded. If you don't give this information, one of the two rows is discarded more or less randomly.
To work around this problem use a aggregate function. in your case MIN() would deliver the desired result.
The whole query cleaned up using PHP heredoc notation:
$follow_q = <<< EOQ
SELECT
MIN( `id` ) AS `id`,
`follow_up_datetime`,
`followed_by`,
`follow_up_status`,
`case_time_zone`,
`description`,
`case_id`
FROM
`case_note`
WHERE
`type` = 'follow-up-open'
AND
`follow_up_datetime` <= '{$current_date}'
AND
`follow_up_status <= 1
GROUP BY
`case_id`
ORDER BY
`case_id` DESC
EOQ;
The problem can be from follow_up_status <= '1'. If the column is a numeric type, you should pass the value as a number, not string. Try:
follow_up_status <= 1
If it was me I would error_log() the $follow_q variable and then copy and paste that query into MySQL and see if it returns the same or wrong results because maybe your $current_date variable is wrong.

What's wrong with this query?

I have this query, running from a PHP page:
$feed_sql = "SELECT id, title, description, rssDate
FROM feed
WHERE MATCH (title) AGAINST ('" . $rows['suburb'] . "')
AND NOT EXISTS(SELECT feed_id, recipient_id, issent
FROM tracking_table
WHERE tracking_table.feed_id = $feed_id
AND tracking_table.recipient_id = $recipient_id
AND tracking_table.issent = 'Y')
GROUP BY pubDate
ORDER BY pubDate DESC
LIMIT 1";
However, it returns the following errors upon running it:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND tracking_table.recipient_id =
AND tracki' at line 7
Line 7 being this:
AND tracking_table.recipient_id = $recipient_id
Some server information:
PHP Version 5.2.6-1+lenny9
MySQL Version 5.0.51a
Thanks :-)
As you can see here:
'AND tracking_table.recipient_id = AND tracki'
// value missing here --^
the value of $recipient_id seems to be empty and generates invalid syntax.
Perhaps $recipient_id is an empty string. Please check it

Categories