Issue when updating date in db table - php

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.

Related

mysql unique for multiple columns

When payment happen, sometimes its captured double entry in table.
I want to ignore double entry capture so i want to insert records when these created, user_id, amount fields should be unique.
How do i make it ? Below is my table.
CREATE TABLE `transactions` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(20) NOT NULL,
`project_id` int(20) DEFAULT NULL,
`foreign_id` int(20) NOT NULL,
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`transaction_type_id` int(20) DEFAULT NULL,
`amount` float(10,2) NOT NULL,
`description` text COLLATE utf8_unicode_ci,
`payment_gateway_id` int(20) DEFAULT NULL,
`gateway_fees` float(10,2) NOT NULL,
`is_old` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=266 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
To strictly answer your question, you create a unique composite key on the combination of those 3 columns. That way no two rows can exist with a combination of the 3 of them in the composite index.
CREATE TABLE `transactions2` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(20) NOT NULL,
`project_id` int(20) DEFAULT NULL,
`foreign_id` int(20) NOT NULL,
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`transaction_type_id` int(20) DEFAULT NULL,
`amount` float(10,2) NOT NULL,
`description` text COLLATE utf8_unicode_ci,
`payment_gateway_id` int(20) DEFAULT NULL,
`gateway_fees` float(10,2) NOT NULL,
`is_old` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
unique key(created,user_id,amount) -- <------------------- right here
);
insert some data to test it:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- inserts fine (above)
Try it again with exactly the same data:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- error 1062: Duplicate entry
-- change it barely:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 13:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- inserts fine
Also, use ENGINE=INNODB. Read about that Here.
Please read Mysql multi column indexes a.k.a. composite indexes.
Lastly, the concept of what you are talking about is not far off from Insert on Duplicate Key Update. Just throwing that reference out there for you.
You can achieve the same using ,handling at the time of inserting,
You can try WHERE NOT EXISTS with INSERT.
Something like this.(You need to specify column name who has NOT NULL constraint,i missed all those columns)
INSERT INTO table_name(`created`,`user_id`,`amount`) VALUES =
'$created','$user_id','$amount'
WHERE NOT EXISTS
(SELECT *
FROM table_name
WHERE created ='$created' AND user_id='$user_id' AND amount='$amount')
Hope this helps.

Fname and last name in mysql, error displaying

