Optional Date, Time, Datetime filed for Mysql Database - php

I have a php form with text fields, multiple choices and Date, Datetime, Time fields, i want to set the date, datetime and time fields to be optional while submitting the form. How to do so.? The values are inserted only Date, Date time, time field are entered.
Php code
// Fetching variables
$checkout_date_input = $_POST['checkout_date_input'];
$checkout_time_input = $_POST['checkout_time_input'];
$arrival_date_time = $_POST['arrival_date_time'];
$arrival_flightno = $_POST['arrival_flightno'];
$departure_date_time = $_POST['departure_date_time'];
$departure_flightno = $_POST['departure_flightno'];
//Insert Query of SQL
$query = mysql_query("insert into reservationform(booking_checkout_date, booking_checkout_time, booking_arrival_date, booking_arrival_flightno, booking_departure_date,booking_departure_flightno) values ('$checkout_date_input', '$checkout_time_input',
$arrival_flightno,'$departure_date_time',$departure_flightno)");

Solution #1
The best way is to check if the user has entered something, if they have you can pass the value, if they haven't you make the variable NULL.
if(!empty(trim($_POST['checkout_date_input']))){
$checkout_date_input = $_POST['checkout_date_input'];
} else {
$checkout_date_input = null;
}
Solution #2
Another thing that you can do is specify which column names you want to insert into the database.
INSERT INTO table (column1, column2) VALUES ('value1','value2')
This query will only insert values into column1 and column2, the other columns will be null.
If you set up a number of if statements, which check whether or not the field has been filled, you can determine which columns to insert values into and which not.
Both solutions are based on the assumption that your database columns allow null values, which will be inserted into the database.
Safety
Your code is very vulnerable for attacks to your database. I suggest using PDO and prepared statements to ensure the sanitation of your database queries. More info can be found here.

Related

PHP MYSQL: Check form for blank value, get value from table 2 and use that value in table 1

I have been searching and trying different methods and remain stumped. I have a form in which the user can input a size code and a dollar value on several different modules. If the user does not input a dollar value for insertion into table1, I want to be able to use a default value in table2 based on the size code and insert that value into table1 for the appropriate field when the user clicks on "Add Client".
My two tables are titled as Clients and Size. The Size table has identical field names as the Clients table for the specific fields.
I am using PHP and mysqli syntax for INSERT, UPDATE etc. and using MySQL Workbench.
I cannot hardcode a value into the HTML as this default value changes regularly and would be easier to maintain within the mysql database.
Is there a way to check if the value is empty prior to insert and if it is, get the default value from the Size table else use the user input value or is there a method within MySQL workbench to check after insert and pull the data from the Size table into the Clients table? Sorry for the long explanation, but I'm truly stumped.
An example of how I do the insert of the form into Clients is as follows:
$size_code = mysqli_real_escape_string($db, $_POST['size']);
$value1 = mysqli_real_escape_string($db, $_POST['val1']);
$value2 = mysqli_real_escape_string($db, $_POST['val2']);
$fields = 'size_code, val1, val2'; //fieldnames in database
$values = "'$size_code', '$value1', '$value2'";
$sql = "INSERT INTO clients ($fields) VALUES ($values)";
This works just fine for inserting the form, but if the user leaves val2 blank I need to pull a default value from the corresponding field from the Size table and use it instead of having a blank field. Any suggestions would be greatly appreciated.
You can use a SELECT statement in the INSERT query, and IF() expressions to replace empty strings with the defaults.
$sql = "INSERT INTO clients (size_code, val1, val2)
SELECT size_code, IF(? = '', val1, ?), IF(? = '', val2, ?)
FROM sizes
WHERE size_code = ?";
$stmt = mysqli_prepare($db, $sql);
mysqli_stmt_bind_param($stmt, "sssss", $_POST['size'], $_POST['val1'], $_POST['val1'], $_POST['val2'], $_POST['val2']);
mysqli_stmt_execute($stmt);

how to insert data from primary key column to foregin key

