How can I make the time difference for each user different? - php

In my script I want to get the last send_time of the user that is logged in. If this send_time is at least a 10 minute time difference with the current time, he will be able to post something new, otherwise he will get an error message.
Though, when I try this, nobody will be able to post for at least 10 minutes since the last post someone made.
$email = $_SESSION['login'];
if ($link)
{
$check="SELECT TIMESTAMPDIFF(MINUTE, send_time, CURRENT_TIMESTAMP) AS 'diff' FROM bloopp WHERE email = '$email' ORDER BY bloopp_id DESC LIMIT 1" or die("Error " . mysqli_error($check));
$res = mysqli_query($link, $check) or die("Error " . mysqli_error($res));
$data = mysqli_fetch_array($res, MYSQLI_ASSOC);
if($data['diff'] <= "10")
{
echo "You posted not so long ago.";
}
else
{
$sql="INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES ('$bloopp', '$browser', 'desktop', NOW(), '$email')";
$result = mysqli_query($link, $sql);
if($result)
{
header('Location: index.php');
}
else
{
echo "Something has gone wrong. We’re sorry.";
}
}
}
else
{
echo "ERROR";
}

Related

Use if statement to select table to input data based on mysql query

I have a mysql database that I am working on. The last part of the work is to send nomination data to different tables based on the zone the user comes from.
There are tree zones (1, 2 and 3) depending on the country you live in.
What I want to do is enter user nomination into 3 different table based on the zone they belong.
I have tried using the if statement but it's not working for me. The only part that enters a value is when the user is in zone 3 (America) that value is sent to the america table. For the other users it does not work.
Here is my current code:
if(isset($_POST['submit']))
{
#$email=$_POST['email'];
$president=$_POST['president'];
#$vice_president=$_POST['vice_president'];
#$secretary=$_POST['secretary'];
#$treasurer1=$_POST['treasurer1'];
#$treasurer2=$_POST['treasurer2'];
#$treasurer3=$_POST['treasurer3'];
#$date= date("Y-m-d h:i:sa");
#$voter=$_SESSION['email'];
$sql = "SELECT zone FROM nickdel_db.students
WHERE email='".$_SESSION['email']."'";;
$result = mysqli_query($con, $sql) or die('error getting zone');
$rs=mysqli_fetch_array($result);
if($rs[0]==1)
{
$query = "INSERT INTO nickdel_db.africavote values(Null,'$email','$president','$vice_president','$secretary','$treasurer1','$treasurer2','$treasurer3','$date','$voter')";
$query_run = mysqli_query($con,$query);
if($query_run)
{
echo '<script>alert("You have succefuly nominated executives");</script>';
function redirect ($location,$delay=0) {
echo "<meta http-equiv='refresh' content='$delay; url=$location' />";
}
redirect('https://nci99set.com/homepage.php');
exit;
}else{
echo '<p class="bg-danger msg-block">Registration Unsuccessful due to server error.</p>';
}
}elseif($rs[0]==2){
$query = "INSERT INTO nickdel_db.europevote values(Null,'$email','$president','$vice_president','$secretary','$treasurer1','$treasurer2','$treasurer3','$date','$voter')";
$query_run = mysqli_query($con,$query);
if($query_run){
echo '<script>alert("You have succefuly nominated executives");</script>';
function redirect ($location,$delay=0) {
echo "<meta http-equiv='refresh' content='$delay; url=$location' />";
}
redirect('https://nci99set.com/homepage.php');
exit;
}else{
echo '<p class="bg-danger msg-block">Registration Unsuccessful due to server error.</p>'; }
}else{
$query = "INSERT INTO nickdel_db.americavote values(Null,'$email','$president','$vice_president','$secretary','$treasurer1','$treasurer2','$treasurer3','$date','$voter')";
$query_run = mysqli_query($con,$query);
if($query_run){
echo '<script>alert("You have succefuly nominated executives");</script>';
function redirect ($location,$delay=0) {
echo "<meta http-equiv='refresh' content='$delay; url=$location' />";
}
redirect('https://nci99set.com/homepage.php');
exit;
}else{ echo '<p class="bg-danger msg-block">Registration Unsuccessful due to server error.</p>';
}
}
}
else
{
}

I want to implement something that doesn't allow the user to rate more than once

I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.

Php login script with login attemp

