Enter the date when the checkbox is selected - php

I'm trying to make it so that when the checkbox is selected it puts today's date in the database, I tried using timestamp but it puts it in all the spaces in the column, I'm a beginner in php
The code I made was this:
<?php
if (isset($_POST['Abate'])){
$Abate="Sim";
$data=time();
$DiaAbate= date("Y/m/d", $data);
}
else{
$Abate="Nao";
$DiaAbate="";
}
?>

You have not included your table structure (CREATE TABLE statement) so I have assumed you have a DATE column for storing $DiaAbate. I have also assumed that the submitted date is in 22/11/2022 format. If you are using a different format for the POSTed date value, you will need to change the format string passed into DateTime::createFromFormat().
Your current code is vulnerable to SQL Injection as you are combining your static strings with user input without any validation. The simple example below uses a prepared statement for the insert query -
if (isset($_POST['Abate'])){
$Abate = 'Sim';
// create a date from the posted date string adn format it
// see https://www.php.net/manual/en/datetime.createfromformat.php
$DiaAbate = DateTime::createFromFormat('d/m/Y', $_POST['DiaAbate'])->format('Y-m-d');
} else {
$Abate = 'Nao';
$DiaAbate = null;
}
$query = 'INSERT INTO pc (Abate, DiaAbate) VALUES (?, ?)';
$query_run = mysqli_execute_query($con, $query, [$Abate, $DiaAbate]);
if ($query_run) {
$_SESSION['status'] = 'Inserted Succesfully';
header('Location: indexx.php');
} else {
$_SESSION['status'] = 'Not Inserted';
header('Location: indexx.php');
}

Related

how to prevent duplicate entry in mysql while data are entered from array?