i have a problem in my examination system. In the admin panel, in the results page displays the correct score but the firstname and the last name not. I dont know what to do.
Here is the code:
$result1=executeQuery("select s.nume_student,s.prenume_student,s.stdname,s.stdid, IFNULL((select sum(q.marks) from studentquestion as sq,question as q where q.qnid=sq.qnid and sq.testid=".$_REQUEST['testid']." and sq.stdid=st.stdid and sq.stdanswer=q.correctanswer),0) as om from studenttest as st, student as s where s.stdid=st.stdid and st.testid=".$_REQUEST['testid'].";" );
$result3=executeQuery("SELECT sq.stdid, sq.testid, COUNT(*) AS correctAnswers, SUM(q.marks) AS studentScore,(SELECT SUM(marks) FROM question WHERE testid=".$_REQUEST['testid'].") AS totalScore FROM question q, studentquestion sq WHERE sq.testid=".$_REQUEST['testid']." AND q.testid = sq.testid AND q.qnid = sq.qnid AND sq.answered = 'answered' AND q.correctanswer = sq.stdanswer GROUP BY sq.stdid");
without $result1 doesen't display anything
And here are the tables from database:
question table:
CREATE TABLE IF NOT EXISTS `question` (
`testid` bigint(20) NOT NULL DEFAULT '0',
`qnid` int(11) NOT NULL DEFAULT '0',
`question` varchar(500) DEFAULT NULL,
`optiona` varchar(100) DEFAULT NULL,
`optionb` varchar(100) DEFAULT NULL,
`optionc` varchar(100) DEFAULT NULL,
`optiond` varchar(100) DEFAULT NULL,
`correctanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL,
`marks` float(3,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
studentquestion table:
CREATE TABLE IF NOT EXISTS `studentquestion` (
`stdid` bigint(20) NOT NULL DEFAULT '0',
`testid` bigint(20) NOT NULL DEFAULT '0',
`qnid` int(11) NOT NULL DEFAULT '0',
`answered` enum('answered','unanswered','review') DEFAULT NULL,
`stdanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
student table:
CREATE TABLE IF NOT EXISTS `student` (
`stdid` bigint(20) NOT NULL,
`stdname` varchar(40) DEFAULT NULL,
`stdpassword` varchar(40) DEFAULT NULL,
`emailid` varchar(40) DEFAULT NULL,
`contactno` varchar(20) DEFAULT NULL,
`fname` varchar(40) DEFAULT NULL,
`lname` varchar(40) DEFAULT NULL,
`pincode` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
student test table:
CREATE TABLE IF NOT EXISTS `studenttest` (
`stdid` bigint(20) NOT NULL DEFAULT '0',
`testid` bigint(20) NOT NULL DEFAULT '0',
`starttime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`endtime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`correctlyanswered` int(11) DEFAULT NULL,
`status` enum('over','inprogress') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and test table:
CREATE TABLE IF NOT EXISTS `test` (
`testid` bigint(20) NOT NULL,
`testname` varchar(30) NOT NULL,
`testdesc` varchar(100) DEFAULT NULL,
`testdate` date DEFAULT NULL,
`testtime` time DEFAULT NULL,
`subid` int(11) DEFAULT NULL,
`testfrom` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`testto` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`duration` int(11) DEFAULT NULL,
`totalquestions` int(11) DEFAULT NULL,
`attemptedstudents` bigint(20) DEFAULT NULL,
`testcode` varchar(40) NOT NULL,
`tcid` bigint(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I resolved the same problem of here:
How to get sql WHERE statement auto update from localhost link
but i'm stucked here with fname and last name.
If your second query returns the correct student ids, you can just change it to add student names:
SELECT s.lastname, s.firstname, e.*
from
students s join (
... your second query ... ) e
on s.stdid=e.stdid
you can change your join type depends on what you want.
Thanks, but i resolved it like this:
SELECT ***s.fname, s.lname***, sq.stdid, sq.testid, COUNT(*) AS correctAnswers,
SUM(q.marks) AS studentScore,(SELECT SUM(marks) FROM question
WHERE testid=1) AS totalScore
FROM question q, studentquestion sq, ***student s***
WHERE sq.testid=1 AND q.testid = sq.testid
AND q.qnid = sq.qnid AND sq.answered = 'answered' ***and sq.stdid=s.stdid***
AND q.correctanswer = sq.stdanswer GROUP BY sq.stdid

NULL entry at id field in Phpmyadmin

I exported the sql from one phpmyadmin db and imported same at another phpmyadmin db.
The create table statement is as follows
CREATE TABLE IF NOT EXISTS `h_stats` (
`Id` int(11) DEFAULT NULL,
`Category` varchar(50) DEFAULT NULL,
`Success` int(11) DEFAULT NULL,
`OutcomeFailure` int(11) DEFAULT NULL,
`ThCount` int(11) DEFAULT NULL,
`OCount` int(11) DEFAULT NULL,
`HDate` varchar(50) DEFAULT '0',
`Count` int(11) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The insert sql file also I have exported it as follows
INSERT INTO `h_stats` (`Id`, `Category`, `Success`, `Failure`, `ThCount`, `OCount`, `HDate`, `Count`) VALUES
(13, 'Hits', 31303, 8828, 8893, 30372, '2015-04-07', 40151),
Note :
When I try to insert new rows at the place of id NULL value is coming.
Can anyone suggest me what to change in create table statement.
You need to define the id as primary key and auto-increment .
CREATE TABLE IF NOT EXISTS `h_stats` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Category` varchar(50) DEFAULT NULL,
`Success` int(11) DEFAULT NULL,
`OutcomeFailure` int(11) DEFAULT NULL,
`ThCount` int(11) DEFAULT NULL,
`OCount` int(11) DEFAULT NULL,
`HDate` varchar(50) DEFAULT '0',
`Count` int(11) DEFAULT '0',
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
So when you add null for id, the auto-increment will come in to play and set it the next value in insert.
Note that this will enforce you to have unique value for id so while doing insert leave id into the insert statement. Something as
insert into h_stats (`Category`,`Success` ...) values ( ....);

Mysql LEFT Join on big data table

I have a table called "tables_data_info" where is stored some of the data relative to different tables. Data like "created time", "editing time", "editing user", "create by user id" etc. I'm using this table because there was a dynamic php script that generate it automatically.
But, when i have a huge number of record ( 15k in this case ) the query getting very very very slow, and take "minutes" to do his job! But i'm not selecting all 15k records, i'm limiting to select 10 records at all!
A simple query:
SELECT pd.id, pd.title, pd.sell_price, pd.available_qt, tdi.createtime, tdi.lastupdatetime, tdi.create_member_id, tdi.create_group_id, tdi.last_update_member_id, tdi.last_update_group_id FROM zd_products AS pd LEFT JOIN zd_tables_data_info AS tdi ON ( tdi.targetid = pd.id and tdi.table_name = 'products' ) ORDER by pd.title ASC LIMIT 0, 10
How can i run this query differently but more efficiently ?
Here the table structure:
zd_products
CREATE TABLE `zd_products` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(256) NOT NULL DEFAULT '',
`internalcode` varchar(256) DEFAULT NULL,
`ean13_jan_code` varchar(256) DEFAULT NULL,
`upc_code` varchar(11) DEFAULT NULL,
`active` tinyint(1) NOT NULL DEFAULT '0',
`status` varchar(12) NOT NULL DEFAULT 'new',
`product_tags` longtext,
`buy_price` double NOT NULL DEFAULT '0',
`sell_price` double NOT NULL DEFAULT '0',
`fiscal_tax_id` int(11) NOT NULL DEFAULT '0',
`box_width` double NOT NULL DEFAULT '0',
`box_height` double NOT NULL DEFAULT '0',
`box_depth` double NOT NULL DEFAULT '0',
`box_weight` double NOT NULL DEFAULT '0',
`shipment_extra_price` double NOT NULL DEFAULT '0',
`available_qt` int(11) NOT NULL DEFAULT '0',
`allow_purchase_out_stock` tinyint(1) NOT NULL DEFAULT '0',
`meta_title` varchar(256) DEFAULT NULL,
`meta_description` varchar(256) DEFAULT NULL,
`meta_keywords` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15730 DEFAULT CHARSET=utf8;
zd_tables_data_info
CREATE TABLE `zd_tables_data_info` (
`table_name` varchar(256) NOT NULL DEFAULT '',
`targetid` int(11) DEFAULT NULL,
`create_member_id` int(11) unsigned DEFAULT NULL,
`create_group_id` int(11) unsigned DEFAULT NULL,
`last_update_member_id` int(11) unsigned DEFAULT NULL,
`last_update_group_id` int(11) unsigned DEFAULT NULL,
`createtime` int(11) unsigned DEFAULT NULL,
`lastupdatetime` int(11) unsigned DEFAULT NULL,
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `INDEX` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19692 DEFAULT CHARSET=utf8;
Your data is not particularly big. Here is the query:
SELECT pd.id, pd.title, pd.sell_price, pd.available_qt,
tdi.createtime, tdi.lastupdatetime, tdi.create_member_id, tdi.create_group_id,
tdi.last_update_member_id, tdi.last_update_group_id
FROM zd_products pd LEFT JOIN
zd_tables_data_info tdi
ON tdi.targetid = pd.id and tdi.table_name = 'products'
ORDER by pd.title ASC
LIMIT 0, 10;
You can improve performance of this query with indexes. The two that come to mind are zd_products(title, id) and zd_tables_data_info(targetid, table_name). Try these and see if they help. You can create these indexes either in the create table statement (or alter table) or by using:
create index zd_products_title_id on zd_products(title, id);
create index zd_tables_data_info_targetid_table_name on zd_tables_data_info(targetid, table_name);
If not, put explain in front of your query and then edit your question with the resulting plan.

MySQL Stored Procedure [Copy table 1 -> table 2]

My knowledge of MySQL/ SQL apart from the simple CRUD operations is basic.
If I had to use a stored procedure to move certain attributes (not in a specific order) to another table how could it be done?
These are the following tables. I want to move from the 1st to the 2nd table.
As you can see the datatype sizes are different for certain columns.
CREATE TABLE IF NOT EXISTS `source_cdr` (
`callstart` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`src` varchar(80) NOT NULL DEFAULT '',
`dst` varchar(80) NOT NULL DEFAULT '',
`accountcode` varchar(50) NOT NULL,
`uniqueid` varchar(100) NOT NULL,
`ID` int(11) NOT NULL AUTO_INCREMENT,
`callanswer` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`callend` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`disposition` varchar(50) NOT NULL,
`cdr_id` int(11) unsigned NOT NULL DEFAULT '0',
`pin_code` varchar(4) NOT NULL,
`provider` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `calldate_idx` (`callstart`) USING BTREE,
KEY `idx_acc_code_calldate` (`accountcode`,`callstart`) USING BTREE,
KEY `uniqueid` (`uniqueid`),
KEY `cdr_id` (`cdr_id`),
KEY `idx_uniqueid_cdr_id` (`uniqueid`,`cdr_id`)
) ENGINE=MyISAM;
--
CREATE TABLE IF NOT EXISTS `destination_cdr` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`calldate` datetime NOT NULL,
`source` varchar(80) NOT NULL,
`destination` varchar(80) NOT NULL,
`account_code` varchar(30) DEFAULT NULL,
`pincode` varchar(45) NOT NULL,
`duration_call` bigint(20) NOT NULL DEFAULT '0',
`duration_talk` bigint(20) NOT NULL,
`disposition` varchar(255) NOT NULL,
`clid` varchar(80) DEFAULT NULL,
`cdr_id` bigint(20) DEFAULT NULL,
`vxcdr_id` bigint(20) DEFAULT NULL,
`provider` int(11) NOT NULL DEFAULT '0'
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
EDIT 1
An example of a row
('2012-03-18 20:54:49', '5796', '0761100866', '103f0124ad510516f33cab132c0a695b', 'call-F1884808-6753-2F10-181C-3A#10.217.164.33', 308006367, '2012-03-18 20:55:05', '2012-03-18 20:55:51', '200 OK', 2, '', 0),
Thanks
You can use MySQL: INSERT ... SELECT Syntax to copy data from one table to the other.
Decide common fields in both and copy the same.
Example:
INSERT INTO TABLE2( COL1, COLx, ... ) SELECT colM, colY FROM TABLE1;
If the column sizes mismatch, data truncation takes place, and you can't overcome that but redefine the destination table columns.

Categories