SQL-PHP datetime - php

I'm integrating an RSS feed unto my website and i need to create a table:
CREATE TABLE `stories` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(255) NOT NULL default '',
`description` text NOT NULL,
`when` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
)
i know how to insert id, title, description but i do not know how to insert the time of the post (user submits them). I used the script given here.
mysql_query("insert into stories (title,description) VALUES ('$_POST[title]','$_POST[description]') ");

For when use the date function:
date('Y-m-d h:i:s')
By default the date function uses the current date/time if you don't supply one as the second argument.

Related

selecting records based on datetime column changes the data in the datetime column ..very strange

So i have a table that has multiple date time columns and i am trying to select certain records based on a certain date using
SELECT * FROM `posdata` WHERE `CommissionDate` >= '2019-01-01 00:00:00'
the table structure
CREATE TABLE `posdata` (
`ID` int(11) NOT NULL,
`DISTYNAME` varchar(30) DEFAULT NULL,
`ENDCUST` varchar(75) DEFAULT NULL,
`MFGCUST` varchar(50) DEFAULT NULL,
`EXTPRICE` double DEFAULT NULL,
`POSPERIOD` datetime DEFAULT NULL,
`PAYMENTDATE` date DEFAULT NULL,
`QTY` double DEFAULT NULL,
`UNITCOST` double DEFAULT NULL,
`UNITPRICE` double DEFAULT NULL,
`COMMISSION` double DEFAULT NULL,
`SALESORDER` varchar(40) DEFAULT NULL,
`PO` varchar(40) DEFAULT NULL,
`POLineItem` varchar(20) DEFAULT NULL,
`ENTRYDATE` datetime DEFAULT NULL,
`AdjustedCommission` int(11) DEFAULT NULL,
`CustomerPart-NO` varchar(50) DEFAULT NULL,
`CommissionDate` datetime DEFAULT NULL,
`EXTCOST` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `posdata`
ADD PRIMARY KEY (`ID`),
ADD KEY `CommissionDate` (`CommissionDate`);
ALTER TABLE `posdata` ADD FULLTEXT KEY `posdata_endcustomer_index` (`ENDCUST`);
a very weird thing happens, it returns all the fields as required, but the CommissionDate column has only '2019-01-01 00:00:00' as the date. The actual CommissionDate column in the database has only '2016-01-01 00:00:00' as the data.
I am using phpmyadmin to to run this query and have used the search filter on that and it always gives me the same result whether i run it thorough a php script or phpmyadmin. What am i doing wrong ?
In your query SELECT * FROM 'posdata' means get all the fields from the table post data and then the next WHERE clause applies.If you only want to get the data from CommissionDate column
Change Your Query to
SELECT `CommissionDate` FROM `posdata`
In the way you get the desired data.
the query was correct can some one delete this question !

Laravel 5 LEFT JOIN issue with id's

I have an issue with LEFT JOIN. I do not want to use eloquent relations because I want to keep my models folder clean. I have an appointments application in which I am using "labels" and "statuses". I want to be able to filter my view based on the labels and statuses. The issue with the LEFT JOIN is that when I want to click on my edit link, it uses the "id" field from my "appointments_statuses" table, instead of the "appointments" table. Below is the relevant code:
My controller:
$appointments = $query->orderBy('appointment', 'asc')
->leftJoin('appointments_labels','appointments_labels.id','=','appointments.label_id')
->leftJoin('appointments_statuses','appointments_statuses.id','=','appointments.status_id')
->get();
My view:
#foreach($appointments as $appointment)
{{ $appointment->id }} // Problem here, it uses the "status_id" field from the "appointments" table instead of the "id" field
#endforeach
My database tables:
CREATE TABLE IF NOT EXISTS `appointments` (
`id` int(11) NOT NULL,
`appointment` varchar(255) NOT NULL,
`location` varchar(255) NOT NULL,
`description` text NOT NULL,
`start` datetime NOT NULL,
`end` datetime NOT NULL,
`label_id` int(11) NOT NULL,
`status_id` int(11) NOT NULL,
`contact` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
)
CREATE TABLE IF NOT EXISTS `appointments_labels` (
`id` int(11) NOT NULL,
`label` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
)
CREATE TABLE IF NOT EXISTS `appointments_statuses` (
`id` int(11) NOT NULL,
`status` varchar(255) NOT NULL,
`flag` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
)
Well, that's because your query collects ALL the fields of the 3 tables, so the columns with the same name get overwritten.
Simply use a select() on what fields you want (which is a good practice, anyway):
$appointments = $query->orderBy('appointment', 'asc')
->leftJoin('appointments_labels','appointments_labels.id','=','appointments.label_id')
->leftJoin('appointments_statuses','appointments_statuses.id','=','appointments.status_id')
->select('appointments.id', 'appointments.name', '........', 'appointments_statuses.name', 'appointments_labels.name')
->get();
NB: I'm guessing the fields you want from the main and the joined tables, but you get the idea :)
NB2: You can also pass an array of values to the select() method:
->select(['appointments.id', 'appointments.name', ....])

Date Now() not going in to mysql database

Hi I have some code shown below, which inserts date_time and date in to the mysql fields using the now() command.
However the date_time field updates but the date field doesn't and I can not seem to work out why?
my mysql fields are datetime and date
INSERT INTO vistordetails1
(ipaddress, client_id, type, date_time, company_name, location, search_term, trafic_source, no_of_pages, date, country_code) VALUES('$ip_address', '$client_id', '$type', now(),'$fields[11]','$fields[6]', '$keyword', '$referer','1', now(), '$country_code')
Table Structure
`id` int(11) NOT NULL AUTO_INCREMENT,
`client_id` int(11) NOT NULL,
`master_id` int(11) NOT NULL,
`type` tinyint(1) NOT NULL ,
`date_time` datetime NOT NULL,
`company_name` varchar(250) NOT NULL,
`location` varchar(250) NOT NULL,
`no_of_pages` int(11) NOT NULL,
`trafic_source` varchar(250) NOT NULL,
`search_term` varchar(250) NOT NULL,
`is_repeater` tinyint(1) NOT NULL,
`classification` int(11) NOT NULL,
`owner` int(11) NOT NULL,
`alert_for_repeat_visit` tinyint(1) NOT NULL DEFAULT '0',
`is_hot_list` enum('0','1') NOT NULL DEFAULT '0',
`ipaddress` varchar(50) NOT NULL,
`country_code` varchar(10) NOT NULL,
`date` date NOT NULL,
Try using CURDATE() instead of NOW() for the date field.
$INSERT = "INSERT INTO vistordetails1
(ipaddress,
client_id,
type,
date_time,
company_name,
location,
search_term,
trafic_source,
no_of_pages,
date,
country_code)
VALUES(
'".mysql_real_escape_string(trim($ip_address))."',
'".mysql_real_escape_string(trim($client_id))."',
'".mysql_real_escape_string(trim($type))."',
now(),
'".mysql_real_escape_string(trim($fields[11]))."',
'".mysql_real_escape_string(trim($fields[6]))."',
'".mysql_real_escape_string(trim($keyword))."',
'".mysql_real_escape_string(trim($referer))."',
'".mysql_real_escape_string(trim(1))."',
CURDATE(),
'".mysql_real_escape_string(trim($country_code'))."')";
Also as a previous user mentioned you seriously need to make sure your data is escaped, or use mysql prepare.
If you need to convert a PHP date into a valid MySql date, then the only thing you need to do is
ensure that it is formatted correctly.
The default date/datetime format for Mysql is: yyyy-mm-dd and yyy-mm-dd hh:mm:ss
Something like this will work.
$phpDate = date('Y-m-d H:i:s', time());
However
Because you are creating a new date, why use PHP at all? Within MySql you can include the current date using NOW() function.
$sql = "INSERT INTO xyz (a, b, c, datetime) VALUES ('a', 'b', 'c', NOW());"
Additionally
You could apply a default value of CURRENT_TIMESTAMP to the table column. Meaning you wouldn't even need to pass any date
as the database will take care of it.
i.e ALTER TABLE test CHANGE datecolumn datecolumn DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

