Notification for user group - php

I'm working on a event manager and I would like to create a notification system for a group of users.
When an admin creates a new event then php create a notification inside mysql with status 0 if not read and then it changes to status 1 if read.
The problem is that I'm using the group id instead of the user id, and when the first logged user click on the notification it updates the notification status so other users are not viewing the notification. Maybe inserting a row for each user into the database can solve this problem? do I need to use an array of user's ids?
This is what i've done so far:
session_start();
// admin id
$userid = $_SESSION['user_id'];
include('../../../config/database.php');
$event_title = $_POST['titleevent'];
$event_color = $_POST['eventcolor'];
$event_start = $_POST['startevent'];
$new_start_date = date('Y-m-d 00:00:00', strtotime($event_start));
$event_end = $_POST['endevent'];
$new_end_date = date('Y-m-d 23:59:00', strtotime($event_end));
$event_group = $_POST['usergroup'];
$event_description = $_POST['eventdescription'];
if ($create_event = mysqli_prepare($conn, "INSERT INTO user_events (event_title, event_description, event_start, event_end, event_color, event_group)
VALUES (?, ?, ?, ?, ?, ?)" )) {
mysqli_stmt_bind_param($create_event, 'sssssi', $event_title, $event_description, $new_start_date, $new_end_date, $event_color, $event_group);
mysqli_stmt_execute($create_event);
// get event id
$event_id = mysqli_insert_id($conn);
$event_start_date = date('d-m-Y', strtotime($new_start_date));
$notification = "Nuovo evento <span class='text-warning'><strong>$event_title</strong></span> inizia il $event_start_date";
$notification_status = "0";
$notification_category= "events";
$event_notification = mysqli_prepare($conn, "INSERT INTO event_notifications (e_notification_sent_by, e_notification_sent_to, e_notification_message, e_notification_time, e_notification_status, e_notification_category, e_notification_category_id) VALUES(?,?,?,now(),?,?,?)");
mysqli_stmt_bind_param($event_notification, 'iisisi', $userid, $event_group, $notification, $notification_status, $notification_category, $event_id);
mysqli_stmt_execute($event_notification);
mysqli_stmt_close($event_notification);
echo "event created";
mysqli_stmt_close($create_event);
}else{
echo "Ops, error";
}
Many thanks for you help
UPDATE i've managed to make it working using an array and foreach in this way:
$event_start_date = date('d-m-Y', strtotime($new_start_date));
$notification = "Nuovo evento <span class='text-warning'><strong>$event_title</strong></span> inizia il $event_start_date";
$notification_status = "0";
$notification_category= "events";
$sql = "SELECT user_join_id FROM user_group_join WHERE group_join_id='$event_group'";
$result= mysqli_query($conn,$sql);
$datas= array();
if(mysqli_num_rows($result) > 0){
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){
$datas[]= $row;
}
}
foreach($datas as $data) {
$id_cliente = $data['user_join_id'];
$event_notification = mysqli_prepare($conn, "INSERT INTO user_notifications (notification_sent_by, notification_sent_to, notification_message, notification_time, notification_status, notification_category, notification_category_id) VALUES(?,?,?,now(),?,?,?)");
mysqli_stmt_bind_param($event_notification, 'iisisi', $userid, $id_cliente, $notification, $notification_status, $notification_category, $event_id);
mysqli_stmt_execute($event_notification);
mysqli_stmt_close($event_notification);
}
Now the question is how can i can i convert it with a prepared statement? And also it looks like i'm going to use a lot of server resources querying the database for each user id, is there any way to optimize the foreach loop?
Many thanks

Related

php - Updating data in database base on id?

I am working on a project that takes students attendance in class and I want to update the database data through PHP whilst running a SQL function of UPDATE, but I want to be able to update it base on the id of the data.
This is the code that I am working with at the moment.
<?php
require_once './dba.php';
$status = "";
if(isset($_POST['time_in'])) {
$query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";
$d = $conn->prepare($query);
$d->execute();
} elseif(isset($_POST['time_out'])) {
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = ? ";
$d = $conn->prepare($query);
$d->execute();
} else {
$status = "Can't time in!";
}
Use $conn->lastInsertId() to get the ID that was assigned when they clocked in. Save that in a session variable and use it when they clock out.
<?php
require_once './dba.php';
$status = "";
if(isset($_POST['time_in'])) {
$query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";
$d = $conn->prepare($query);
$d->execute();
$_SESSION['clock_id'] = $conn->lastInsertId();
} elseif(isset($_POST['time_out'])) {
if (!isset($_SESSION['clock_id'])) {
$status = "You need to clock in first!";
} else {
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
$d->execute(['id' => $_SESSION['clock_id']]);
}
} else {
$status = "Can't time in!";
}
You must remember to prepare the query and bind the parameters onto it.
Use the $id variable to prepare the query with the appropriate ID.
Make sure you authenticate the session before passing the ID to the query, otherwise an attacker can manipulate this data to pull anyone's data they wish.
// Its helpful to create elements within the code to bind onto. :id is ours.
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
// Run the query & bind id to :id
$d->execute(['id' => $id]);
You try update
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
$d->execute(['id' => $id ]);

prepared statements on loop and rollback if there are errors

