how to check the database is update/modify/changed? - php

This is my database
This is my php code which is used to fetch the data from the table
while($row = mysqli_fetch_array($result))
{
$user_id = $row['id'];
$sql = "SELECT id, ScheduleDate, StartTime,Endtime, Hours,Employeeid
FROM empdet WHERE Employeeid ='".$user_id."' ";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$id=$row["id"].
$date=$row["ScheduleDate"];
$start=$row["StartTime"];
$end=$row["Endtime"];
$hour=$row["Hours"];
$Employeeid=$row["Employeeid"];
list($year,$month,$day) = split("-",$date);
$data[] = array("year"=>$year,
"month"=>$month,
"day"=>$day,
"StartTime"=>$start,
"Endtime"=>$end,
"Hours"=>$hour );
}
$response = $data;
}
else
{
$data=1;
$response = $data;
}
My question is how to find whether the database is modified/changed/updated?
In the users table, if I change the start time from 2:00pm to 3:00 pm of "2018-12-01" it should notify me in echo as the "2018-12-01" has been modified.
Can anyone suggest how to do this with PHP?

int mysql_affected_rows ([ resource $link_identifier = NULL ] )
Returns the number of affected rows on success, and -1 if the last query failed.
see http://php.net/manual/en/function.mysql-affected-rows.php

You could make use of the timestamp column type in the database which, when set to use auto-update, would give an indication that the record has been updated.
alter table `empdet`
add column `timestamp` timestamp null default current_timestamp on update current_timestamp after `Employeeid`;
Then you could alter your query to determine if the record is updated
select `id`, `scheduledate`, `starttime`, `endtime`, `hours`, `employeeid`,
case
when `timestamp` is not null then
true
else
false
end as 'updated'
from `empdet` where `employeeid` ='".$user_id."';
However, looking at the original code there appears to be nested loops both trying to process the query result variable $result with the inner query re-assigning this variable. As the outer loop is providing an ID for the inner loop it would make more sense perhaps to do a join - but hard to be specific without seeing the previous code and knowing what the original query was.