PHP script to create table

I need to create MySQL table. So I'm running this script but it's just not working. Any idea why?
<?php
$con = mysql_connect("database.dcs.aber.ac.uk","xxx","nnnnnnnnnn");
mysql_select_db("jaz",$con);
$sql = "CREATE TABLE storys
(
id int NOT NULL AUTO_INCREMET,
title TINYTEXT,
type TINYTEXT,
link TEXT,
preview TINYTEXT,
tags TINYTEXT,
text MEDIUMTEXT,
updated TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP,
created DATETIME() DEFAULT NULL,
PRIMARY KEY(id)
)";
mysql_query($sql,$con);
mysql_close($con);
?>
Your code has absolute NO error handling, which would have shown you the reason the query's failing.
$con = mysql_connect(...) or die(mysql_error());
$res = mysql_query(...) or die(mysql_error());
is the bare minimum error handling you should have on pretty much every mysql call.
Had this been in place, you'd have to been told:
id int NOT NULL AUTO_INCREMET,
^---missing 'n', not a valid SQL keyword.
Among the previously listed issues, you are using functions in the data type definitions, and the "ON UPDATE" syntax is wrong.
Here is what I think you are looking for in the SQL:
CREATE TABLE IF NOT EXISTS `storys` (
`id` INT NOT NULL AUTO_INCREMENT ,
`title` TINYTEXT,
`type` TINYTEXT,
`link` TEXT,
`preview` TINYTEXT,
`tags` TINYTEXT,
`text` MEDIUMTEXT,
`updated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
`created` DATETIME DEFAULT NULL ,
PRIMARY KEY ( id )
);

Issue when updating date in db table

I'm working on a codeigniter project and I'm trying to troubleshoot a sql issue. I have a query that updates a date field in my table and it's not updating it at all.
I have this table
CREATE TABLE `Customer` (
`customer_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(55) NOT NULL DEFAULT '',
`last_name` varchar(55) NOT NULL DEFAULT '',
`city` varchar(255) DEFAULT '',
`state` char(2) DEFAULT '',
`zip` int(5) DEFAULT NULL,
`title` varchar(255) NOT NULL DEFAULT '',
`image` varchar(255) DEFAULT '',
`blurb` blob,
`end_date` date DEFAULT NULL,
`goal` int(11) DEFAULT NULL,
`paypal_acct_num` int(11) DEFAULT NULL,
`progress_bar` enum('full','half','none') DEFAULT NULL,
`page_views` int(11) NOT NULL DEFAULT '0',
`total_pages` int(11) NOT NULL DEFAULT '0',
`total_conversions` int(11) NOT NULL DEFAULT '0',
`total_given` int(11) NOT NULL DEFAULT '0',
`conversion_percentage` int(11) NOT NULL DEFAULT '0',
`avg_contribution` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`customer_id`)
) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
and when I run this query to insert data, it runs fine and sets the date to 2012-11-01
INSERT INTO `Customer` (`first_name`, `last_name`, `end_date`) VALUES ('John', 'Smith2', '2012-11-01');
Then I get the customer_id and try to run this query
UPDATE `Customer` SET `end_date` = '2012-14-01' WHERE `customer_id` = '18';
and it sets the date end_date field to 0000-00-00.
Why is it changing the end date to 0000-00-00 rather than 2012-14-01?
2012-14-01 is first day of fourteenth month :)
(so its invalid date, thus casted to 0000-00-00 and Data truncated for column 'end_date' at row 1 warning was returned by mysql, which you can see by querying SHOW WARNINGS to mysql immediately after badly behaving query)
2012-01-14 is 14th of January.
use this:
UPDATE `Customer` SET `end_date` = date('Y-m-d') WHERE `customer_id` = '18';
Use date function to update this field.

Categories