I was hoping someone would guide me in the right direction. What I am trying to accomplish is the following:
user uploads a csv file the data is then stored in a multidimensional array $formatted_payments. Then I check the records on the file against the records on the DB. I need to check if the route from the file matches the route on DB if it does for all records then commit all the updates but if there is one mismatch then i need to rollback all the update. I hope this all makes sense. Here is what I did but I haven't tested yet.
Thank you
$conn->autocommit(FALSE);
$route_errors = [];
foreach($formatted_payments as $val){
$sql = "SELECT id, account_no, payment_amount, route_id, payment_date FROM car_payments WHERE payment_date = '".$date."' AND account_no = '".$val['account_no']. "'";
$res = $conn->query($sql);
$data = $res->fetch_object();
if($data){
if($val['amount'] > 0){
if($val['route_id'] != $data->route_id){
$route_errors[] = $val['account_no'];
}else{
$sql = "UPDATE car_payments SET payment_amount = ? charged = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $val['amount'], 'Si', $data->id);
$stmt->execute();
}
}else{
$sql = "UPDATE car_payments SET payment_amount = ? charged = ?, pending = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss", $val['amount'], 'No', 1, $data->id);
$stmt->execute();
}
}
}
if(!empty($route_errors)){
$conn->roll_back();
echo 'The following accounts do not match the route. Records not imported.<br>';
foreach($route_errors as $value){
echo '<li>' . $value . '</li>';
}
}else{
$conn->commit();
}

I need to fetch the data from mysql database using the employee id from the table

I need to fetch the data from the table using the employee id,
there are two tables
1."user_info" which contains id, name,password,email,ScheduleDate,etc!
2."fetch" which contains id,ScheduleDate,starttime,endtime,hours,employeeid.
if i give the name and the password it takes the id of the particular user from "user_info" and it should send the id as the employee id to the table "fetch" and it should fetch the data from that employee id.
User_info database
fetch database
for example if i give the input as name :rajesh password:1995 in user_info,it should take the id of this user and it should send the id as employee id as 15 to the "fetch" table.
when i tried to send the id as employee id it doesn't print anything,and didn't show any error.
<?php
require "init.php";
$name = "surya";
$password = "1995";
$Sql = "SELECT * FROM `user_info`
WHERE `name`='".$name."' AND
`password`='".$password."';";
$result = mysqli_query($con, $Sql);
$retrive = array();
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
{
echo "0 results";
}
}
echo json_encode(array("user_data"=> $response));
?>
i need to fetch all the 3 data from the "fetch" table using the employee id 15.can anyone help to find it out this?
From my understanding your code is correct till second query. In that query execution, you will get multiple records. So you need to use loop for that.
See below example code:
while ($rows = $result->fetch_assoc()) {
$date=$rows["ScheduleDate"];
$start=$rows["StartTime"];
$end=$rows["Endtime"];
$hour=$rows["Hours"];
list($year,$month,$day) = split("-",$date);
$data[] = array("year"=>$year,
"month"=>$month,
"day"=>$day,
"StartTime"=>$start,
"Endtime"=>$end,
"Hours"=>$hour );
}
$response = $data;
Let me know if it helps.
I would use 'INNER JOIN' to achieve what you want:
$sql = "SELECT fetch.ScheduleDate, fetch.StartTime, fetch.Endtime, fetch.Hours"
." FROM fetch INNER JOIN user_info ON fetch.id = user_info.id"
." WHERE user_info.name = ? AND user_info.password = ? ";
//Prepare statement
$stmt = $mysqli_prepare($con, $sql);
//Bind parameter (id)
mysqli_stmt_bind_param($stmt, ss, $name, $password);
//Execute statement
mysqli_stmt_execute($stmt);
//Bind results
mysqli_stmt_bind_result($stmt, $date, $start, $end, $hour);
//Fetch values (puts the values into the variables)
mysqli_stmt_fetch($stmt);

Check value between two times in my database php

I have a booking form where the users can book a certain facility, on a certain date and between two times. I have come to a point where my PHP code will prevent the user from booking the same pitch on the same date and from the same start or end time.
However the user can go between a time and book the same facility on the same date as another user. e.g. if one user has booked from 9 to 12 on the 1st May another user can come in and book the 10 or 11 slot.
Is there any way of preventing the user from booking a time between the time another user has already booked???
<?php
include "config.php";
//Booking point
if(isset($_POST['booking']))
{
//get values for variables
$pitchID = $_POST['pitchID'];
$start_date = $_POST['start_date'];
$start_hour = $_POST['start_hour'];
$end_hour = $_POST['end_hour'];
$booking_age = $_POST['booking_age'];
$pitch_size = $_POST['pitch_size'];
$light_tokens = $_POST['light_tokens'];
/* $q = $db->prepare("SELECT * FROM booking WHERE start_date = ?, start_hour = ?, end_hour=?, pitchID=?");
$query = $q->execute(array($start_date, $start_hour, $end_hour, $pitchID));
$count = $q->rowCount(); */
$q = $db->prepare("SELECT * FROM booking WHERE start_date = ? AND start_hour = ? AND pitchID = ?");
$query = $q->execute(array($start_date, $start_hour, $pitchID));
$count = $q->rowCount();
if($count == 0){
$query = $db->prepare("INSERT INTO booking SET pitchID = ?, start_date = ?, start_hour = ?, end_hour = ?, booking_age = ?, pitch_size = ?, light_tokens = ?, userID='$userID'");
$query = $query->execute(array($pitchID,$start_date,$start_hour,$end_hour,$booking_age,$pitch_size,$light_tokens));
if($query){
echo "Your booking has been made";
header("Location:home2_template.html");
return;
} else {
echo "Fail";
} //else fail
} else {
echo "This booking already exists";
} //else count
} //if booking
?>
If you only can reserve one day, try this
select * from booking
where (start_date='new_date'
and (
(start_hour <='new_start_hour' and end_hour>='new_start_hour')
or
(start_hour<= 'new_end_hour' and end_hour>='new_end_hour')
)
) and pitchID = ?

Fetch data but INSERT results only once a day

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

Categories