How can i limit the failed logins with this script? If the login fails, i insert it into the sql. (Is it the right way?)
But how can i check at the next login, that the user can now log in? I would take the login limit in 1 hour.
Aniway, is this code is good for that?
<?php
$loginError = array();
if(isset($_POST['login_submit']))
{
if(empty($_POST['email']) or !isset($_POST['email'])){$loginError[] = "Hiányzó email cím.";}
if(empty($_POST['pass']) or !isset($_POST['pass'])){$loginError[] = "Hiányzó jelszó.";}
if(strlen($_POST['email']) > 50 ){$loginError[] = "Hibás adat az email mezőben.";}
if(strlen($_POST['pass']) > 40 ){$loginError[] = "Hibás adat a jelszó mezőben.";}
if(count($loginError) == 0 )
{
$email = mysqli_real_escape_string($kapcs,$_POST['email']);
$pass = sha1($_POST['pass']);
$lekerdezes = mysqli_query($kapcs, "SELECT * FROM admin_user WHERE email = '$email'") or die(mysqli_error($kapcs));
if(mysqli_num_rows($lekerdezes) > 0 )
{
$adat = mysqli_fetch_assoc($lekerdezes);
if($adat['status'] == 1 )
{
if($adat['pass'] == $pass)
{
$_SESSION['adatok'] = $adat;
$_SESSION['email'] = $adat['email'];
$_SESSION['userid'] = $adat['id'];
header("Location:home.php");
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Még nincs aktiválva a fiók.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
}
?>
I would create a field in the database called status (blocked/ok) and assuming youve got a field timestamp for the last login...
Then Id connect to the database in case the login fails and save the status bloqued and the time stamp. the next attempt you would check the time.now vs last access...
I good suggestion would be create a function for the database connection so you can call it a couple of time without repeat the code, also dont forget use the try/except fot the db connection.

How to see if result of SQL query is empty before performing other queries in PHP

I have the following PHP code which is for a voting system of an app.
Its a Q&A app, and the user can vote for questions and answers that are posted.
In my php code, I first check if the user has voted for a specific question.
This would exist in the QVOTES table, with the email and the id of the question being voted for.
When performing this check, I am not sure of how to see if $result is an empty set, so as to submit the user's vote if they have not voted for the question yet.
How can i get this working? All help is greatly appreciated.
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = '$email'");
if (!mysqli_num_rows($result) ){
if ($result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, '$email')")) {
mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid");
echo "Update successful";
} else{
echo "Update unsuccessful";
}
} else{
echo "null";
}
mysqli_close($con);
Actually you are doing in a wrong way. Please try to do like this:-
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = $email") or die(mysqli_error($con)); // no need of extra quote
if ($result->num_rows == 0 ){ // means no vote-up done till now
$result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, $email)")or die(mysqli_error($con)); // insert
if($result){
echo "Vote Added successfully.";
} else{
echo "Error occur while adding vote.Please try again.";
}
} else{
$result = mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid AND EMAIL = $email")or die(mysqli_error($con)); // upddate
if($result){
echo "Vote updated successfully.";
} else{
echo "Error occur while updating vote.Please try again.";
}
}
mysqli_close($con);
Note:- I change message for better understanding. You can change according to your wish. thanks.
How to see if $result is an empty set?
From the docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE (Ref)
Use $result->num_rows if $result is not FALSE;

echoing two things in different if statements

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$serv_id = $_POST['serv_id'];
$time = $_POST["time"];
$date = $_POST["date"];
if (!isset($_SESSION['id']))
{
echo "sorry you're not logged in.";
exit();
}
if(date('w', strtotime($date)) == 6 || date('w', strtotime($date)) == 0)
{
echo 'Event is on a weekend and cannot be booked.';
}
else
{
echo 'Thank for you booking with Claires hair and beauty';
$time = $time. ":00:00";
$result = mysqli_query($con, "SELECT time FROM tbl_booking WHERE time = '$time' AND date = '$date'") or trigger_error("Query Failed! SQL: $result - Error: ".mysqli_error($con), E_USER_ERROR);
}
if(mysqli_num_rows($result) == 0)
{
$sql = "INSERT INTO tbl_booking (tbl_mem_id, serv_id, date, time) VALUES ('{$_SESSION['id']}','$serv_id','$date','$time')";
mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
location: 'dashboard.php';
}
else
{
echo("this time is already booked");
}
}
Essentially I'm trying to make it check if they're logged in by checking a session variable, then check if the date they have entered is a weekend and then if the date/time being entered is already taken as if it is it just needs to echo this time is already booked.
But what is happening is when the slot is already taken? It echos
Thank for you booking with Claires hair and beautythis time is already booked
Try This Code:
if(date('w', strtotime($date)) == 6 || date('w', strtotime($date)) == 0)
{
echo 'Event is on a weekend and cannot be booked.';
}
else
{
$time = $time. ":00:00";
$result = mysqli_query($con, "SELECT time FROM tbl_booking WHERE time = '$time' AND date = '$date'") or trigger_error("Query Failed! SQL: $result - Error: ".mysqli_error($con), E_USER_ERROR);
}
if(mysqli_num_rows($result) == 0)
{
$sql = "INSERT INTO tbl_booking (tbl_mem_id, serv_id, date, time) VALUES ('{$_SESSION['id']}','$serv_id','$date','$time')";
mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
echo 'Thank for you booking with Claires hair and beauty';//this is right place
location: 'dashboard.php';// Don't know what you trying to do here
}
else
{
echo("this time is already booked");
}
If you want to redirect to another page in php use this:
header('Location: yourpage.php');
PHP Header Function

Categories