Hi I don't know what's the problem. The date field is not inserting to mysql.The format should be in YYYY-MM-DD like in mysql. Maybe that's the problem? The date in the input type is mm-dd-yyyy.
Query:
if(isset($_POST['subButton']))
{
mysql_query("INSERT INTO order_queue (Date, Tracking, Name, Address,
ContactNo, dateneed, Payment, Claiming, qtyBlackWhite,
totalBlackWhite, qtyChocnut, totalChocnut, qtyHotMama, totalHotMama,
qtyMocha, totalMocha, qtyUbeKeso, totalUbeKeso, GrandTotal)
VALUES (NOW(), '".$_POST['Tracking']."', '".$_POST['Name']."',
'".$_POST['Address']."', '".$_POST['ContactNo']."',
'".$_POST['dateneed']."', '".$_POST['Payment']."',
'".$_POST['Claiming']."', '".$_POST['qtyBlackWhite']."',
'".$_POST['totalBlackWhite']."', '".$_POST['qtyChocnut']."',
'".$_POST['totalChocnut']."', '".$_POST['qtyHotMama']."',
'".$_POST['totalHotMama']."', '".$_POST['qtyMocha']."',
'".$_POST['totalMocha']."', '".$_POST['qtyUbeKeso']."',
'".$_POST['totalUbeKeso']."', '".$_POST['GrandTotal']."')");
}
html
<input type="date" name="dateneed" id="dateneed" />
The date input type is mm/dd/yyyy.
In mysql the dateneed field is in DATE datatype and NN. What's wrong? In the query the Date is the auto inserting of date when the form is submitted. The problem is the dateneed is kinda preventing the form from insert everything. T__T
There are more problems with it.
As other suggested, first of all, don't use PHP mysql extension, use mysqli or PDO.
Second, always check for EVERY user input data, and format them according to your query.
Use parameters in your SQL or escape the values you insert.
But to answer your question, use this:
$d = explode('/',$_POST['dateneed']);
$date = $d[2].'-'.$d[0].'-'.$d[1];
But you should check the date to be valid.
You Just have to pass fieldname is dateneed instead of Date
if(isset($_POST['subButton']))
{
mysql_query("INSERT INTO order_queue (dateneed, Tracking, Name, Address,
ContactNo, dateneed, Payment, Claiming, qtyBlackWhite,
totalBlackWhite, qtyChocnut, totalChocnut, qtyHotMama, totalHotMama,
qtyMocha, totalMocha, qtyUbeKeso, totalUbeKeso, GrandTotal)
VALUES (NOW(), '".$_POST['Tracking']."', '".$_POST['Name']."',
'".$_POST['Address']."', '".$_POST['ContactNo']."',
'".$_POST['dateneed']."', '".$_POST['Payment']."',
'".$_POST['Claiming']."', '".$_POST['qtyBlackWhite']."',
'".$_POST['totalBlackWhite']."', '".$_POST['qtyChocnut']."',
'".$_POST['totalChocnut']."', '".$_POST['qtyHotMama']."',
'".$_POST['totalHotMama']."', '".$_POST['qtyMocha']."',
'".$_POST['totalMocha']."', '".$_POST['qtyUbeKeso']."',
'".$_POST['totalUbeKeso']."', '".$_POST['GrandTotal']."')");
}
YOu can manipulate the dateneed value into require format then we can store it to database.
if(isset($_POST['subButton']))
{
$dateneedExplode = explode('-',$_POST['dateneed']);
$dateneedValue = $dateneedExplode[2].'-'.$dateneedExplode[0].'- '.$dateneedExplode[1];
mysql_query("INSERT INTO order_queue (Date, Tracking, Name, Address,
ContactNo, dateneed, Payment, Claiming, qtyBlackWhite,
totalBlackWhite, qtyChocnut, totalChocnut, qtyHotMama, totalHotMama,
qtyMocha, totalMocha, qtyUbeKeso, totalUbeKeso, GrandTotal)
VALUES (NOW(), '".$_POST['Tracking']."', '".$_POST['Name']."',
'".$_POST['Address']."', '".$_POST['ContactNo']."',
'".$dateneedValue."', '".$_POST['Payment']."',
'".$_POST['Claiming']."', '".$_POST['qtyBlackWhite']."',
'".$_POST['totalBlackWhite']."', '".$_POST['qtyChocnut']."',
'".$_POST['totalChocnut']."', '".$_POST['qtyHotMama']."',
'".$_POST['totalHotMama']."', '".$_POST['qtyMocha']."',
'".$_POST['totalMocha']."', '".$_POST['qtyUbeKeso']."',
'".$_POST['totalUbeKeso']."', '".$_POST['GrandTotal']."')");
}
Related
When I try to send data from an html form to a database using php, I keep getting error unexpected ; in line 6. I cant seem to find the exact cause.
This is the code of send.php:
<?php
//Connecting to sql db.
$connect = mysqli_connect("host","user","password","database");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO sw5_green (firstname_r, lastname_r, vid, occupation, address, firstname_s, lastname_s, country, amount, currency)
VALUES ('$_POST[post_firstname_r]', '$_POST[post_lastname_r]', '$_POST[post_vid]', '$_POST[post_occupation]', '$_POST[post_address]', '$_POST[post_firstname_s]', '$_POST[post_lastname_s]', '$_POST[post_country]', '$_POST[post_amount]', '$_POST[post_currency]')";
?>
You are missing ) at the end of the statement. put ) this before last ;.
Try it,
mysqli_query($connect,"INSERT INTO sw5_green (firstname_r, lastname_r, vid, occupation, address, firstname_s, lastname_s, country, amount, currency)
VALUES ('$_POST[post_firstname_r]', '$_POST[post_lastname_r]', '$_POST[post_vid]', '$_POST[post_occupation]', '$_POST[post_address]', '$_POST[post_firstname_s]', '$_POST[post_lastname_s]', '$_POST[post_country]', '$_POST[post_amount]', '$_POST[post_currency]')");
You are missing )
Replace your code with query with this
mysqli_query($connect,"INSERT INTO sw5_green (firstname_r, lastname_r, vid, occupation, address, firstname_s, lastname_s, country, amount, currency)
VALUES ('$_POST[post_firstname_r]', '$_POST[post_lastname_r]', '$_POST[post_vid]', '$_POST[post_occupation]', '$_POST[post_address]', '$_POST[post_firstname_s]', '$_POST[post_lastname_s]', '$_POST[post_country]', '$_POST[post_amount]', '$_POST[post_currency]'))";
wrong syntax
'$_POST[post_firstname_r]' should be $_POST['post_firstname_r']
Always escape your data before saving.
I've created an HTML form and its corresponding insert.php code. The question I have is this:
1) Does PHP read the ID or NAME field (HTML) when the user presses submit on an HTML form?
2) How do I use PHP to combine fields so that it is inserted into a MySQL Database in a single column/field? (I'm trying to be more specific; last few Questions of mine were flagged on Stack, so I'm -trying- to adhere to the community standard)
<label class="description" for="element_23">Date of Birth </label>
<span>
<input id="element_23_1" name="applicants.DOB_month" class="element text" size="2" maxlength="2" value="" type="text"> /
<label for="element_23_1">MM</label>
</span>
<span>
<input id="element_23_2" name="applicants.DOB_day" class="element text" size="2" maxlength="2" value="" type="text"> /
<label for="element_23_2">DD</label>
</span>
<span>
<input id="element_23_3" name="applicants.DOB_year" class="element text" size="4" maxlength="4" value="" type="text">
<label for="element_23_3">YYYY</label>
</span>
--MySQL--
$sql = "INSERT INTO applicants (fname, lname, address, city, state, zip, country, phone, school, DOB, age, amount_requested) VALUES ('$applicants_fname', '$applicants_lname', '$applicants_address','$applicants_city','$applicants_state','$applicants_zip','$applicants_country','$applicants_phone','$applicants_school','$DOB','$age', '$applicants_amount_requested')";
To create 1 field in DB from 3 fields with data from your form you can get all this 3 fields (from $_POST оr $_GET array (this param must be in <form>s action attribute)):
$value = $_POST['field1_name'].'/'.$_POST['field2_name'].' /'.$_POST['field3_name'];
and then insert it into DB.
it depends of your column type but if this is a string,
you can use MySQL CONCAT
INSERT INTO `table`(`field`) VALUES (CONCAT('val1', '/', 'val2', '/', 'val3'));
on form submit, the request string is created from the name fields, not the id. Thus the request is name1=value1&name2=value2 ....
You have to create the valid value to insert in the right field. You can use php and concatenate values $values = $_POST['name1'] . 'delimiter' . $_POST['name2'] or you can use the SQL CONCAT function.
Assign a new variable and concatenate the ones you want to be entered in the db, then use that variable as the final product.
I.e.: and assuming a POST form method, since you did not specify that in your question.
$year = $_POST['applicants.DOB_year'];
$month = $_POST['applicants.DOB_month'];
$day = $_POST['applicants.DOB_day'];
$DOB = $year . "-" . $month . "-" . $day;
$sql = "INSERT INTO applicants
(fname, lname, address, city, state, zip, country, phone, school, DOB, age, amount_requested)
VALUES ('$applicants_fname', '$applicants_lname', '$applicants_address','$applicants_city',
'$applicants_state','$applicants_zip','$applicants_country','$applicants_phone','$applicants_school',
'$DOB','$age', '$applicants_amount_requested')";
You'll also want to set your column as a DATE type since MySQL stores that as YYYY-MM-DD.
https://dev.mysql.com/doc/refman/5.1/en/datetime.html
The reason being that it will be easier to query later. You will have a harder time if your column is set to VARCHAR and would have to result in using more functions/resources than what is required.
Use MySQL's built-in DATE functions.
The above will render something like 1995-12-22
From the manual:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
You should also use a prepared statement, since your code may be prone to an SQL injection. It is unknown if you are escaping your data.
https://en.wikipedia.org/wiki/Prepared_statement
"1) Does PHP read the ID or NAME field (HTML) when the user presses submit on an HTML form?"
If you're using pure PHP, then it relies on the "name" attribute.
Consult http://php.net/manual/en/tutorial.forms.php
JS/Ajax however, does support the ID attribute though.
Consult http://webdesign.tutsplus.com/tutorials/building-a-bootstrap-contact-form-using-php-and-ajax--cms-23068
I have just begun learning PDO. I have connected to my database and I have a working login happening with the mySql database. Now I am trying to get three pieces of data from a form and then insert them into the table. I have been on this for a week and every version I come up with fails. I get no error messages yet when I check the table it remains empty.
As I have other PDO action working, I'm confident that the problem is in the following piece of code. The button involved is named 'addGig'. This is the first time I have used the name of a button... I'm not confident with this.
I have just edited this post to include my revised code.
So many rookie mistakes!
$date = $_POST['date'];
$venue = $_POST['venue'];
$time = $_POST['time'];
if (!empty($date) && !empty($venue) && !empty($time)){
try{
$query = $connect->prepare("INSERT INTO gigs (date, venue, time) VALUES (:date, :venue, :time)");
$query->bindParam(':date' , $date);
$query->bindParam(':venue' , $venue);
$query->bindParam(':time' , $time);
$query->execute();
}
catch(PDOException $e)
{
handle_sql_errors($query, $e->getMessage());
}
}
}
This is my html form
<form>
<label>date</label><br><input type="text" name="date"><br>
<label>venue</label><br><input type="text" name="venue"><br>
<label>time</label><br><input type="text" name="time"><br>
<br>
<button type="submit" value="addGig" name="addGig">add gig</button>
</form>
You have ZERO error handling, and are simply assuming that your prepare could never fail. If you had error handling, you'd have been told about your syntax errors:
INSERT INTO gigs ('date', 'venue', 'time')
^----^--^-----^--^----^----
You've used the incorrect quotes. ' turns things into string literals. You cannot use string literals as identifiers in MySQL. Identifiers (table/field names) must either be bare words, or quoted with backticks. Since none of your field names are reserved words, backticks are not required. But either of the following would be acceptable
INSERT INTO gigs (`date`, `venue`, `time`)
INSERT INTO gigs (date, venue, time)
you have to edit your prepared statement into the right format:
the columns in your database shouldn't be escaped with '.
"INSERT INTO gigs (date, venue, time) ...
you can write the prepared statement like this (for better reading):
...VALUES (:date, :venue, :time)...
In your bindParam Method you can assign your variables like this:
$query->bindParam(':date' , $date);
Or you do it like in your query:
...VALUES (?, ?, ?)...
and then:
$query->bindParam(1 , $date);
try this:
$query = $connect->prepare("INSERT INTO gigs (date, venue, time) VALUES (:date, :venue, :time)");
$query->bindParam(':date' , $date);
$query->bindParam(':venue' , $venue);
$query->bindParam(':time' , $time);
$query->execute();
for more information consult the manual:
http://php.net/pdo.prepared-statements
There are a few issues here. (Now known after you posted your form code).
One of which is, that you are using <form> which defaults to GET when a method is not given. This in conjunction with your $_POST variables.
Therefore you need to give it a specific method, POST.
<form method="post">
Plus, without an action, defaults to self.
If you're using the form seperately from your SQL, you need to specify it.
I.e.:
<form method="post" action="handler.php">
Plus, you are/were using quotes for your columns. Remove them or using ticks.
Those aren't the right identifiers, as per your original question
https://stackoverflow.com/revisions/28091236/2
('date', 'venue', 'time')
http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
I'm totally new to php and mysql & need some help with this.
I want to insert a date into a mysql table, formatted as dd/mm/yyyy.
I have 4 columns in my table: id, name, age & birthday.
MY HTML-CODE
<form action="php_creat_cliente.php" method="post">
Name : <input name="reference" type="text" /><br />
Age : <input name="focode" type="text" /><br />
Birthday : <input name="date" type="text" /><br />
</form>
MY PHP-CODE
<?php
include('config.php');
$name=$_POST['name'];
$age=$_POST['age'];
$birthday=$_POST['birthday'];
$save=mysql_query("INSERT INTO loan (name, age, birthday) VALUES ('$name', '$age', '$birthday')");
header("location: index.html");
exit();
?>
Currently, the date is inserted in the mm/dd/yyyy format, but I need it in the dd/mm/yyyy format.
You have several ways, but the best if you are inserted as date or timestamp.
The first way is, if you store it in a varchar field, but in this case you can not use the mysql date functions.
Insert in regular way: YYYY-MM-DD
And, when you need it, you can use the mysql date functions to format it, or you can format it with php code also.
If you are assuming, your $_POST['birthday']; comes in mm-dd-yyyy format, then you should do something like this
//This varaible will come from the form, this is just a test now!
$_POST["birthday"] = 'mm-dd-yyyy';
$month = substr($_POST["birthday"], 0, 2);
$day = substr($_POST["birthday"], 3, 2);
$year = substr($_POST["birthday"], 6);
$birthday = $year . "-" . $month . "-" . $day;
$save = mysql_query("INSERT INTO loan (`name`, `age`, `birthday`) VALUES ('".$name."','".$age."','".$birthday."')");
MySQL accepts a string in the format of 'yyyy-mm-dd' or 'yyyymmdd' for dates. So you can enter it in the text field in whichever format you want as long as you make sure you reformat it (in your code) to a valid format (like the ones I mentioned) before passing it to the database.
Or you can specify the format yourself like so:
$save=mysql_query("INSERT INTO loan (name, age, birthday)
VALUES ('$name', '$age', STR_TO_DATE('$birthday', '%d-%m-%Y'))");
The jQuery UI Datepicker widget is popular for dates in forms.
As others have mentioned the current way you're doing this (at least the way shown here) is prone to SQL injection, XSS, CSRF, and everything in between. I'd advise you to learn about these attacks if you are to become a web developer.
EDIT:
What jQuery UI Datepicker helps with is picking a date and placing it in the text field in a valid date format. You can specify the format in which you want the widget to show your date like this:
$( "#datepicker" ).datepicker( "option", "dateFormat", "dd-mm-yy" );
And then you can make sure MySQL accepts the date format you're submitting in your insert command by specifying it like I showed above:
STR_TO_DATE('$birthday', '%d-%m-%Y')
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());
}