I have a function which fetches data from my database, it counts a number of instances existing for the same user and gives me a total figure. But I want to store this value in another table, which it does just fine the problem is that every time a user refreshes a page the same data is inserted and I want it to be inserted only once.
my function:
public function getYesterday($user){
$user = "SELECT user_id FROM tbl_user WHERE ott_email='$user'";
$query = mysqli_query($this->con(), $user);
$count = mysqli_num_rows($query);
if($count == 1){
while($row = mysqli_fetch_assoc($query)){
$id = $row['user_id'];;
}
$yesterday = "SELECT COUNT(tbl_template_log.user_id) FROM tbl_template_log ";
$yesterday .= "WHERE tbl_template_log.user_id='$id'";
$yesterday .= " AND DATE(send_date) = DATE(NOW() - INTERVAL 1 DAY)";
$query_yesterday = mysqli_query($this->con(), $yesterday);
$result = mysqli_fetch_row($query_yesterday);
$insert = "INSERT INTO tbl_statistics (user_id, sta_count, sta_date)VALUES ('$id', '$result[0]', NOW())";
mysqli_query($this->con(), $insert);
echo $result[0];
}
}
Looking at my function logic and structure could someone suggest a correct solution to make sure the insert query is done only once per day.....?
I am using PHP, and MySQL
Related
I have table with many rows. I have exp date and I want to change status of those rows where date is already exp.
It work well if I do not use UPDATE. If I just echo them. But when I want to UPDATE status of this row to 0, problems start. My problem is that it change only 1 row and not all of them that needs to be whit status 0.
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
$id = $row['id'];
if($resultcheck > 0) {
while($row = mysqli_fetch_assoc($result)) {
$expdate = $row['date'];
$exp = strtotime($date);
$today = date('m/d/Y');
$td = strtotime($today);
if($td>$exp) {
$status=0;
$sql = " UPDATE table SET status = '$status' WHERE ID = '$id' ";
$result = mysqli_query($conn, $sql);
}
}
}
Any advice how to fix that, I tried several option but nothing worked.
Use row['id'] instead of $id.
$sql = " UPDATE table SET status = '$status' WHERE ID = 'row['id']' ";
Rename $result for update. You are reusing the same variable name, hence, after a success update, it will set $result to true and the while loop will stop.
I'm trying to create a visitor counter, when user visit the page it will record the time and the number of visitor. But when I refresh the page, my database will be like this:
The code that I do is:
if (empty($counter)){
$counter = 1;
$total = 1;
$time = date('Y-m-d H:i:s');
$sql1 = "INSERT INTO humancount(counter, time, totalHumanCount) VALUES ('$counter', '$time', '$total)";
$result1 = mysqli_query($con, $sql1);
}
//date_default_timezone_set('Asia/Kuala_Lumpur');
$date1 = strtotime("now");
$date2 = strtotime("tomorrow");
echo date("Y-m-d H:i:s", $date1);
echo "<br>";
echo date("Y-m-d H:i:s", $date2);
if ($date1 < $date2){
$plusCounter = $counter + 1;
$plusTotal = $total + 1;
$nextTime = date('Y-m-d H:i:s');
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal'";
$result2 = mysqli_query($con, $sql2);
}
I was expecting that it will record the time of the user visit by every row.
This line of code is overwriting every row in the table with the current counter update:
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal'";
you should instead insert a new row for each new visitor.
Also, this will always be true:
if ($date1 < $date2)
so you can remove the if statement.
You can do something like this:
//first fetch the last values from the database
$sql0 = "SELECT counter, totalHumanCount FROM humancount ORDER BY time DESC LIMIT 1";
$result = mysqli_query($con, $sql0);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$counter = $row['counter'] + 1;
$total = $row['totalHumanCount'] + 1;
} else {
$counter = 1;
$total = 1;
}
//date_default_timezone_set('Asia/Kuala_Lumpur');
$time = date('Y-m-d H:i:s');
$sql1 = "INSERT INTO humancount(counter, time, totalHumanCount) VALUES ('$counter', '$time', '$total)";
$result1 = mysqli_query($con, $sql1);
Use Where condition in UPDATE query. as per your query every time it will update all rows in table 'humancount'. so add UserID column for unique row and then update row for selected user.
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal' WHERE userID = ?";
<?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];
UPDATED
I'm trying to create a basic schedule for all students in their final year to present their final project to 2 supervisors. I have successfully created a schedule with no constraints but now i need to create a schedule based on the supervisors availability.
Here is a detailed description of the problem.
A student is assigned a supervisor and a supervisor will supervise more than one student. The supervisor also teaches classes during the day. Now i need to create a schedule for all of the students to present to their supervisor and one additional supervisor that supervises other students. (for the moment I'm focusing on the supervisors that are assigned to the student and not the second one until i get it working.
I want to compare the supervisors availability for the slots time if they're free then assign them to the slot and then update the availability of that time to false to avoid double booking using a PHP sql query.
so...
What i have done so far:
// get all of the Slots.
$sql = "SELECT Slot_ID FROM slot WHERE StartTime < '18:00:00'";
$result = mysqli_query($con, $sql);
$DayTimeSlots = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$DayTimeSlots [] = $row;
}
}
// Store slots into simple array
function extractSlotId($DayTimeSlots){
return $DayTimeSlots['Slot_ID'];
}
$slots = array_map("extractSlotId",$DayTimeSlots);
// SHOW SLOTS
foreach ($slots as $slotID) {
echo " SlotID: = $slotID <br>";
}
// Get All students
$sql = "SELECT Student_ID FROM student WHERE PartTime =0";
$result = mysqli_query($con, $sql);
$FullTimeStudents = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$FullTimeStudents [] = $row;
}
}
// Store into a simple array
// Extract student id and Supervisor_ID
function extractStudentId($FullTimeStudents){
return $FullTimeStudents['Student_ID'];
}
$students = array_map("extractStudentId",$FullTimeStudents);
// Combine the Slot and Students array
$min = min(count($FullTimeStudents), count($DayTimeSlots));
$result = array_combine(array_slice($students , 0, $min), array_slice($slots, 0, $min));
foreach($result as $key=>$value){ // $Key = Student_ID, $value = Slot_ID
echo " $key : $value ";
// get supervisor ID
$sql = "select Supervisor_ID FROM student where Student_ID = $key";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$SuperID = $row['Supervisor_ID'];
echo "SuperID : $SuperID ";
// get slotID
$sql = "select Date, StartTime FROM Slot where Slot_ID = $value";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Date = $row['Date'];
$StartTime = $row['StartTime'];
echo "Slot Date : $Date Start Time : $StartTime ";
// get Date id
$sql = "select Date_ID FROM dates where Date = '$Date'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$DateID = $row['Date_ID'];
echo "Date ID : $DateID ";
// Check if the supervisor is available
$sql = "select `$StartTime` FROM supervisor_availability where Date_ID = $DateID AND Supervisor_ID = $SuperID";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Available = $row["$StartTime"];
echo "Is the Lecture Available? : $Available ";
$Time = "`$StartTime`";
if($Available == 1){
$sql = "INSERT INTO student_slot (Student_ID, Slot_ID) VALUES ($key, $value)";
$result = mysqli_query($con, $sql);
$sql = "UPDATE `supervisor_availability` SET $Time = '0' WHERE `supervisor_availability`.`Supervisor_ID` = $SuperID AND `supervisor_availability`.`Date_ID` = $DateID" ;
$result = mysqli_query($con, $sql);
} else if ($Available == 0) {
// Not sure what to do here.
// Can i make the Slot it's currently checking go to the end of the
// array for a different student and then check the next slot and come
// back to it.
}
}
I'm using echo for debugging.
The algorithm works fine if the Supervisor is available, it assigns it correctly and then updates the Supervisors availability for that time slot
Just need help with how to handle it if they're not available.
Any help or advice would be appreciated.
Supervisor_Availability Slot Table Student Table Date Table DB_Structure
I'm using the following code to sort MySQL queries into time/date:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row = mysql_fetch_array($result))
{
print($row['user']);
}
instead of having the PHP run through and show all the values in the table can I have it show the values from an array?
So, you want to find specific users in the SQL query to return? Build your query programmatically:
$users = array('User1','John','Pete Allport','etc');
$sql = "SELECT * FROM `users_newest_post` WHERE ";
$i = 1;
foreach($users as $user)
{
$sql .= "`username` = '$user'";
if($i != count($users))
{
$sql .= " OR ";
}
$i++;
}
$sql .= " ORDER BY `users_date_post` DESC";
$result = mysql_query($sql);
Which would get you a query like:
SELECT * FROM `users_newest_post`
WHERE `username` = 'User1'
OR `username` = 'John'
OR `username` = 'Pete Allport'
OR `username` = 'etc'
ORDER BY `users_date_post`
DESC
So, you want to find all posts for a certain date or between two dates, kinda hard to do it without knowing the table structure, but you'd do it with something like this:
//Here's how to find all posts for a single date for all users
$date = date('Y-m-d',$timestamp);
//You'd pull the timestamp/date in from a form on another page or where ever
//Like a calendar with links on the days which have posts and pass the day
//selected through $_GET like page.php?date=1302115769
//timestamps are in UNIX timestamp format, such as you'd get from time() or strtotime()
//Note that, without a timestamp parameter passed to date() it uses the current time() instead
$sql = "SELECT * FROM `posts` WHERE `users_date_post` = '$date'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
echo $row['post_name'] . $row['users_date_post']; //output something from the posts
}
//Here's how to find all posts for a range of dates
$startdate = date('Y-m-d',$starttimestamp);
$enddate = date('Y-m-d',$endtimestamp);
//Yet again, date ranges need to be pulled in from somewhere, like $_GET or a POSTed form.
//Can also just pull in a formatted date rather than a timestamp and use it straight up instead, rather than going through date()
$sql = "SELECT * FROM `posts` WHERE `users_date_post` BETWEEN '$startdate' AND '$enddate'";
//could also do:
//"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$endate'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
//output data
}
To find posts for a specific user you would modify the statement to be something like:
$userid = 5; //Pulled in from form or $_GET or whatever
"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$enddate' AND `userid` = $userid"
To dump the result into an array do the following:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row=mysql_fetch_assoc($result))
{
$newarray[]=$row
}
What you probably want to do is this:
$users = array("Pete", "Jon", "Steffi");
$users = array_map("mysql_real_escape_string", $users);
$users = implode(",", $users);
..("SELECT * FROM users_newest_post WHERE FIND_IN_SET(user, '$users')");
The FIND_IN_SET function is a but inefficient for this purpose. But you could transition to an IN clause with a bit more typing if there's a real need.
$sql = 'SELECT * FROM `users_newest_post` WHERE username IN (' . implode(',', $users) . ')';