you create a column with timestamp using this query
ALTER TABLE `table_name` ADD `time_stamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `column_name`;
timestamp create auto time when data enter so you can get lastime of data and checkout max timestamp

Related

Can we find record that doesn't exist in table using mysql Procedure?

I am using MySql Procedure to update value, but before that I am checking if record exists. And condition is, if record exist then just update the detailand it is updating very well.
Now my question is How to find records that doesn't exist in table and return that all value(which is not exist or doesn't satisfied IF EXISTS condition). Below I am sharing my MySql Procedure.
CREATE DEFINER=`root`#`%` PROCEDURE `sp_ABC`(
IN `_startdate` DATE,
IN `_enddate` DATE,
IN `_invc` VARCHAR(100),
IN `_amt` VARCHAR(100),
IN `_stones` VARCHAR(100),
IN `_tracking` VARCHAR(100)
)
BEGIN
IF EXISTS (SELECT invc, value, ttl_stones FROM tbl_quality WHERE invc = '_invc' AND value =
'_amt' AND ttl_stones = '_stones' AND DATE(date) BETWEEN '_startdate' AND '_enddate')
THEN
UPDATE quality_memo SET trackid = '_tracking'
WHERE invc = '_invc' AND value = '_amt' AND ttl_stones = '_stones' AND
DATE(date) BETWEEN '_startdate' AND '_enddate';
ELSE
-- HERE I WANT TO FIND OR RETURN **invc, value, ttl_stones** WHICH ROW DIDN'T GOT UPDATED
-- or NOT FOUND or IF EXISTS CONDITION NOT GOT SATISFIED
END IF;
END
Also, I am sharing my PHP code, where I am using ARRAY and FOR-EACH LOOP to pass value in PROCEDURE.
<?php
error_reporting(E_ERROR | E_PARSE);
include "config.php";
$s = '';
$trackingmyarray = $_POST['trackingmyarray'];
$tracking = json_decode($trackingmyarray, true);
if (is_array($tracking)) {
foreach ($tracking as $item) {
$s .= "CALL `sp_ABC`('".$item['startdate']."', '" . $item['enddate'] . "',
'".$item['invc1']."', '".$item['amt']."',
'".$item['stones']."', '".$item['tracking']."');";
}
}
$res = query($s);
if (strlen($res) > 0) {
echo $res;
} else {
echo 'Records added successfully...';
}
?>
I hope I made my concern clear. Again in simple words, if value doesn't satisfied IF EXISTS condtion then print it as output
Any help will be appreciated, and thanks in advance.
You do not need to check the existence of the rows before update. Just run the update and return the number of rows affected to PHP. If the return value was zero, you know the parameters passed do not have matching rows.
Also, if you use backticks to escape the variables, make sure you use backticks instead of single quotation marks.
CREATE PROCEDURE sp_ABC(
_startdate DATE,
_enddate DATE,
_invc VARCHAR(100),
_amt VARCHAR(100),
_stones VARCHAR(100),
_tracking VARCHAR(100)
)
BEGIN
UPDATE quality_memo
SET trackid = _tracking
WHERE invc = _invc AND value = _amt AND ttl_stones = _stones AND DATE(date) BETWEEN _startdate AND _enddate;
SELECT ROW_COUNT();
END

mysql insert record not immediately available, select count(*) doesn't see it right away

In my php code, I have a Mysql query:
SELECT COUNT(*)
to see if the record already exists, then if it doesn't exist I do an:
INSERT INTO <etc>
But if someone hits reload with a second or so, the SELECT COUNT(*) doesn't see the inserted record.
$ssql="SELECT COUNT(*) as counts FROM `points` WHERE `username` LIKE '".$lusername."' AND description LIKE '".$desc."' AND `info` LIKE '".$key."' AND `date` LIKE '".$today."'";
$result = mysql_query($ssql);
$row=mysql_fetch_array($result);
if ($row['counts']==0) // no points for this design before
{
$isql="INSERT INTO `points` (`datetime`,`username`,`ip`,`description`,`points`,`info`, `date`,`uri`) ";
$isql=$isql."VALUES ('".date("Y-m-d H:i:s")."','".$lusername."',";
$isql=$isql."'".$_SERVER['REMOTE_ADDR']."','".$desc."','".$points."',";
$isql=$isql."'".$key."','".$today."','".$_SERVER['REQUEST_URI']."')";
$iresult = mysql_query($isql);
return(true);
}
else
return(false);
I was using MyISAM database type
Instead of running two seperate queries just use REPLACE INTO.
From the documentation:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
For example if your key field is id then:
REPLACE INTO my_table SET id = 4 AND other_field = 'foobar'
will insert if there is no record with id 4, or if there is then it will replace the other_field value with foobar.

If statement condition not running [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am checking the for the user_id (it is held in a session) - this is working. Then I am running a SELECT query for that user for the database table click_count. I am checking to see if that user has any records within it, ie: $page_count. If not, I want my INSERT statement to run to add that user to the database table along with other data.
The part I do not understand is it seems that my UPDATE query is always running. For example no matter which user I login with my query only updates the only user in the database table. IE: Bob is the only user in the click_count table, if I log in with Pete, Bob's record is being updated.
I have tested the value for $page_count and it equals 0, so my INSERT should be running. I have also tried if ($page_count === 0) {
Does anyone see anything I am missing?
$curPage = $_SERVER['PHP_SELF'];
$clicks = 0;
$setup = 0;
$page_total_count = 0;
var_dump($user_id);
$click_sql = "
SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$click_stmt = $con->prepare($click_sql);
$click_stmt->execute(array($user_id, $curPage));
$click_stmt_rows = $click_stmt->fetchAll(PDO::FETCH_ASSOC);
$page_count = $click_stmt->rowCount();
foreach ($click_stmt_rows as $click_stmt_row) {
$setup_status = $click_stmt_row['setup'];
$page_total_count = $click_stmt_row['page_count'];
}
if ($page_count == 0) {
$click_insert_sql = "
INSERT INTO click_count
(user_id, page_url, page_count, setup)
VALUES(?, ?, ?, ?)
ON DUPLICATE KEY UPDATE page_count=page_count+1;
";
$click_insert_stmt = $con->prepare($click_insert_sql);
$click_insert_stmt->execute(array($user_id, $curPage, 1, $setup));
}
else {
$click_update_sql = "
UPDATE click_count
SET page_count=page_count+1
WHERE user_id = ?
AND page_url = ?
";
$click_update_stmt = $con->prepare($click_update_sql);
$click_update_stmt->execute(array($user_id, $curPage));
}
Table
click_count
CREATE TABLE `click_count` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`page_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`page_count` int(11) NOT NULL,
`setup` int(5) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
UNIQUE KEY `page_url` (`page_url`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Since there is only the one user in the table, there is no record "to insert/update", therefore
ON DUPLICATE KEY UPDATE failed you silently.
A regular UPDATE will suffice:
I.e. and as an example:
UPDATE table SET col_x = 0|1 WHERE col_y = ? // (boolean 0-1)
Note:
If ever you wish to increase a column by counting later on, the syntax would be:
UPDATE table SET col_x = col_x + 1 WHERE col_y = ?
In regards to your asking about how you could improve on your code:
#Fred-ii- Thanks. Yes, it is working now how I want, but if there are ways to improve the code I am always willing to try to learn it. I just remembered people in the past saying that I didn't need the update query at all with the duplicate key update. – Paul
You could use named placeholders :name rather than ? since they are easier to keep track of, but this is of course a matter of opinion that I feel is also shared by many and not just myself.
Footnotes/credits:
I would like to also give credit to the following comment:
"If you always fall into update indicates that $page_count is not zero.. Try to echo() it to see maybe.. I would probably first try to add another user into click_count table and then it may become easier to see where it goes wrong.. – johnyTee"
where the OP responded with:
"#Fred-ii- I figured it out. I used johnyTee's advise and tried adding another user to the database manually and it wouldn't let me because of the unique index for the page_url column. I then removed the unique index from it and now it works perfectly. Thanks for the help! – Paul"
from PHP PDO doc http://php.net/manual/en/pdostatement.rowcount.php
PDOStatement::rowCount() returns the number of rows affected by a
DELETE, INSERT, or UPDATE statement.
if you need th number of rows in select you should use somethings like
$sql = "SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
It may be '0' (a string). You can use intval to convert it to an integer.
$page_count = intval( $click_stmt->rowCount() );
http://php.net/manual/en/function.intval.php
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
try like this:
$sql = "SELECT count(*)
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
//insert
}else {
//update
}
}