i am inserting data from a form i want when i will insert data so the first column primary id which is using in second column as a foreign key should be increased
i have tried this code but not working
first table code
$this->db->query("insert into af_ads (ad_title,ad_pic,ad_description)
values ('$title','$filepath','$description')");
second table code
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category','ad_id')");
NOTE: i want to insert ad_id into ad_id_fk
Try this:
// Your first query
$this->db->query("insert into af_ads(ad_id, ad_title, ad_pic, ad_description)
values ('', '$title', '$filepath', '$description')");
$ad_id = $this->db->insert_id(); // This returns the id that is automatically assigned to that record
// Use the id as foreign key in your second insert query
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category', $ad_id)");
MySQL provides the LAST_INSERT_ID function as way to retrieve the value generated for an AUTO_INCREMENT column from the immediately preceding INSERT statement.
A lot of client libraries make this conveniently avaiable (e.g. PDO lastInsertId function.)
(I'm not familiar with CodeIgniter or ActiveRecord, so I can't speak to how that's made available.
Your code looks like it's using the PDO interface... but I'm not sure about that.
# either we need to check return from functions for errors
# or we can have PDO do the checks and throw an exception
$this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
# attempt insert which will generate AUTO_INCREMENT value
$this->db->query("INSERT (ad_id, ... ) VALUES (NULL, ...)");
# if previous insert successfully inserted a row (or rows)
$ad_id = $this->db->lastInsertId();
You really need to check whether the previous insert was successful or not. If you aren't going to code that check yourself, then PDO does provide a mechanism that performs this checking automatically, and will throw an exception if a MySQL error occurs.
I've avoided copying your original code, which looks like it's vulnerable to SQL Injection. If you're using PDO, you can make effective use of prepared statements with bind placeholders, rather than including values in the SQL text.

How do I bind current column value in PDO?

I have a feature in my web app where a table is "quick-editable", that is, its cells can be edited directly. When the user saves his changes, the client sends to the server the changed rows, with their changed columns (excluding non-changed columns, just to clarify), and their corresponding IDs.
In order to do UPDATE queries efficiently, I am using PDO's prepared statement feature. Here is an equivalent statement what I currently came up:
UPDATE table
SET
col1 = :arg_col1,
col2 = :arg_col2,
col3 = :arg_col3
WHERE
ID = :arg_ID
Then I came up with this problem in which I cannot set a column into its current value. Because only the edited column(s) in a row is/are submitted, I only need to bind the data to their respective column(s). For example, if only col1 and col2 are changed, the resulting statement should be
UPDATE table
SET
col1 = 'new data',
col2 = 'an edit',
col3 = col3 /* Use the current value of the column */
WHERE
ID = 153454
Modifying the statement directly would definitely nullify the performance improvement of using the same prepared statement for updating multiple rows. Sadly, PDO doesn't seem to have an option to bind a column to its current value.
How should I solve this problem?
ADDITIONAL: I do not wish to send all the columns, for performance reasons.
Unfortunately, an approach you are aiming to, won't actually work. You just can't prepare a statement in one call and then use it in all subsequent calls - you'll have to prepare it every time again.
So, there is no point in creating a generic query. Thus, you can create a custom query for the very data set. And this latter task can be automated: just create your UPDATE statement dynamically.
A solution, based on the tag wiki (scroll to the very bottom):
// first, have your update data in array (you can omit this line though)
$update = $_POST;
// next, list all fields a user allowed to
$allowed = array("col1","col2","col3");
// finally, create a SET statement query dynamically
$set = pdoSet($fields,$values, $update);
// voila - your query contains only fields were POSTed:
$sql = "UPDATE users SET $set WHERE id = :id";
$stm = $dbh->prepare($sql);
// just add an ID and execute
$values["id"] = $_POST['id'];
$stm->execute($values);
You actually don't want the col3 in the sql, what you need to do is to build the sql dynamically, only add the changed columns to the sql.

MYSQL and PHP INSERT NULL values

lets say my table only has these members - id (key) and date (which defaults to NULL) .
Now when I want to insert a row with my php , do I need to check before my query whether date has a value or not or can I just insert like so -
$query = "INSERT INTO mytable VALUES(3,{$_GET['date]})"
And mysql would assign a NULL value to date ?
And does this hold true to a table no matter how large ?
e.g : can I insert many values that come from php and may be empty(or null) to a table , and mysql would automatically assign NULL to them (if I defined them as NULL by default of course) or do I need to do all kinds of checks before my inserts?
No, it will assign the value passed with the parameter $_GET['date']. If the value is empty '' and the date was of data type varchar it will insert a value of '' which is different than NULL then it will insert an empty. Thats because NULL and empty strings are not equal. They are two different things in SQL.
If you want to insert NULL values, either ignore this column in the insert columns list, then it will assigned with the default value which is NULL. Or write it explicitly in the values of the INSERT statement.
Note that: Your code this way is vulnerable to SQL injection. You should use prepared statements or PDO instead. See this for more details:
Best way to prevent SQL injection?
This might be relevant and this would also make sure you are not vulnerable to sql injection attacks.
I'd say to just check each variable personally, then you have way more control over your variables before they are getting put in your database.
Try this
$query = "INSERT INTO mytable VALUES(3,'".$_GET['date']."')";
But also consider the datatype of your table field if its set to date/datetime then, check the return value of $_GET['date'] it must also in form of date.
That snippet is wide open to SQL injection. Escape your values or use prepared statements!
If the variable contains nothing, the query will look like ... VALUES (3,). That's a syntax error, so it doesn't work.
If you'd change this to VALUES(3, '{$_GET['date']}')", so in the case of an empty variable the query would be ... VALUES(3, ''), an empty string is the value. That will be cast to some sane value for the column in question, in case of a date column, to an unrecognized date. That's not NULL.
NULL only applies if you omit the column entirely from a query or explicitly set it to NULL. In any other case, the value will be something other than NULL.
$date = date("d-m-Y",strtotime($_GET['date']));
if(isset($date))
$query = "INSERT INTO mytable VALUES(3,$date)";

PHP: Inserting the current timestamp into SQL Server 2005

How do I insert a current_timestamp into an SQL Server 2005 database datable with a timestamp column?
It should be simple but I cannot get it to work. Examples would be much appreciated.
if you can execute a query from PHP then it should just be a matter of using 'getdate()' ;
update MyTable set MyColumn=getdate();
or
insert into MyTable (MyColumn) values (getdate());
The column datatype should be datetime
You can either get the database to work out the date:
$sql = 'INSERT INTO tablename (fieldname) VALUES (getdate())';
or get PHP to work out the date
$sql = 'INSERT INTO tablename (fieldname) VALUES (\'' . date('Y-m-d H:i:s') . '\')';
then something like mssql_execute($sql); but this depends on how you are connecting to your database
To insert data into a timeStamp field, I think you have to use DEFAULT.
For example:
INSERT INTO User(username, EnterTS) VALUES ('user123', DEFAULT)
where EnterTS is a TimeStamp field
You just use the normal mechanism to execute your queries into SQL Server, and use what follows.
The current_timestamp function returns it
insert into table (creation_date) VALUES (current_timestamp)
Complete example
CREATE table timestamp_test (creation_timestamp datetime)
INSERT INTO timestamp_test (creation_timestamp) VALUES (current_timestamp)
SELECT * FROM timestamp_test
DROP TABLE timestamp_test
If you explain the error you are receiving (and post your insert or update code), it might make it easier to see what your problem is. One possible issue is that you must be inserting into a datetime field (or in 2008 you could use a date field as well). Occasionally people think that they can insert the current date into a timestamp field but even though the name of this data type seems as if it should be date related, this data type actaully has nothing to do with dates and times and cannot accept date data.
I realize this is an old post but I ran across this and figured others might too.
What I do is to create a field in the table using the datatype of datetime and then for the column properties for the default Value or binding, I enter getdate(). Every record that gets entered into the table now has a date and time stamp.

Categories