I created a form where a user can change his name, saved in a database. I'd like to control, after submit, if the user has already changed his name less than a month ago.
In my database i have a column called "name_changed", where the default data is 0000-00-00 and when the name is changed, the date is saved in "name_changed". But i don't know how controll the month.
Here the HTML code:
<form action="#" method="POST">
<input type="text" name="name" required>
<input type="submit" name="change-name">
</form>
Here the PHP code:
if(isset($_POST['change-name']) && $_POST['name'] != ""){ // take data form
$errors = "0";
if(strlen($_POST['name']) < 21){ // control length
$name = "$_POST[name]";
$sql = "SELECT * FROM user_db WHERE email = '$_SESSION[email]'";
$date_today = date('Y-m-d'); // i don't know if it's right
$data_today_month = // take only month
$date_db = $fetch_info['name_changed']; // take date on db from column "name_changed"
$date_db_month = // take only month
$diff_between_date_today_month_and_data_db_month = $date_today_month - $date_db_month;
if($data_db == '0000-00-00' or $diff_between_date_m_and_data_db_m>= '1'){
$update_pass = "UPDATE user SET name = '$name' WHERE email = '$_SESSION[email]'";
$run_query = mysqli_query($con, $update_pass);
if($run_query){
$sql = "SELECT * FROM user WHERE email = '$_SESSION[email]'";
$update_pass = "UPDATE user SET name_changed = '$date' WHERE email = '$_SESSION[email]'";
$run_query = mysqli_query($con, $update_pass);
}
}else{
$count_error = '1';
$errors = "you can only change your name once a month!";
}
}else{
$count_error = '1';
$errors['db-error'] = "Something wrong!";
}
}
Thankss
CodePudding user response:
Consider this for your application SELECT DATEDIFF(NOW(),name_changed); for the number of days difference. If less than 30, stop the effort. Keep it simple.
CodePudding user response:
Have a look at the php date formatting: https://www.adminschoice.com/php-date-format
As you have the line
date('Y-m-d')
You can also have
date("m") --> for only the month.
But by doing the check on month, you could potentially have a diff of one month when the user changed his name on 31-jan and also on 1-feb: month 1 and month 2.