I am new in android development I am sending a json array through android application and insert that data into MySQL database. The problem is that whenever I insert userJSON it entered every time with duplicate entries. So, I want to prevent duplicate entry in mysql how can this possible with php. Please help me to solve this problem.
json string from android side
'[{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 15:26:29 GMT+05:30 2016"},
{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 13:49:50 GMT+05:30 2016"}]';
Here is my php file for post json:
<?php
require_once('conn.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$json = $_POST["usersJSON"];
echo $json;
if (get_magic_quotes_gpc())
{
$json = stripslashes($json);
}
$data = json_decode($json,true);
$query=mysqli_query($con,"SELECT *
FROM users
where number = '$number'
and type = '$type'
and date = '$date'
and duration= '$duration'");
if(mysqli_num_rows($query)>0) {
echo "already exist";
}
elseif(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
$valuesArr = array();
foreach($data as $row)
{
$type = mysqli_real_escape_string( $con,$row['type'] );
$duration = mysqli_real_escape_string($con, $row['duration'] );
$number = mysqli_real_escape_string( $con,$row['number'] );
$date = mysqli_real_escape_string( $con,$row['date'] );
$valuesArr[] = "('$type', '$duration', '$number', '$date')";
}
$sql .= implode(',', $valuesArr);
if(mysqli_query($con,$sql))
{
echo 'Entry Added Successfully';
}
else
{
echo 'Could Not Add Entry';
}
}
//Closing the database
mysqli_close($con);
}
?>
Create a UNIQUE INDEX
Regardless of whatever programming language that you use, all the constraints on the data have to be enforced with in the database and not in your application layer. And the easiest way to do that is to add a UNIQUE KEY on the columns in question.
ALTER TABLE users ADD UNIQUE KEY all_columns(number,type,date,duration)
I am adding all the four columns to the unique index because you seem to want any column to have duplicate values taken in isolation. Please confirm if this is correct or choose the columns appropriately when creating the index.
Simply your code
With a unique key in place, your don't need that SELECT
$data = json_decode($json,true);
if(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
....
}
Use Prepared Statements
Instead of a huge string concatenation as is being currently done and multple calls to mysqli_real_escape, you would be better of using prepared statements. You might even get a tiny increase in performance. However more importantly there is a maximum size of a string that can be passed through to the server, if you get a large array you might go beyond that.

url did not send correct data ,what can i do for send the correct values

i want to send data with url
and my code php is:
<?php
$db_host="127.0.0.1"; $db_uid="root"; $db_pass="";
$db_name="highway_db"; $db_con =
mysqli_connect($db_host,$db_uid,$db_pass,$db_name);
$longitude =(isset( $_GET['lon`enter code here`gitude']));
$latitude = (isset($_GET['latitude']));
$timestamp = (isset($_GET['timestamp']));
$result = mysqli_query($db_con,"INSERT INTO accident (longitude, latitude, timestamp)
VALUES ($longitude, $latitude, $timestamp)");
if($result == true)
echo '{"query_result":"SUCCESS"}';
else
echo '{"query_result":"FAILURE"}';
mysqli_close($db_con);
?>
and my table is accident have id,longitude,latitude and timestamp
id is AUTO_INCREMENT.
but thme problem when i use this url :
http://127.0.0.1/addAccidents.php?longitude=3.54&latitude=3.09&timestamp=2016-04-25 11:11:00
i find that is add to my table accident
longitude=1
latitude =1,
timestamp =0000-00-00 00:00:00.
and this my problem with url please help me
try this :
$result = mysqli_query($db_con,"INSERT INTO accident (longitude, latitude, timestamp) VALUES ('".$longitude."', '".$latitude."', '".$timestamp."')");
Echo the sql query and try to run query directly in your phpmyadmin and also check your database table column type.
try changing the setting of hte variables around - you should anyway because even if the GET value is not present - this code will still try to insert values into the db, such as :
if(isset( $_GET['longitude'])){$longitude =$_GET['longitude']};
and then write code that only allows the writing to the db if the three values are set.
isset() is a function which checks if a given variable has contents or not. If it has it returns 1 and if not it return 0.
In all 3 below statements, you are just checking the variables, you have not assigned values to your variables!
Try to use this code here, it should work if GET REQUEST with those specified parameters is sent!
<?php
$db_host="127.0.0.1";
$db_uid="root";
$db_pass="";
$db_name="highway_db";
$db_con = mysqli_connect($db_host,$db_uid,$db_pass,$db_name);
$longitude = isset($_GET['longitude'])?$_GET['longitude']:"";
$latitude = isset($_GET['latitude'])?$_GET['latitude']:"";
$timestamp = isset($_GET['timestamp'])?$_GET['timestamp']:"";
$query = "INSERT INTO accident (longitude,latitude,timestamp) VALUES ($longitude,$latitude,$timestamp)";
if(mysqli_query($db_con,$query)){
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
echo "ERROR= ". mysql_error();
}
mysqli_close($db_con);
?>
Let me know how it goes....

using mysql NOW() function to update row in database not working in PHP query

I am trying to use the NOW() mysql function to update the datetime column for an inserted row. The datetime column is called 'transaction'. I tried finding a similar PHP function to mirror/mimic the datetime format but couldn't find one suitable.
$purchase = query("INSERT INTO `Portfolio`(`id`, `symbol`, `shares`, `transaction`, `transType`) VALUES ((?),(?),(?),(?),(?)) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)",$user,$symbol,$shs,NOW(),"BUY");
You can use PHP date function:
date("Y-m-d H:i:s")
to put current time
or you can not bind the parameter:
$purchase = query("INSERT INTO `Portfolio`(`id`, `symbol`, `shares`, transaction`, `transType`) VALUES (?,?,?,NOW(),?) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)",$user,$symbol,$shs,"BUY");
The NOW() goes in place of one of the "?", not in the bind list.
If you also wanted to update that field in case the statement turns into an UPDATE, then you need it in the SET also.
$database = new database;
$now = $database->now();
class database {
...
public function now($query = "SELECT NOW();"){
$sth = $this->connect->prepare($query);
// execute
if ($sth->execute()) {
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result["NOW()"];
} else {
echo "\nPDO::errorInfo():\n";
print_r($sth->errorInfo());
echo "\nQuery:\n";
echo $query;
echo "\nParam:\n";
}
}
}

PHP loop through array and check dates

I have a form in my app. This form consists of 2 textfields type='date'. Now, when two dates are given, the dates are send to a PHP-script that translates the dates with strtotime.
The PHP-script makes a connection to a mySQL database that returns a result with requests. I would like to loop through all requests and check if the date of the request is BETWEEN the two dates that where sent by the form.
What happens now:
$sql = "SELECT * FROM Requests";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($result) {
foreach ($result as $row){
$return[]=array('employeeid'=>$row['employeeid']
'id'=>$row['id'],
'startdate'=>$row['startdate'],
'enddate'=>$row['enddate'],
'type'=>$row['type'],
'reason'=>$row['reason']);
}
header('Content-type: application/json');
echo '' . json_encode($return) .'';
return true;
} else {
return false;
}
The code above generates a perfect json-file with the requests. But as I mentioned I would like to check whether the startdate of the requests above is between the two dates that are send by the form.
Something like this:
if (($request_startdate >= $startdate) && ($request_startdate <= $enddate)) {
//generate array with the requests
} else {
//no requests between dates.
}
But how to loop through the requests and check the startdate?
Thanks in advance.
Jan
You are taking the hard way, it's easier to add a where statment to your select query:
I assume that your form have two fields named date1, date2
$sql = "SELECT * FROM Requests where startdate>:date1 and enddate<:date2";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':date1',$_POST['date1'],PDO::PARAM_STR);
$stmt->bindValue(':date2',$_POST['date2'],PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Convert your string inputs to DateTime and format it to ISO date format (or at least make sure they are in a format that mySQL accepts)
$sdt = DateTime::createFromFormat('format of your input', $request_startdate);
$edt = DateTime::createFromFormat('format of your input', $request_enddate);
Modify your sql to query only the rows that you want to use:
SELECT * FROM Requests
WHERE startdate <= :sdt AND :edt >= :edt
Then bind your parameters (see php doc):
$stmt->bindParam(':sdt', $sdt->format('YYYY-mm-dd 00:00:00'), PDO::PARAM_STR);
$stmt->bindParam(':edt', $edt->format('YYYY-mm-dd 23:59:59'), PDO::PARAM_STR);

Inserting date value into MySQL

I currently have a form which takes a date in the format m/d/y - I have then attempted to insert it into a table, but the value in the table reads 0000-00-00. I understand that the value is not being inserted due to the format of the date being inserted.
The problem is, I am unsure on how to change the format so that it is inserted in a format that MySQL will store.
Below is the function that inserts the data into the table:
public function addUser($array) {
$array['password'] = $this->hashPassword($array['password']);
$implodeArray = '"'.implode( '","', $array ).'"';
$sql = ('INSERT INTO user
(email, password, firstName, lastName, officeID, departmentID, managerID, roleID, username, contractType, startDate, endDate, totalLeaveEntitlement, remainingLeave)
VALUES
('.$implodeArray.')');
echo $sql;
die();
mysql_query($sql,$this->_db) or die(mysql_error());
mysql_close();
}
Due to the use of implodeArray, I cannot format the value of startDate and endDate to match the MySQL DATE format.
Why don't you use similar method to when you hashed the password? So, you just need to add another function to convert your date input into mysql date format:
public function addUser($array) {
$array['password'] = $this->hashPassword($array['password']);
$array['startDate'] = $this->mysql_date_format($array['startDate']);
$array['endDate'] = $this->mysql_date_format($array['endDate']);
$implodeArray = '"'.implode( '","', $array ).'"';
$sql = ('INSERT INTO user (email, password, firstName, lastName, officeID, departmentID, managerID, roleID, username, contractType, startDate, endDate, totalLeaveEntitlement, remainingLeave) VALUES ('.$implodeArray.')');
echo $sql;
die();
mysql_query($sql,$this->_db) or die(mysql_error());
mysql_close();
}
Hmmmmm
I know it looks like its easier to write queries like this (one function generates all your parameters etc etc) but I would STRONGLY advise that you prepare your statements - someone coming along to support your code will thank you for it.
That way you can use NOW(), DATE_DIFF and such other awesomes...
I know that doesn't answer your question but I do feel you should take the time to construct your queries properly - help prevent run time errors/ attacks etc etc.
Not sure on the specifics of your issue, but in general:
$mysql_formatted_date = date("Y-m-d", strtotime($mdy_formatted_date));
I think you'll want STR_TO_DATE()
STR_TO_DATE("%m/%d/%Y") is I think the right format
While both arrays and mysql columns have an implicit order, how do you know they are the same?
It would have been a lot more useful if you'd provided the output of 'echo $sql' rather than all the PHP code - although hte latter highlights a lot of messy programming not least:
the field order problem
quoting non-numeric values
not escaping fields properly
not trapping / handling errors
no comments
form which takes a date in the format m/d/y - I have then attempted to insert it
In the case of date fields, quoting is optional depending on the format used for the literal - but it is always ordered as per ISO 8601 - i.e. big endian
public function addUser($array) {
list($d,$m,$y) = explode("/",$array['startDate']);
$array['startDate'] = "$y-$m-$d";
list($d,$m,$y) = explode("/",$array['endDate']);
$array['endDate'] = "$y-$m-$d";
$array['password'] = $this->hashPassword($array['password']);
foreach($array as $key => $value){
$array[$key] = mysql_real_escape_string($value);
}
$implodeArray = implode("','", $array);
$sql = "INSERT INTO user VALUES (NULL,'$implodeArray')";
echo $sql;
die();
mysql_query($sql,$this->_db) or trigger_error(mysql_error());
}

Categories