I'm looking to run a mysql_query() that allows me to create a new table within a database and name it according to the current date and time.
Example: Create a table named 2012-01-09-03-00-00, or something along those lines.
I know that this is not an optimal way of doing things, but ultimately I'm going to take the data on this table and dump it into a bigger database.
I've tried the code:
<?php
$date = date('YmdHis', time()-(3600*5));
$exportSQL = "CREATE TABLE $date(
FirstName varchar(15)
)";
mysql_select_db($database);
mysql_query($exportSQL) or die (mysql_error());
echo "Table created!";
?>
But this has been to no good. Please Help and thanks in advance.
EDIT: THIS HAS BEEN SOLVED. THE CODE WORKING SHOULD LOOK LIKE THIS:
<?php
$date = date('YmdHis', time()-(3600*5));
$exportSQL = "CREATE TABLE `$date`(
FirstName varchar(15)
)";
mysql_select_db($database);
mysql_query($exportSQL) or die (mysql_error());
echo "Table created!";
?>
Except that it is very weird design, if you want to name table in such a way - place its name in square brackets, like this:
CREATE TABLE [2012-01-09 12:20:15.010] (your columns)
that means that you should have the name of the table BEFORE composing the query, OR you have to use dynamic sql like this:
DECLARE #sql NVARCHAR(MAX)
SET #sql = N'CREATE TABLE['+
CAST(DATEPART(year, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(month, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(day, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(hour, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(minute, GETDATE()) AS NVARCHAR)+N'-'+
CAST(DATEPART(second, GETDATE()) AS NVARCHAR)+
N'] (FirstName varchar(15))'
EXEC(#sql)
The presented syntax is for sql server, so due to the sql compliance you can replace square brackets with double quotes and use proper date functions, but the approach left just the same
Related
I am struggling trying to update a row in an Azure SQL database.
What I am trying to do is to update a row with some input variables along with a fresh datestamp.
If I input the following (for test purposes), my database is updated, but the date is way off:
"UPDATE TABLENAME set COL1 = ".$_POST[VAL1].", COL2 = ".$_POST[VAL2].", COL3 = 2020-03-20 WHERE COL0 = 'VAL0'"
giving me a datestamp looking like this: 1905-06-21T00:00:00.0000000
I have been trying just around a hundred ways of formatting the date() variable, putting it in my SQL statement like this:
"UPDATE TABLENAME set COL1 = ".$_POST[VAL1].", COL2 = ".$_POST[VAL2].", COL3 = ".date()." WHERE COL0 = 'VAL0'"
Needless to say, COL3 is my datestamp column. But I cannot get the database to accept my datestamp formatting. I have tried YYYY-mm-dd xyz1234 in countless variants inside date(), but to no avail.
The database has the following collation set: SQL_Latin1_General_CP1_CI_AS.
Any pointers?
First, about your incorrect date value. It is correct, because when you miss '' around 2020-03-20, SQL Server makes implicit data type conversion. Next example demonstrates this:
Implicit conversion:
DECLARE #date datetime
SELECT #date = 2020-03-20
SELECT #date
SELECT DATEADD(day, 2020-03-20, 0)
Output:
1905-06-21 00:00:00.000
Second, if you want to pass date and time values, just use appropriate format - 'yyyy-MM-dd', 'yyyyMMdd hh:nn:ss' or 'yyyy-MM-ddThh:nn:ss':
"UPDATE TABLENAME set COL1 = ".$_POST[VAL1].", COL2 = ".$_POST[VAL2].", COL3 = '2020-03-20' WHERE COL0 = 'VAL0'"
I don't know how you make your connection to SQL Server, but try to use prepared statements.
Update (Retrieve and send date and time values from and to SQL Server):
Based on driver that you use to connect to SQL Server, you may retrieve date and time values as text or as PHP datetime object (if you use PHP Driver for SQL Server), but you need to send these values as text. In your case values are returned as text. So you need to generate universal datetime value (in 'yyyy-MM-ddThh:nn:ss' for example) as text.
Next example shows some valid and invalid combinations for UPDATE T-SQL statement for your datetime column. It is tested with PHP Driver for SQL Server 4.0.3.
<?php
# Value from database as text
$row['COL3'] = '2019-03-29T11:35:30.0000000';
# Valid statement
$tsql = "UPDATE TABLENAME SET COL3 = '".substr($row['COL3'], 0, 19)."' ";
# Valid statement - date("Y-m-d\Th:i:s") will return current datetime
$tsql = "UPDATE TABLENAME SET COL3 = '".date("Y-m-d\Th:i:s")."' ";
# Invalid statement - date("d-m-Y h:i:s", $row['COL3']) expects int as second parameter,
# generates warning and returns '01-01-1970 12:33:39' as result
$tsql = "UPDATE TABLENAME SET COL3 = '".date("d-m-Y h:i:s", $row['COL3'])."' ";
?>
How to get the next id in mysql to insert it in the table
INSERT INTO payments (date, item, method, payment_code)
VALUES (NOW(), '1 Month', 'paypal', CONCAT("sahf4d2fdd45", id))
You can use
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'table_name'
AND table_schema = DATABASE( ) ;
or if you do not wish to use information_schema you can use this
SHOW TABLE STATUS LIKE 'table_name'
You can get the next auto-increment value by doing:
SHOW TABLE STATUS FROM tablename LIKE Auto_increment
/*or*/
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = 'tablename'
Note that you should not use this to alter the table, use an auto_increment column to do that automatically instead.
The problem is that last_insert_id() is retrospective and can thus be guaranteed within the current connection.
This baby is prospective and is therefore not unique per connection and cannot be relied upon.
Only in a single connection database would it work, but single connection databases today have a habit of becoming multiple connection databases tomorrow.
See: SHOW TABLE STATUS
This will return auto increment value for the MySQL database and I didn't check with other databases. Please note that if you are using any other database, the query syntax may be different.
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'your_table_name'
and table_schema = 'your_database_name';
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'your_table_name'
and table_schema = database();
The top answer uses PHP MySQL_ for a solution, thought I would share an updated PHP MySQLi_ solution for achieving this. There is no error output in this exmaple!
$db = new mysqli('localhost', 'user', 'pass', 'database');
$sql = "SHOW TABLE STATUS LIKE 'table'";
$result=$db->query($sql);
$row = $result->fetch_assoc();
echo $row['Auto_increment'];
Kicks out the next Auto increment coming up in a table.
In PHP you can try this:
$query = mysql_query("SELECT MAX(id) FROM `your_table_name`");
$results = mysql_fetch_array($query);
$cur_auto_id = $results['MAX(id)'] + 1;
OR
$result = mysql_query("SHOW TABLE STATUS WHERE `Name` = 'your_table_name'");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
Use LAST_INSERT_ID() from your SQL query.
Or
You can also use mysql_insert_id() to get it using PHP.
Solution:
CREATE TRIGGER `IdTrigger` BEFORE INSERT ON `payments`
FOR EACH ROW
BEGIN
SELECT AUTO_INCREMENT Into #xId
FROM information_schema.tables
WHERE
Table_SCHEMA ="DataBaseName" AND
table_name = "payments";
SET NEW.`payment_code` = CONCAT("sahf4d2fdd45",#xId);
END;
"DataBaseName" is the name of our Data Base
Simple query would do
SHOW TABLE STATUS LIKE 'table_name'
For MySQL 8 use SHOW CREATE TABLE to retrieve the next autoincrement insert id:
SHOW CREATE TABLE mysql.time_zone
Result:
CREATE TABLE `time_zone` (
`Time_zone_id` int unsigned NOT NULL AUTO_INCREMENT,
`Use_leap_seconds` enum('Y','N') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'N',
PRIMARY KEY (`Time_zone_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1784 DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 ROW_FORMAT=DYNAMIC COMMENT='Time zones'
See the AUTO_INCREMENT=1784 at the last line of returned query.
Compare with the last value inserted:
select max(Time_zone_id) from mysql.time_zone
Result:
+-------------------+
| max(Time_zone_id) |
+-------------------+
| 1783 |
+-------------------+
Tested on MySQL v8.0.20.
SELECT id FROM `table` ORDER BY id DESC LIMIT 1
Although I doubt in its productiveness but it's 100% reliable
You have to connect to MySQL and select a database before you can do this
$table_name = "myTable";
$query = mysql_query("SHOW TABLE STATUS WHERE name='$table_name'");
$row = mysql_fetch_array($query);
$next_inc_value = $row["AUTO_INCREMENT"];
I suggest to rethink what you are doing. I never experienced one single use case where that special knowledge is required. The next id is a very special implementation detail and I wouldn't count on getting it is ACID safe.
Make one simple transaction which updates your inserted row with the last id:
BEGIN;
INSERT INTO payments (date, item, method)
VALUES (NOW(), '1 Month', 'paypal');
UPDATE payments SET payment_code = CONCAT("sahf4d2fdd45", LAST_INSERT_ID())
WHERE id = LAST_INSERT_ID();
COMMIT;
You can't use the ID while inserting, neither do you need it. MySQL does not even know the ID when you are inserting that record. You could just save "sahf4d2fdd45" in the payment_code table and use id and payment_code later on.
If you really need your payment_code to have the ID in it then UPDATE the row after the insert to add the ID.
What do you need the next incremental ID for?
MySQL only allows one auto-increment field per table and it must also be the primary key to guarantee uniqueness.
Note that when you get the next insert ID it may not be available when you use it since the value you have is only within the scope of that transaction. Therefore depending on the load on your database, that value may be already used by the time the next request comes in.
I would suggest that you review your design to ensure that you do not need to know which auto-increment value to assign next
use "mysql_insert_id()". mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.
Below are the example of use:
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable VALUES('','value')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
I hope above example is useful.
If return no correct AUTO_INCREMENT, try it:
ANALYZE TABLE `my_table`;
SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE (TABLE_NAME = 'my_table');
This clear cache for table, in BD
using the answer of ravi404:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
using in your insert query, to create a SHA1 Hash. ex.:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( getAutoincrementalNextval ('document') ),
'Title',
'Body'
);
Improvement of #ravi404, in case your autoincrement offset IS NOT 1 :
SELECT (`auto_increment`-1) + IFNULL(##auto_increment_offset,1)
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = your_table_name
AND table_schema = DATABASE( );
(auto_increment-1) : db engine seems to alwaus consider an offset of 1. So you need to ditch this assumption, then add the optional value of ##auto_increment_offset, or default to 1 : IFNULL(##auto_increment_offset,1)
For me it works, and looks simple:
$auto_inc_db = mysql_query("SELECT * FROM my_table_name ORDER BY id ASC ");
while($auto_inc_result = mysql_fetch_array($auto_inc_db))
{
$last_id = $auto_inc_result['id'];
}
$next_id = ($last_id+1);
echo $next_id;//this is the new id, if auto increment is on
SELECT AUTO_INCREMENT AS next_id FROM information_schema.tables WHERE table_name = 'table name' AND table_schema = 'database name of table name'
mysql_insert_id();
That's it :)
I have an issue where I can only insert data into my table once. If i delete the row and insert a new one, it works but if I already have a row and try to insert another one, it doesn't work. No errors in the console or network.
I'm inserting with this:
<?php
error_reporting(E_ALL);
include 'DB.php';
$con = mysql_connect($host,$user,$pass)
or die("Error: ".mysql_error());
$dbs = mysql_select_db($databaseName, $con);
$name = mysql_real_escape_string($_POST['name']);
$date = date('Y-m-d');
$amount = $_POST['amount'];
$timPaid = $_POST['timPaid'];
$rennyPaid = $_POST['rennyPaid'];
$sql = "INSERT INTO $tableName (`name`, `date`, `amount`, `timpaid`, `rennypaid`)
VALUES ('$name', '$date', '$amount', '$timPaid', '$rennyPaid')";
$result = mysql_query($sql, $con)
or die("Error: ".mysql_error());
mysql_close($con);
?>
I'm thinking it might have to do with how my table is set up, primary key and such. I have an id column which is the primary and I think it's auto-increment, can't tell.
Since you are not sure about whether the id field is auto-increment or not, you should alter your table like this,
ALTER TABLE `yourtable`
MODIFY COLUMN `id` int(11) NULL AUTO_INCREMENT FIRST;
the result FROM SHOW CREATE TABLE tableName would help.
I would guess you have a unique index on on of your fields and you are trying to insert a second record with the same value.
Also CHECK TABLE tablename could help identify the problem.
I had this... I had set my first column as 'unique' and my 'Insert' didn't involve that column.
As a result the 'Insert' added a value of zero into the 'Unique' column (I'd set that column to 'integer').
When I did another insert 'I THINK' that the 'Insert' wanted to add another zero in the 'Unique' column that I wasn't 'Inserting' into, so it tried to 'Insert' another zero, BUT because that column was 'unique' it wouldn't allow another zero and refused the 'Insert'.
I proved this by changing the first 'Inserts' entry into the 'Unique' column manually to another 'Integer' then the 'Insert; statement worked one more time.... repeat process above as described and my table allowed another 'Insert'.
Hope this makes sense and helps?.
I had a similar problem, however mine was where I was using the INT data type in my create table script for storing a 13-digit long number, and it only wanted to accept something 10-digits in size. Changing this to a VARCHAR(13) fixed the problem for me.
Well I have a task to store "quotes" into a database (Already done this) and display them & sort them out for the most recent quotes. I'm assuming to get the "most recent", I'd need to store date/time of the submitted quote.
I am new to PHP and trying to learn, so I don't know how to exactly do this.
Here is the PHP for adding the quotes to the database. There are two columns in the table called "quotes" and "id". I'm guessing I will also need to make a column for the date too?
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
How would I also insert the date?
use CURDATE() if you want to insert the current date
example:
$query_auto = "INSERT INTO tablename (col_name, col_date) VALUE ('DATE: Auto CURDATE()', CURDATE() )";
but if you wqant it manually then should use this:
$query_manual = "INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2008-07-04')";
UPDATE
CREATE TABLE auto_ins
(
`MySQL_Function` VARCHAR(30),
`DateTime` DATETIME,
`Date` DATE,
`Time` TIME,
`Year` YEAR,
`TimeStamp` TIMESTAMP
);
INSERT INTO auto_ins
(`MySQL_Function`, `DateTime`, `Date`, `Time`, `Year`, `TimeStamp`)
VALUES
(“CURDATE()”, CURDATE(), CURDATE(), CURDATE(), CURDATE(), CURDATE());
If you only want the most recent quotes, you can simply sort your result set by their id DESC assuming the id is an auto-incremented value.
Yes, you need a third column lets say most_recent (defined as date or datetime) :
mysql_query("INSERT INTO entries (quote, most_recent) VALUES('$quotes', now())")
You will need at least couple of tables who submitted the quote and the quote table itself.
create table users(id int primary key not null, username varchar(32),pwd varchar(32));
you can add any info to that table like email address and so on.
create table quotes (
id int not null ,
user_id integer,
quote_text varchar(256),
inserted_date timestamp default current_timestamp ,primary key (id));
alter table quotes add constraint fk_users foreign key(user_id) references users(id);
Otherwise feel free to modify them.
It's not about php here its about DB design in general.
Use this code:
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = now().' - '.mysql_real_escape_string($quote);
// THIS WILL ADD THE DATE AND TIME TO YOUR $quotes STRING.
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
i found an old blog script (very old) kicking around on my PC. im having troubles with fetching the date and time from my DB to display in PHP. Can someone help me.
This is my MySQL DB setup.
CREATE TABLE blog_posts (
id int(11) NOT NULL auto_increment,
title varchar(30) NOT NULL default '',
news text NOT NULL,
poster varchar(15) NOT NULL default '',
date timestamp(14) NOT NULL,
PRIMARY KEY (id)
) TYPE=MyISAM;
And this is what im using to send a post:
<?php
include "db.php";
$title=$_POST['title'];
$news=$_POST['news'];
$poster=$_POST['poster'];
$query="INSERT INTO $blogposts (title, news, poster) VALUES ('$title', '$news', '$poster')";
$result=mysql_query($query) or die (mysql_error());
mysql_close();
header("Location: post.php");
?>
And finally this is what im using to call the date on the front-end:
<?php echo "posted on: - ".$day.".".$month.".".$year." at ".$hour.":".$min; ?>
I'm no expert (clearly) but the call for the date doesnt look right to me. Anyone have any ideas on how i could make it work, or even make it better??
EDIT::
<?php
include "db.php";
//query
$query="SELECT * FROM ".$blogposts." ORDER BY id DESC LIMIT 0,$limit ";
$result=mysql_query($query) or die (mysql_error());
//loop
while($row=mysql_fetch_array($result))
{
$querycomment = "SELECT ID FROM ".$newscomments." WHERE newsid=".$row['id'];
$resultcomment=mysql_query($querycomment) or die (mysql_error());
$num_rows = mysql_num_rows($resultcomment);
ereg("^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})",$row['date'],$res);
$year=$res[1];
$month=$res[2];
$day=$res[3];
$hour=$res[4];
$min=$res[5];
$sec=$res[6];
?>
Thanks
As date column has TIMESTAMP data type and got not null constraint so it will have default current_timestamp value if no data posted on date column while inserting. see mysql timestamp ref manual.
So to achieve a result that you ask you can try fetch that data by using code like this:
$sql = "select id, title, news, poster, DATE_FORMAT(date,'%d.%m.%Y at %k:%i') as posteddate from blog_posts";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row["title"]."<br/>";
echo "By : " . $row["poster"]."<br/>";
echo "posted on: - " . $row["posteddate"]."<br/>"; //"posted on: - 03.03.2011 at 7:35"
}
You don't seem to be adding any value to the date field in your insert command. You could use now() to add the current time stamp to add the current time during the insert. To extract the time you could either (a) read the date field from the table and format the time using PHP or (b) get formatted fields of the time stamp in the select command using the mysql date and time functions
You also need to have some code to read the values in your PHP to read the values for the fields. This seems to be missing in your question.
Surely you haven't defined any of the date variables, that you're trying to use?