How to get a tuple's values that is inserted into PostgreSql db using php?

I am trying to insert a tuple into PostgreSql using PHP. After inserting the tuple I want to get the value of one of the columns of the inserted row. This column value is generated automatically by the db as it is defined as SERIAL in DDL.
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me')";
$result = pg_query($dbh,$query);
if (!$result) {
$status = 0;
} else {
$status = 1;
}
$row = pg_fetch_assoc($result);
$pID = $row['postID'];
$array = array(
'status' => $status,
'pID' => $pID
);
#Delete query is only for checking if the code is working.
$query = "DELETE FROM posts WHERE postID='$pID'";
$result = pg_query($dbh,$query);
The table 'posts' has following DDL:
CREATE TABLE posts
( title CHAR(20),
content CHAR(42),
x_coor INTEGER,
y_coor INTEGER,
userID CHAR(50),
time_stamp TIMESTAMP default current_timestamp,
postID SERIAL,
PRIMARY KEY(postID),
FOREIGN KEY (userID) REFERENCES users ON DELETE CASCADE);
I want to get the value of 'postID' column when I insert a row into the table 'posts' to perform additional functions based on postID. I have tried pg_fetch_assoc, pg_fetch_row, pg_fetch_object & pg_fetch_array. None of those seem to work. (I made appropriate modifications to the code when using each of those functions.)
Is there something incorrect in the code or perhaps I am missing something?
Thanks!
A good way is the returning clause:
INSERT INTO posts
VALUES('$title','$msg',$x,$y,'$me')
RETURNING id;
My PHP is a bit rusty, but it'd look something like:
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me') RETURNING id";
$result = pg_query($dbh, $query);
if ($result) {
$row = pg_fetch_row($result);
$inserted_id = $row[0];
}

Mysql/Php - Current date and time

I have a query that I want to update a column with the current date time. The column I want to update is of the type datetime.
How can I get it and set it?
else{ //If the last update is NULL, It must be players first page load. So set datetime equal to NOW
$query = "UPDATE `stats` SET `last_ap_update` = WHERE `member_id` = {$_SESSION['SESS_MEMBER_ID']}";
$queryresult = mysql_query($insertqry);
}
Using NOW() in the query would provide this.
else{ //If the last update is NULL, It must be players first page load. So set datetime equal to NOW
$query = "UPDATE `stats` SET `last_ap_update` = NOW() WHERE `member_id` = {$_SESSION['SESS_MEMBER_ID']}";
$queryresult = mysql_query($insertqry);
}
But if this gets updated anytime the table updates, I would suggest changing the column to TIMESTAMP and this will automatically update to the current time for you anytime that record changes.
else{ //If the last update is NULL, It must be players first page load. So set datetime equal to NOW
$query = "UPDATE `stats` SET `last_ap_update` = '".gmdate("Y-m-d H:i:s")."' WHERE `member_id` = {$_SESSION['SESS_MEMBER_ID']}";
$queryresult = mysql_query($insertqry);
}
You can use any format you want instead of gmdate("Y-m-d H:i:s")
You can use the mysql function NOW() for this, or you can pase the $_SERVER['REQUEST_TIME'] in there so the query gets cached by mysql.

Categories