Proper value for timestamp? - php

I am trying to add in values TIMESTAMP to my database but the it is not working. When I delete the timestamp row in my DB, every value adds and gets inserted. Do i need to set $timestamp to something different for my value?
$exam_name = $data["name"];
$exam_points = $data["total_score"];
$exam_grade = NULL;
$release_status = 0;
$exam_comments = NULL;
$exam_ucid = NULL;
$timestamp = NULL;
$sql = "INSERT INTO exams (exam_name, exam_grade, release_status, total_score, exam_comments,
our_ucid, timestamp )
VALUES
('$exam_name', '$exam_grade', '$release_status', '$exam_points', '$exam_comments',
'$exam_ucid', '$timestamp')";
$query = mysqli_query($conn, $sql);

timestamp is a keyword, you have to change field name
e.g. timestamp1

Related

Is it a good way to count unique visitors?

<?php
$date = date("Y-m-d"); //Return current date in yyyy-mm-dd format
$userIP = $_SERVER['REMOTE_ADDR'];// Stores remote user ip address
$query = "SELECT * FROM `unique_visitors` WHERE `date` = '$date'";
$result = mysqli_query($connection,$query);
if($result->num_rows == 0)// this block will execute when there is no record of current date in database
{
$insertQuery = "INSERT INTO `unique_visitors` (`date`,`ip`) VALUES ('$date','$userIP')";
mysqli_query($connection,$insertQuery);
}
else
{
$row = $result->fetch_assoc();//Extracts result row from result object
if(!preg_match('/'.$userIP.'/i',$row['ip']))//Will execute When Current ip is not in databse
{
$newIP = "$row[ip] $userIP"; //Combine previous and current user ip address with a separator for updating in database
$updateQuery = "UPDATE `unique_visitors` SET `ip`='$newIP', `views`=`views`+1 WHERE `date` = '$date' ";
mysqli_query($connection,$updateQuery);
}
}
?>
Is there a better way to count unique visitors in my website or this simple code is fine to insert into my website?
Here is the basic PHP/mysqli code for the approach you taken. You have to create an unique index for two fields, date and ip. And everything would work with just a single query.
<?php
$userIP = $_SERVER['REMOTE_ADDR'];// Stores remote user ip address
$sql = "INSERT INTO unique_visitors (date, ip, views) VALUES (curdate(),?,1)
ON DUPLICATE KEY UPDATE views = views + 1";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $userIP);
$stmt->execute();
$sql = "SELECT count(*) FROM unique_visitors WHERE date = curdate()";
$result = $connection->query($sql);
$visitors = $result->fetch_row()[0];

SQL Update query when there is an existing date in table by importing .csv files using PHP

I have a code that will get to create and insert .csv files to MySQL. Now what I want to get is how to Update my data if there is already an existing date in my table by importing a .csv file.
I tried to do it with a simple Update Query and its working fine... but the tricky part is to get the date from .csv file and compare it to the date that is in MySQL. Can you give me any hints on how to this?
Here's my code:
$file = 'C:\Users\HP\Desktop\csvfiles\ADJTIME.csv';
$table = 'adjtime';
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen($file,'r');
// first row, structure
if ( ($data = fgetcsv($handle) ) === FALSE ) {
//echo "Cannot read from csv $file";die();
}
$fields = array();
$field_count = 0;
for($i=0;$i<count($data); $i++) {
$f = strtolower(trim($data[$i]));
if ($f) {
// normalize the field name, strip to 20 chars if too long
$f = substr(preg_replace ('/[^0-9a-z]/', '_', $f), 0, 100);
$field_count++;
if($f == 'date'){
$fields[] = '`'.$f.'` DATE()';
} else {
$fields[] = '`'.$f.'` VARCHAR(500)';
}
}
}
$sqlgetdate = ("SELECT DATE from $table where DATE = '5/3/2017' ");
echo $sqlgetdate;
$sqlupdate = ("UPDATE $table SET Fieldname = 'John' where DATE = '5/3/2017' ");
echo $sqlupdate;
mysql accepts date format in 'yyyy-mm-dd'
so your query should be $sqlgetdate = ("SELECT DATE from $table where DATE = '2017-03-05' "); and $sqlupdate = ("UPDATE $table SET Fieldname = 'John' where DATE = '2017-03-05' ");
Create a unique key on date column and use the INSERT ... ON DUPLICATE KEY UPDATE statement.
Documentation can be found here

