Say I have a table name auto_parts with these fields.
id, part, price, timestamp
and I insert a new row via php as so:
$query = "insert into auto_parts(id, part, price, timestamp)
values(1, 'axle', 200)"
mysql_query($query);
will that automatically add the timestamp.
Or do I have to insert a value for timestamp myself?
What you need to do is declare timestamp to be of type in your sql
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
and modify the query to
$query = "insert into auto_parts(id, part, price)
values(1, 'axle', 200)"
mysql_query($query);
$query = "insert into auto_parts(id, part, price, timestamp)
values(1, 'axle', 200, 'NOW()')"
mysql_query($query);
Do it in SQL itself instead of passing it ... its more efficient ... This is the corresponding post:
Auto TimeStamp new entry to DB (phpMyAdmin)
I know there are already answers to this question so I am kind of combining all answers and explaining a little bit.
There may be two ways to do this,
Change your table and make timestamp column to default CURRENT_TIMESTAMP
ALTER TABLE tablename MODIFY timestamp TIMESTAMP NOT NULL DEFAULT
CURRENT_TIMESTAMP
and modify your query like this, timestamp will be inserted automatically
$query = "insert into auto_parts(id, part, price) values(1, 'axle',
200)"; mysql_query($query);
If you have more than one timestamp table then you can make one as current timestamp and for other one use like this
ALTER TABLE tablename MODIFY timestamp TIMESTAMP NOT NULL
and modify your query like this
$query = "insert into auto_parts(id, part, price, timestamp) values (1, 'axle', 200, now())"; mysql_query($query);
Related
I am new to SQL Server. I have created a script where I import data and insert into SQL Server. The update query works fine but the insert query does not . I get a error
Error converting data type varchar to float.. INSERT INTO dbo.
This is the code
$amount = trim(str_replace('$','',$data[2]));
// echo ($amount); // prints 1,000,000.00
// INSERT QUERY
//Try 1 : Fails
$Query = "INSERT INTO dbo.testtable (id, name, amount)
values ( 11, 'John' , $amount )";
//Try 2 : Fails
$Query = "INSERT INTO dbo.testtable (id, name, amount)
values ( 11, 'John' , CONVERT(FLOAT,'$amount') )";
How in the world can I insert a proper float value from the variable ($amount) into SQL Server?
use this:
cast('$amount' as money)
Updates:
It actually depends on what's the type of your column amount. If it's varchar, it should not throw an error for 1st line. So, I guess it's something like decimal(18, 2). Refer to the demo here
declare #amount varchar(25)
SET #amount = '1,000.00'
create table #tmp_money (amount FLOAT)
insert into #tmp_money
SELECT cast(#amount as money)
select * from #tmp_money
I am wondering how to store the value of a primary key, auto-incremented by "DEFAULT" so that I can insert it as a value in another table row.
So far I have:
$sql = "INSERT INTO sales (
sale_id,
sale_amt,
sale_date)
VALUES (
DEFAULT, # <--- how to store the resulting value of this?
'$amt',
'$date'
)";
I need the specific value created by "DEFAULT" to be stored, so that I can insert it into another table's row. How do I do this with either PHP or MySQL?
You don't. You use last_insert_id() to retrieve it AFTER you've performed the first insert.
INSERT INTO foo (bar) VALUES (baz)
SELECT #id := last_insert_id();
INSERT INTO other (id, parent) VALUES (null, #id)
INSERT INTO yetanother (id, parent) VALUES (null, #id)
Note that last_insert_id() is not smart and will return the id of the LAST insert you did. If you do two inserts, and then try to get the ids, you'll get the id of the second (last) insert.
MySQL:
You can find this in MySQL by using the LAST_INSERT_ID() function, as the last insert ID will be returned that you inserted for an AUTO_INCREMENT value.
$sql = "INSERT INTO sales (
sale_id,
sale_amt,
sale_date)
VALUES (
DEFAULT, # <--- how to store the resulting value of this?
'$amt',
'$date'
)";
sql2 = "INSERT INTO records (
sale_id,
customer_name,
other_info)
VALUES (
LAST_INSERT_ID(), <-------- correct sales_id
'$name',
'$info');
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'm pulling data from a calendar feed and each event in the calendar has a unique $EventID string. I'm using PHP.
I have a SQL database with an Event_ID column. These IDs are strings. I need to be able to compare my $EventID against the Event_ID column and put in in the database if it's not there.
I have a primary key set up to auto increment in the database, and I was thinking I can set up a loop to increment through those and compare each to the $EventID, but I'm wondering if there is a better way-maybe a PHP function I don't know about?
I've got a whole lot of code, but basically I've got:
<?php
$EventID = $event->id; //This is the event ID
mysql_query("INSERT INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
?>
So how do I set up a conditional to check all the Event_IDs that are already in the database against the $EventID?
$query = "SELECT * FROM `myTable` WHERE `Event_ID`='$EventID' ";
$result = mysql_query($query);
if (!mysql_num_rows($result))
// INSERT QUERY
Check if the Event ID is present, If not insert it
You could just skip the "Select" query and do an "INSERT IGNORE" instead:
mysql_query("INSERT IGNORE INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
this will leave existing Event_id's, and just add new records if required.
Is it possible to merge these two mysql queries into one? I want to get NOW() returned to a php variable.
mysql_query('INSERT INTO translate (IDRef, RefType, Lang, Text, LastChangeTS) VALUES ('.$id.', \''.$reftype.'\', \''.$lang.'\', \''.$text.'\', NOW()) ON DUPLICATE KEY UPDATE text = \''.$text.'\', LastChangeTS = NOW()');
mysql_query('SELECT LastChangeTS FROM translate WHERE IDRef = '.$id.' AND RefType = \''.$reftype.'\' AND Lang = \''.$lang.'\'');
You can't merge a insert statement and a select statement. But, you can sure use a stored procedure which inserts the data and then returns the LastChange value.