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());
}
Related
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']."')");
}
I'm trying to filter out repeated values entering into a MySQL table, by comparing the input PHP variable with the timestamp of an entry already present in the table and only if they don't match, the input PHP variable is entered into the table.
$user1_date = mysql_real_escape_string($user1_date); // the date variable
$user1_temp1 = mysql_real_escape_string($user1_temp1);
$user1_temp2 = mysql_real_escape_string($user1_temp2);
$user1_temp3 = mysql_real_escape_string($user1_temp3);
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date)); //Typecasting PHP variable into timestamp
$sql_check = "SELECT * FROM user_details WHERE temp_date ='$user1_date'";
$result_check = mysql_query($sql_check);
$num_rows_check = mysql_num_rows($result_check);
if ($num_rows_check == 0) // To check if there is no entry in the table with the same date and time as input PHP variable
{
$sql_insert = "INSERT INTO data_hour (user_id, temp1, temp_date, temp2, temp3)
VALUES (1,'$user1_temp1', '$user1_date', '$user1_temp2', '$user1_temp3')";
$result_insert = mysql_query($sql_insert);
}
temp_date is a column in the table of type timestamp. Even when the $user1_date is the same as the temp_date(timestamp) column for one of the entries in the table, it considers it as not equal and is inserting it into the table and hence I'm getting repeated values. I'm guessing the WHERE temp_date = '$user1_date'is not working properly. Some troubleshooting that I have done included
Changing '$user1_date' to just $user1_date in the WHERE
statement
Changing the WHERE clause as follows WHERE temp_date = (date)'$user1_date'
It will be great if somebody can help me out with this!
A nice easy solution would be giving temp_date a UNIQUE INDEX in your Mysql Table, as that would not allow the same value to be inserted twice. This would also make your operations more efficient, as you wouldn't have to do SELECT * every time you want to insert something.
However, for what you're doing, I think I see your problem; there are some quirks in your logic so I'll try to dispel them here. (Hopefully?) this will make your program cleaner and you'll be able to pinpoint the error, if not eliminate it altogether.
Examining this piece of code:
// $user1_date doesn't have a value here! //
$user1_date = mysql_real_escape_string($user1_date);
...
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
Error 1 - You escape the string before ever setting a value.
What you are doing is that you are using mysql_real_escape_string() before $user1_date is ever defined.
Correction:
// Getting better, but not done. //
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
...
$user1_date = mysql_real_escape_string($user1_date);
Error 2 - You do not give the date() function appropriate parameters
The date() function in PHP expects a timestamp, which is just an int. You can easily get the time with time(), so that should rectify your problem
Correction:
// You use strtotime($user1_date), but you should use time() //
$user1_date = date("Y-m-d H:i:s", time());
...
$user1_date = mysql_real_escape_string($user1_date);
These are small mistakes, but they can be deadly. Like I said, you should assign temp_date to a UNIQUE INDEX in your MySQL table, but make sure to correct these errors listed as well.
Let me know how it goes!
I have multiple fields with names that look like name_$i and I am trying to figure out a way to "on submit", send them all to the database. The thing is that the form is looped and the insert has to be able to adapt to the number of fields in the form. Is there a way to do this???
<?php
$fldcnt = $_POST['fldcnt'];
$i = $_POST['i'];
for ($i = 0; $i < $fldcnt; $i++){
$NAME = $_POST['name_$i'];
$AGE = $_POST['age_$i'];
$ADDRESS = $_POST['address_$i'];
$TELEPHONE = $_POST['telephone_$i'];
$EMAIL = $_POST['email_$i'];
$q_register_new_users = "insert into registration set
NAME = '$NAME',
AGE = '$AGE',
ADDRESS = '$ADDRESS',
TELEPHONE = '$TELEPHONE',
EMAIL = '$EMAIL'";
mysql_query($q_new_products,$connection) or die(mysql_error());
};
?>"
HTML and PHP
You can enter input fields into an array by simply calling the field name[]. Like so:
<input name="name[]" />
You can then use PHP to loop through the fields like so:
foreach($_POST['name'] as $key=>$value){
// Insert the value of the form field into a string or query
// i.e. build the query
$query .= $value;
}
// Then execute the query for each set of fields
The logic above is actually incorrect, but it should give you an idea of what I mean.
MySQL
Your SQL syntax is incorrect, the correct syntax for inserting into a MySQL database is:
INSERT INTO `table` (`field_1`, `field_2`)
VALUES ('value_1', 'value_2')
PLEASE NOTE
The use of the mysql_ functions is hugely discouraged due to there impending deprecation. Instead, most PHP programmers are now using the PDO / SQLite Classes. Whilst these might seem complex, they are actually pretty simple and offer a much more secure way of executing SQL statements.
PDO
SQLite
The syntax for INSERT statement should be like this,
INSERT INTO registration (NAME , AGE , ADDRESS, TELEPHONE, EMAIL)
VALUES ('$NAME', '$AGE', '$ADDRESS','$TELEPHONE', '$EMAIL')
but hte query above is vulnerable with SQL INJECTION, please read the article below to learn how to protect from it,
How can I prevent SQL injection in PHP?
If you are going to keep structure of your code, you need to use double quotes instead of apostrophes
$NAME = $_POST["name_$i"];
or put the variable out
$NAME = $_POST['name_'.$i];
Using array is best way to do this. But if you still want to go head with a counter then you could use
for($i = 0;isset($_POST["name_{$i}"]);$i++)
{
// name found
}
Please note that this code may not be optimal if the name_xx fields are coming from checkboxes, where a user selected items and skipped some in between.
PS. I posted this a comment but it is more suitable as an answer.
I am having an issue with a simple form uploading script.
On this upload script I built to upload data to a MySql database, I can't seem to get the record to insert into the database when I include this one variable.
I figured that perhaps I am overlooking some minor coding issue, and I'm working on a deadline to get this system live...
Here is the code snippit that is giving me issues.
$title=$_REQUEST['title'];
$author=$_REQUEST['author'];
$hours=$_REQUEST['hours'];
$start_d=$_REQUEST['start_d'];
$start_m=$_REQUEST['start_m'];
$start_y=$_REQUEST['start_y'];
$end_d=$_REQUEST['end_d'];
$end_m=$_REQUEST['end_m'];
$end_y=$_REQUEST['end_y'];
$certificate=$_REQUEST['certificate'];
$required=$_REQUEST['required'];
$assessment=$_REQUEST['assessment'];
$describe=$_REQUEST['description'];
$query=mysql_query("INSERT INTO `records` (title, hours, start_date_d, start_date_m, start_date_y , end_date_d, end_date_m, end_date_y , certificate, requirement, author, approved, assessment, describe) VALUES ('$title', '$hours', '$start_d', '$start_m', '$start_y', '$end_d', '$end_m', '$end_y', '$certificate', '$required', '$author', '0', '$assessment', '$describe')");
mysql_close();
The variable that is giving me issues is the one denoted as '$describe'.
My previous testing has indicated:
The form script is collecting data correctly
The form script is passing the data to the upload script correctly via method='post'
The database connection information is correct
All of the field names in the mysql query are typed correctly
Thank you in advance for your help.
Update:
echo mysql_error(); => "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' assessment, describe) VALUES' at line 1
this awful code should be totally rewritten.
but to solve this very problem
foreach ($_REQUEST as $key => $value) $_REQUEST[$key] = mysql_real_escape_string($value);
Something like this.
Note that i've changed date fields to date format.
$_POST['start_date'] = $_POST['start_y'].'-'.$_POST['start_m'].'-'.$_POST['start_d'];
$_POST['end_date'] = $_POST['end_y'].'-'.$_POST['end_m'].'-'.$_POST['end_d'];
$_POST['approved'] = 0;
$fields = explode(" ","title author hours start_date end_date certificate required assessment describe");
$query = "INSERT INTO `records` SET ".dbSet($fields);
mysql_query($query) or trigger_error(mysql_error().$query);
function dbSet($fields) {
$q='';
foreach ($fields as $v) $q.="`$v`='".mysql_real_escape_string($_POST[$v])."', ";
return trim($q,", ");
}
Try this:
$query="INSERT INTO `records` (title, hours, start_date_d, start_date_m, start_date_y , end_date_d, end_date_m, end_date_y , certificate, requirement, author, approved, assessment, describe) VALUES ('$title', '$hours', '$start_d', '$start_m', '$start_y', '$end_d', '$end_m', '$end_y', '$certificate', '$required', '$author', '0', '$assessment', '$describe')";
var_dump($query);
And post to us :)
It turns out that "Describe" is a reserved word in MySql.
I changed the field name, and now my script works...
I have a table in MySQL with "text", "date_posted", and "user". I currently query all text from user=Andy, and call those questions. All of the other text fields from other users are answers to the most recent question.
What I want is to associate those answers with the most recent question, with a loop similar to "for each text where user=Andy, find the text where user!=Andy until date>the next user=Andy (question)"
This seems awfully contrived, and I'm wondering if it can be done roughly as I've outlined, or if I can save myself some trouble in how I'm storing the data or something.
Thanks for any advice.
EDIT: I've added in the insert queries I've been using.
$url = "http://search.twitter.com/search.json?q=&ands=&phrase=&ors=¬s=RT%2C+%40&tag=andyasks&lang=all&from=amcafee&to=&ref=&near=&within=1000&units=mi&since=&until=&tude%5B%5D=%3F&rpp=50)";
$contents = file_get_contents($url);
$decode = json_decode($contents, true);
foreach($decode['results'] as $current) {
$query = "INSERT IGNORE INTO andyasks (questions, date, user) VALUES ('$current[text]','$current[created_at]','Andy')";
mysql_query($query);
}
$url2 = "http://search.twitter.com/search.json?q=&ands=&phrase=&ors=¬s=RT&tag=andyasks&lang=all&from=&to=amcafee&ref=&near=&within=15&units=mi&since=&until=&rpp=50";
$contents2 = file_get_contents($url2);
$decode2 = json_decode($contents2, true);
foreach($decode2['results'] as $current2) {
$query2 = "INSERT IGNORE INTO andyasks (questions, date, user) VALUES ('$current2[text]','$current2[created_at]','$current2[from_user]')";
mysql_query($query2);
}
And then on the SELECT side, this is where I am currently:
$results = mysql_query("SELECT * FROM andyasks");
$answers = mysql_query("SELECT * FROM andyasks WHERE 'user' != 'Andy'");
while($row = mysql_fetch_array($results))
{
if ($row['user'] == 'Andy') {
print(preg_replace($pattern, $replace, "<p>".$row["questions"]."</p>"));
}
}
while($row = mysql_fetch_array($answers))
{
print(preg_replace('/#amcafee/', '', "<p>".$row["questions"]."</p>"));
}
What you have in mind could, I believe, be done with subtle use of JOIN or nested SELECT, ORDER BY, LIMIT, etc, but, as you surmise, it would be "awfully contrived" and likely pretty slow.
As you suspect, you would save yourself a lot of trouble at SELECT time if you added a column to the table, which, for answers, has the primary key of the question they're answering (that could be easily obtained at INSERT time, since it's the latest entry with user equal Alex). Then the retrieval would be easier!
If you can alter your schema this way, but need help with the SQL, pls comment or edit your answer to indicate that and I'll be happy to follow up (similarly, I'd be happy to follow up if you're stuck with this schema and need the "awfully contrived" SQL -- I just don't know which of the two possibilities applies!-).
Edit: since the schema's changed, the INSERT could be (using form :name to indicate parameters you should bind):
INSERT IGNORE INTO andyasks
(questions, date, user, answering)
SELECT :text, :created_at, :from_user,
IF(:from_user='Andy', NULL, aa.id)
FROM andyasks AS aa
WHERE user='Andy'
ORDER BY date DESC
LIMIT 1
i.e.: use INSERT INTO ... SELECT' to do a query-within-insertion, which picks the latest post by Andy. I'm assuming you do also have a primary keyid` that's auto-increment, which is the normal arrangement of things.
Later to get all answers to a given question, you only need to select rows whose answering attribute equals that question's id.
If I understand you correctly you want something like:
$myArr = array("bob","joe","jennifer","mary");
while ($something = next($myArr)) {
if ($nextone = next($myArr)) {
//do Something
prev($myArr)
}
}
see http://jp2.php.net/next as well as the sections on prev, reset and current