Storing the date in database - php

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());

Related

INSERT ON DUPLICATE KEY UPDATE IF statements

I'm trying to create a script for stats about visitors to my site. To do this, I record the visitor's IP, along with the date of the day and the number of times it has passed.
If this is the first visit, on all records in the database. But I want to count 1 pass per person per day.
What I am trying to do : If the IP already exists, and the date is different from the day : we assign the date of the day, and increment the number of passing (+1).
The Problem : When the date is different from the day, it is changed, BUT: the number of passing continues to increment even if the IP has already been counted that day.
It should only be done the next day, when the date changes...
Here is my table structure :
--
-- Table structure for table `ChartsGuests`
--
CREATE TABLE `ChartsGuests` (
`IP_Guest` varchar(39) NOT NULL,
`Date` varchar(10) NOT NULL,
`Total` int(11) NOT NULL,
PRIMARY KEY (`IP_Guest`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB DEFAULT CHARSET=utf8;
Here is the code :
$IP_NewGuest = $_SERVER['REMOTE_ADDR'];
$Today = date('d/m/Y');
$SQL = "INSERT INTO `ChartsGuests` (`IP_Guest` , `Date`, `Total`) VALUES ('".$IP_NewGuest."' , '".$Today."', 1)
ON DUPLICATE KEY UPDATE
Date = IF(Date != '".$Today."', VALUES(Date), '".$Today."'),
Total = IF(Date != '$Today', VALUES(Total), Total + 1 )";
$REQ = $DB->prepare($SQL);
$REQ->execute() or die(var_dump($REQ->errorInfo()));
// echo $SQL;
It should only be done the next day, when the date changes... I do not know where the problem comes from, and this is the first time I use the "ON DUPLICATE KEY" with an "IF" ...
Thank you in advance !
Your problem is that your duplicate key is just on the IP address, but your table is really unique per IP Address/Date combo. As a result, visits on subsequent days overwrite the rows for the previous day.
If you change the logic of your table to have composite unique key on those two fields, the query will generate inserts for new (IP,Date) combos, and updates for (IP,date) combos that have been seen already.
If you fix that, you don't need the conditional (nor PHP for the current date), and you can just make this your SQL:
INSERT INTO `ChartsGuests` (`IP_Guest` , `Date`, `Total`)
VALUES ('".$IP_NewGuest."' , CURDATE(), 1)
ON DUPLICATE KEY UPDATE Total = Total + 1 )";

how to insert data with where cause

create table cmu_patient
( patient_id character varying(13) NOT NULL,
patient_hn character varying(7),
patient_fname character varying(50),
patient_lname character varying(50),
home_id integer,
CONSTRAINT cmu_patient_pkey PRIMARY KEY (patient_id),
CONSTRAINT Fk_home FOREIGN KEY(home_id)
REFERENCES cmu_home(home_id)
);
create table cmu_treatment
( treatment_id serial NOT NULL,
treatment_date date,
treatment_time time without time zone,
treatment_typecome character varying(100),
treatment_detail text,
patient_id character varying(13),
appointment_id character varying(5),
transfer_id character varying(5),
res_users_id integer,
CONSTRAINT cmu_treatment_pkey PRIMARY KEY (treatment_id),
CONSTRAINT Fk_patient FOREIGN KEY(patient_id)
REFERENCES cmu_patient(patient_id),
CONSTRAINT Fk_user_id FOREIGN KEY(res_users_id)
REFERENCES res_users(id)
);
$treatment_date = $GET_[...];
$treatment_time = $GET_[...];
$treatment_typecome = $GET_[...];
$treatment_note = $GET_[...];
$CID = $GET_[...];
this code -------- it's incorrect
INSERT INTO cmu_treatment(treatment_id, treatment_date, treatment_time,
treatment_typecome, treatment_detail, patient_id, appointment_id,transfer_id, res_users_id)
VALUES(NULL,'".$tratment_date."','".$treatment_time."','".
$treatment_typecome."','".$treatment_note."','".$CID."',NULL,NULL,NULL)
WHERE cmu_patient.patient_id = cmu_treatment.patient_id ;
i think that's wrong
i don't know if i want to write insert data into table with where cause i should write sql ?
thank :)
I suspect what you really want is an update, to change existing values in an existing record:
update cmu_treatment
set treatment_date = $treatment_date,
treatment_time = $treatment_time,
treatment_detail = $treatment_typecome,
treatment_note = $treatment_note
where patient_id = $CID;
(I'm leaving out the NULL values on the assumption that those shouldn't really change.)
If you do indeed want a new record, you can do:
INSERT INTO cmu_treatment(treatment_id, treatment_date, treatment_time,
treatment_typecome, treatment_detail, patient_id, appointment_id,
transfer_id, res_users_id
)
select NULL,'".$tratment_date."', '".$treatment_time."','".
$treatment_typecome."','".$treatment_note."','".$CID."', NULL, NULL, NULL;
You can write an INSERT statement populating target table with a SELECT statement. In the SELECT statement you can use WHERE condition.
So instead this query:
INSERT INTO table VALUES (....)
You must write:
INSERT INTO table
SELECT fields
FROM anothertable
WHERE condition
In your case, I think you must use an INSERT without WHERE condition if you want to insert only a row in your treatment table.
Tell me if you want to know further info
EDIT After comment
IMHO your statement must be:
INSERT INTO cmu_treatment
(treatment_id, treatment_date, treatment_time,
treatment_typecome, treatment_detail, patient_id, appointment_id,
transfer_id, res_users_id)
VALUES
(NULL,'".$tratment_date."','".$treatment_time."',
'".$treatment_typecome."','".$treatment_note."','".$CID."',NULL,NULL,NULL)
INSERT INTO `cmu_treatment`(`treatment_id`, `treatment_date`, `treatment_time`,
`treatment_typecome`, `treatment_detail`, `patient_id`, `appointment_id`,`transfer_id`, `res_users_id`)
VALUES(NULL,'".$tratment_date."','".$treatment_time."','".
$treatment_typecome."','".$treatment_note."','".$CID."',NULL,NULL,NULL)
WHERE `cmu_patient.patient_id` = `cmu_treatment.patient_id` ;
And you don't need (table name).(column).
Is this Inside "" ? If yes then you don't need '".$tratment_date."' you can use only '' so your code will look like this.
INSERT INTO cmu_treatment(treatment_id, treatment_date, treatment_time,
treatment_typecome, treatment_detail, patient_id, appointment_id,transfer_id, res_users_id)
VALUES(NULL,'$tratment_date','$treatment_time','
$treatment_typecome','$treatment_note','$CID',NULL,NULL,NULL)
WHERE `patient_id` = patient_id ;
And finally what is patient_id? Is it variable? If not IT MUST BE. Don't give same names to different things.

PHP mysql auto insert timestamp

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);

How to check to see if a key exists before trying to insert it into a database?

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.

PHP+MySQL Update TimeStamp and get NOW() back

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.

Categories