SQL Updates: Updates Multiple rows rather than Single rows

I am writing a code for MySQL to fetch the 1st row with status is "inactive" and make them "active", but whenever I tried to update the column and make it "active" my query updates multiple rows rather than the single row.
date_default_timezone_set('Asia/Kolkata');
$d = time ();
$date = date("Y-m-d", $d);
$customer_id="1470831854";
$member_details="SELECT * FROM login_update WHERE customer_id ='$customer_id' AND status='inactive' ORDER BY id ASC LIMIT 1 ";
$member = mysql_query($member_details);
while($list = mysql_fetch_array($member)){
$status = $list['status'];
$id = (int)$list['id'];
}
$date_update = "UPDATE login_update SET status='active' WHERE id = '$id'";
$enter_date = mysql_query($date_update);
I think your code should be change as follow
while($list = mysql_fetch_array($member)){
$status = $list['status'];
$customerId = (int)$list['customer_id'];
}
$date_update = "UPDATE login_update SET status='active' WHERE id = '$customerId'";
$enter_date = mysql_query($date_update);
becasue if you get $list['id'] it is always return only 1 unique value from the database then update only one record. I assumed id is your primary key.

Need to figure out total hours between check-in and check-out times

I am trying to create a check-in/check-out table in my database. My check-in form works without issue, inserting the time into my database. The problem occurs when I try to check out. Everything is good on the first entry...
But when I try to check in and check out again, this happens...
So far so good, but when I check out...
Currently, my code updates the out column and totalTime column of all matching child_id's.
Here is my code:
// Select the correct child from the database
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$var = $row['id'];
// Insert the check out time for the child
$query = "UPDATE checkinout
SET `out` = :nowTime
WHERE child_id = $var
AND `in` IS NOT NULL";
$statement = $pdo->prepare($query);
$statement->bindValue(':nowTime', date("YmjHis"));
$statement->execute();
// Select check in time for specified child
$sql_inTime = "SELECT `in` FROM checkinout
WHERE child_id = $var";
$inResult = $pdo->query($sql_inTime);
$inRow = $inResult->fetch();
$inTime = strtotime($inRow['in']);
// Select the check out time for specified child
$sql_outTime = "SELECT `out` FROM checkinout
WHERE child_id = $var";
$outResult = $pdo->query($sql_outTime);
$outRow = $outResult->fetch();
$outTime = strtotime($outRow['out']);
// Find total hours
$totalTime = abs($outTime - $inTime)/(60*60);
// Update totalHours column for specified child
$queryTotalTime = "UPDATE checkinout
SET totalTime = :totalTime
WHERE child_id = $var
AND 'out' IS NOT NULL";
$statement = $pdo->prepare($queryTotalTime);
$statement->bindValue(':totalTime', $totalTime);
$statement->execute();
I think you could do all of this in your first update statement using TIMESTAMPDIFF rather than figuring the total time with PHP:
UPDATE checkinout
SET
out = NOW(),
totalTime = TIMESTAMPDIFF(SECOND, `in`, NOW()) / 3600
WHERE
child_id = $var
AND out IS NULL
The criteria WHERE out IS NULL will only update rows that do not have a value in the out column yet.
IF you have MySQL Db THEN sql will be
SELECT TIMESTAMPDIFF(HOUR,in,out) from checkinout;

MySql delete operation comparing datetime with current date time

I am new in PHP and MySql. I want to delete rows from a table where order_before passed the current date and time. the order_before is date/time type.
<?php
$db = new PDO('mysql:host=localhost;dbname=db','root','root');
if(filter_has_var(INPUT_POST, 'submit')) {
$now = date("Y-m-d H:i:s");
$r = $db->query("SELECT * FROM db WHERE datetime < '".$now."'");
$n = $r->rowCount();
if ($n){
while($o = $r->fetchObject()) {
$db->query('DELETE FROM db WHERE id = '.$o->id);
}
}
}
Maybe something like the above? (untested, and off the top).
Just add the condition in the statement, should be easy enough:
$sql = sprintf("DELETE FROM mytable WHERE order_before > '%s'", date('Y-m-d H:i:s'));
$db->exec($sql);

Categories