I'm trying t开发者_如何学编程o post the date and time at the time I create a new record. The record is created but the 'add_time' column is blank in mySQL.
What's wrong with it?
$date = date("Y-m-d G:i:s") ;
$order = "INSERT INTO cartons_added (add_time, type, part_no, add_type, add_qty,
add_ref, add_by, add_notes)
VALUES
('$_POST[date]',
'$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]')";
$result = mysql_query($order);
You're never using the $date
variable you created. You probably meant to use that instead of $_POST[date]
.
I believe instead of:
VALUES
('$_POST[date]',
'$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]')";
You mean to use
// Use your $date variable
VALUES
('$date',
'$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]')";
All of this needs a great deal of treatment for protection against SQL injection. The easiest path to take is to surround all $_POST
vars in mysql_real_escape_string()
:
"...
VALUES
('$date',
'" . mysql_real_escape_string($_POST['type']) ."',
'" . mysql_real_escape_string($_POST['part_no']) ."',
'" . mysql_real_escape_string($_POST['add_type']) ."',
'" . mysql_real_escape_string($_POST['add_qty']) ."',
'" . mysql_real_escape_string($_POST['add_ref']) ."',
'" . mysql_real_escape_string($_POST['add_by']) ."',
'" . mysql_real_escape_string($_POST['add_notes']) ."')";
Try this:
date('Y-m-d H:i:s');
You have to fix that SQL-injection hole:
There's also a syntax error, it's not $_POST[add_ref]
, but $_POST['add_ref']
You can write '$_POST[name]'
(bad) instead of $_POST['name']
, (good) but don't it's bad practice.
Change the code to:
$query = "INSERT INTO cartons_added (add_time, type, part_no, add_type, add_qty,
add_ref, add_by, add_notes)
VALUES
('$date',
'{mysql_real_escape_string($_POST['type'])}',
'{mysql_real_escape_string($_POST['part_no'])}',
'{mysql_real_escape_string($_POST['add_type'])}',
'{mysql_real_escape_string($_POST['add_qty'])}',
'{mysql_real_escape_string($_POST['add_ref'])}',
'{mysql_real_escape_string($_POST['add_by'])}',
'{mysql_real_escape_string($_POST['add_notes'])}') ";
Never ever ever insert a $_POST
, $_GET
, $_SESSION
and alike stuff directly into a query.
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
精彩评论