I have tried to insert the current date using the now() syntax but it's not working. The column in MySQL is under datetime called date_added but when I check the command prompt all I get is 0000-00-00 00:00:00.
INSERT INTO FOOD (food_name, food_type, total, available, date_added)
VALUES
('$_POST[food_name]','$_POST[food_type]','$_POST[total]','$_POST[available]','NOW()')";
You need to remove the single quotes from NOW():
...
VALUES (
$_POST[food_name],
$_POST[food_type],
$_POST[total],
$_POST[available],
NOW())";
Remove the quotes around NOW(), in that way NOW() is treated as a SQL function instead of a string.
VALUES ('$_POST[food_name]','$_POST[food_type]','$_POST[total]','$_POST[available]',NOW())";
Try if the following option works:
GETDATE()
offtopic:
Is this possible with the array? Never gave it a shot:
$food= array('apple', 'Banana', 'Pineapple');
INSERT INTO food ('fruit_arrays') VALUES ($food)
Related
Code below adds date in correct format but hours/minutes/seconds are inserted as 00:00:00.
$timestamp[] = 'date("2017-12-31 21:01:50")';
$i because I have this inside a a loop.
$sql = "INSERT INTO posts (post_id, username, content, timestamp, likes)
VALUES ('$post_id[$i]', '$username[$i]', '$content[$i]', $timestamp[$i],
'$likes[$i]')";
Result:
MySQL's date function returns a date without a time portion, which is why it's getting truncated to midnight.
You should be able to ignore the call to date entirely, and just pass the raw string - it's already in a format that MySQL will understand:
$timestamp[] = '2017-12-31 21:01:50';
$sql = "INSERT INTO posts (post_id, username, content, timestamp, likes)
VALUES ('$post_id[$i]', '$username[$i]', '$content[$i]', '$timestamp[$i]', '$likes[$i]')";
(Note the added quotes around the $timestamp variable)
You should also look into using prepared statements, rather than building up your SQL string manually. It'd be both a security and readability benefit.
I have the following date input box in an HTML code:
<input type="date" name="DOB" size="20">
The form data are passed to a different PHP file using the POST method. And there the date is saved to a variable.
$DOB=$_POST['DOB'];
When I echo this variable it prints the date value saved in it. However if I use this variable in a query, the value won't be read. The query does not return any values.
This is my query:
"SELECT site_no, name,NIC,gender,address,telephone FROM employee WHERE emp_no=$emp_no AND DOB=$DOB"
Try this
use single quotes with date(assumption you got date value in $DOB variable )
"SELECT site_no, name,NIC,gender,address,telephone FROM employee WHERE emp_no=$emp_no AND DOB='$DOB'"
EDIT
MySQL expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'
You need to enclose variables in single quotes. Use the code below
"SELECT site_no, name,NIC,gender,address,telephone FROM employee WHERE emp_no='$emp_no' AND DOB='$DOB'"
Hope this helps you
For visibility it's good practice to add quotes to your SQL. It's important to know what types you're working with and to escape the values, especially with something like this.
Your query with quotes and indentation for visibility:
SELECT
`site_no`, `name`, `NIC`, `gender`, `address`, `telephone`
FROM
`employee`
WHERE
`emp_no` = '$emp_no'
AND
`DOB` = '$DOB'
Best practice to save dates is either using DATE/DATETIME or timestamps. You'll want to verify the DOB format and input, strip unnecessary characters etc. Look up real_escape_string, time and date for PHP
Use single quotes for $DOB
"SELECT site_no, name,NIC,gender,address,telephone FROM employee WHERE emp_no=$emp_no AND DOB='$DOB'"
I'm using the p4a application framework, i need to insert rows into my database via fields that i have made previously, when the user presses submit, the database should update and thus other new rows should be able to to made etc.
I'm struggling to find how to input the data into the database, i can easily do it through putting the values into the sql statement but this is completely alien to me,
The code is:
public function submit()
{
$location = $this->location->getNewValue();
$date = $this->date->getNewValue();
$merono = $this->merono->getNewValue();
$sql = $db->query("INSERT INTO 'meetingrooms'(location, date, merono)
VALUES
($location, $date, $merono)");
p4a_db::singleton()->newRow($sql, array($location));
$this->load();
location, date and merono are all set in the fields i have created before this function and it should work as i have previously done the same for a login page, so i know the first section should be getting the variables. and as i have accessed the db previously i know that it is connecting, so it must be to do with the MySQL statement.
Thanks,
Steve.
on your query, i found out that you are enclosing the table name with single quote, if you want to escape tableName or columnName use backtick instead,
INSERT INTO `meetingrooms`(location, date, merono)
VALUES ($location, $date, $merono)
but since your tableName is not a reserved word or contains any invalid characters, you can get rid of the backtick.
If you are inserting values on the table which are not numeric, wrap it with single quotes,
INSERT INTO meetingrooms (location, date, merono)
VALUES ('$location', '$date', '$merono')
I finally managed to figure it out (even though this question was only active for a few mins XD)
the SQL statement was wrong for a start (Thanks to John Woo for the help (y)) now the statement goes:
query("INSERT INTO meetingrooms(location, date, merono)
VALUES
('$location', '$date', '$merono')");
this successful statement allows for the variables placed into $location $date and $merono to be inserted into the table plus the extra addition to the start of the statement
goes as:
p4a_db::singleton()->
this calls the P4A database extension which in this pop-up class i have made, is not accessible,
so the full function now goes:-
public function submit()
{
$location = $this->AreaName->getNewValue();
$date = $this->date->getNewValue();
$merono = $this->merono->getNewValue();
p4a_db::singleton()->query("INSERT INTO meetingrooms(location, date, merono)
VALUES
('$location', '$date', '$merono')");
Thanks for the help,
Steve.
I'm new to PHP and MySQL query construction. I have a processor for a large form. A few fields are required, most fields are user optional. In my case, the HTML ids and the MySQL column names are identical. I've found tutorials about using arrays to convert $_POST into the fields and values for INSERT INTO, but I can't get them working - after many hours. I've stepped back to make a very simple INSERT using arrays and variables, but I'm still stumped. The following line works and INSERTs 5 items into a database with over 100 columns. The first 4 items are strings, the 5th item, monthlyRental is an integer.
$query = "INSERT INTO `$table` (country, stateProvince, city3, city3Geocode, monthlyRental) VALUES ( '$country', '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental')";
When I make an array for the fields and use it, as follows:
$colsx = array('country,', 'stateProvince,', 'city3,', 'city3Geocode,', 'monthlyRental');
$query = "INSERT INTO `$table` ('$colsx') VALUES ( '$country', '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental')";
I get a MySQL error - check the manual that corresponds to your MySQL server version for the right syntax to use near ''Array') VALUES ( 'US', 'New York', 'Fairport, Monroe County, New York', '(43.09)' at line 1. I get this error whether the array items have commas inside the single quotes or not. I've done a lot of reading and tried many combinations and I can't get it. I want to see the proper syntax on a small scale before I go back to foreach expressions to process $_POST and both the fields and values are arrays. And yes, I know I should use mysql_real_escape_string, but that is an easy later step in the foreach. Lastly, some clues about the syntax for an array of values would be helpful, particularly if it is different from the fields array. I know I need to add a null as the first array item to trigger the MySQL autoincrement id. What else?
I'm pretty new, so please be specific.
$query = "INSERT INTO `$table` ('$colsx') etc...
isn't going to work. $colsx is an array, so what you're going to end up producing is literally
$query = "INSERT INTO `sometable` ('Array')
^^^^^---yes, it'll literally say "Array"
You'll have to preprocess the array into a string before doing this, e.g.
$colsx = array(...);
$col_string = implode(',', $colsx);
$query = "INSERT INTO `$table` ($col_string) etc...";
I need help on a method of inserting values into a single column on different rows.
Right now, I have an imploded array that gives me a value such as this:
('12', '13', '14')
Those numbers are the new IDs of which I wish to insert into the DB.
The code I used to implode the array is this:
$combi = "('".implode("', '",$box)."')"; // Where $box is the initial array
The query of which I plan to use gets stuck here:
mysql_query("INSERT INTO studentcoursedetails (studentID) VALUES
One option would be to repeat this, but I cant, because the array will loop; there might be 3 IDs, there might be 20.
A loop doesn't seem right. Any help would be appreciated.
For inserting more than one value into a table you should use (value1), (value2) syntax:
$combi = "('".implode("'), ('",$box)."')";
PS: This feature is called row value constructors and is available since SQL-92
Can you not do something like this:
for($x = 0; $x < count($box); $x++)
{
mysql_query("INSERT INTO studentcoursedetails (studentID) VALUES ($box[$x]);
}
This will work directly on your array, insert a new row for each value in $box and also prevent the need to implode the array to a comma delimited string
Storing ids as a comma delimited string might initially seem like a simple model but in the long term this will cause you no end of trouble when trying to work with a non-normalised database.
Some flavors of sql allow compound inserts:
insert into studentcoursedetails (studentid) values
(1),
(2),
(3),
If you are using MySQL, you can insert multiple values in a single sentence:
sql> insert into studentcoursedetails (studentID)
> values (('12'), ('13'), ('14'));
So, you just need to build that string in PHP and you are done.
You can still create the statement via implode. Just don't use VALUES; use SELECT instead
$combi = " ".implode(" UNION ALL SELECT ",$box)." "; // Where $box is the initial array
mysql_query("INSERT INTO studentcoursedetails (studentID) SELECT " . $combi)
The SELECT .. union is portable across many dbms.
Note on the IDs - if they are numbers, don't quote them.
Check to see if there is a variant of the mysql_query function that will operate on an array parameter.