PHP isset() function returns FALSE even though the variable is defined

Let’s say we have a table item in a MySQL database, with the primary key iditem and a field code that can be NULL:

CREATE TABLE `item` (
`iditem` int(10) unsigned NOT NULL,
`code` VARCHAR(10) DEFAULT NULL,
PRIMARY KEY (`iditem`),
);

--
-- Dumping data for table `item`
--

INSERT INTO `item` (`iditem`, `code`) VALUES
(1, 'as1435v'),
(2, NULL),
(3, 1, 'YHryt4t90');

In PHP we define a variable $item_code that we initialize with 0 and then we run a query for setting the value of $item_code to the code of the item which has the id 2 in our database:

$item_code = 0;
$query = "SELECT code FROM item WHERE iditem = 2";
$result = mysql_query($conn); //$conn is our database connection
if($result) {
	if($row = mysql_fetch_row($result)) {
		$item_code = $row[0];
	}
}

if(isset($item_code)) {
	echo "item code: ".$item_code;
} else {
	echo "item code is not set";
}

The output will be:
item code is not set

That is because the code is NULL in the database and it is transferred into PHP not as the empty string, but as NULL.
And the name of the isset() function is misleading as it returns FALSE not only when a variable is not defined, but also when a variable has been set to NULL.

Updating multiple fields in multiple rows with different values in a single query in MySQL using the CASE operator does not supply a correct result

Suppose we have a table with rows representing nodes of a tree structure, each node being represented by an id, a parent id and a position between the children of its parent node:

CREATE TABLE  `tree`.`node` (
`idnode` TINYINT NOT NULL AUTO_INCREMENT ,
`idnode_parent` TINYINT NULL ,
`position` TINYINT NULL ,
PRIMARY KEY ( `idnode` )
);

The nodes with idnode_parent set to 0 or NULL are on the first level of the tree structure.

Now we populate the table:

#add some first level nodes
INSERT INTO `tree`.`node` VALUES (NULL, 0, 1); #idnode = 1
INSERT INTO `tree`.`node` VALUES (NULL, 0, 2); #idnode = 2
#add some children for the first node on the first level
INSERT INTO `tree`.`node` VALUES (NULL, 1, 1); #idnode = 3
INSERT INTO `tree`.`node` VALUES (NULL, 1, 2); #idnode = 4
#add some children for the node with idnode 2
INSERT INTO `tree`.`node` VALUES (NULL, 2, 1); #idnode = 5
INSERT INTO `tree`.`node` VALUES (NULL, 2, 2); #idnode = 6
INSERT INTO `tree`.`node` VALUES (NULL, 2, 3); #idnode = 7
#add a child for the node with idnode 7
INSERT INTO `tree`.`node` VALUES (NULL, 7, 1); #idnode = 8

Now the table looks like this:
idnode idnode_parent position
1 0 1
2 0 2
3 1 1
4 1 2
5 2 1
6 2 2
7 2 3
8 3 1
9 7 1

We want to delete:
– node 1, so we move its children (3, 4) up one level (idnode_parent changes from 1 to 0) and update their positions to the position of their parent (position changes from 1, 2 respectively to 1);
– node 7, so we move its children (8) up one level (idnode_parent changes from 7 to 2) and update their positions to the position of their parent (position changes from 1 to 3)

a) We try this query:

UPDATE node
SET idnode_parent = CASE(idnode_parent)
WHEN 1 THEN 0
WHEN 7 THEN 2
END,
position = CASE(idnode_parent)
WHEN 1 THEN 1
WHEN 7 THEN 3
END
WHERE idnode_parent IN (1, 7);

Running this query, MySQL says 3 rows were affectedand the table looks as follows:

idnode idnode_parent position
1 0 1
2 0 2
3 0 NULL
4 0 NULL
5 2 1
6 2 2
7 2 3
8 3 1
9 2 NULL

We can see that only the field idnode_parent updated as expected, the position field for the moved nodes being set to NULL.

b) We reset the table to the initial test data and we run the above query with the difference of using the ELSE clause in the CASE expression:

UPDATE node
SET idnode_parent = CASE(idnode_parent)
WHEN 1 THEN 0
WHEN 7 THEN 2
ELSE idnode_parent
END,
position = CASE(idnode_parent)
WHEN 1 THEN 1
WHEN 7 THEN 3
ELSE position
END
WHERE idnode_parent IN (1, 7);

The result is:

idnode idnode_parent position
1 0 1
2 0 2
3 0 1
4 0 2
5 2 1
6 2 2
7 2 3
8 3 1
9 2 1

So the idnode_parent field updates correctly, but position remains unchanged.

My conclusion is that that the query runs as if there were two different queries running over the bunch of rows resulted after evaluating the WHERE condition, the second CASE operator applying over the data modified by the first CASE operator:
1. WHERE condition is evaluated; resulted data set:

idnode idnode_parent position
3 1 1
4 1 2
9 7 1

2. idnode_parent is set by evaluating the first CASE expression:

idnode idnode_parent position
3 0 1
4 0 2
9 2 1
3. position is set by evaluating the second CASE expression:

a) Using the query without the ELSE condition, position is set to NULL for all the rows in the data set, as after running the first CASE expression there are no more rows with the idnode_parent needed for the second CASE expression:
idnode idnode_parent position
3 0 NULL
4 0 NULL
9 2 NULL

b) Using the query with the ELSE condition, position remains unchanged for all the rows in the data set, as there are no more rows with the needed idnode_parent, as they were modified by applying the previous CASE operator, and the ELSE condition is evaluated:
idnode idnode_parent position
3 0 1
4 0 2
9 2 1

So if we want the query to run correctly, we set the position first, and then the id of the parent node, as position does not modify data needed for subsequent idnode_parent updates in the same query:

UPDATE node
SET position = CASE(idnode_parent)
WHEN 1 THEN 1
WHEN 7 THEN 3
END,
idnode_parent = CASE(idnode_parent)
WHEN 1 THEN 0
WHEN 7 THEN 2
END
WHERE idnode_parent IN (1, 7);

We finally obtain the expected result:
idnode idnode_parent position
3 0 1
4 0 1
9 2 3

Importing a MySQL data file using phpMyAdmin results in incomplete data in MySQL

I tried moving all my databases from MySQL 4.1 to MySQL 5.1 on Windows and since I had some InnoDB tables I could not just copy the data files between MySQL Server versions (from C:\Documents and Settings\All Users\Application Data\MySQL\MySQL 4.1\data\ to  C:\Documents and Settings\All Users\Application Data\MySQL\MySQL 5.1\data\).
So, after I exported the data from the old MySQL Server version I tried importing it to the MySQL 5.1 using phpMyAdmin.
The file to import was 42MB in size, so I had to set some PHP configuration variables (in php.ini file) to greater values:

post_max_size = 64M
upload_max_filesize = 64M

At first it looked like the phpMyAdmin import script entered a loop or something, as it wouldn’t stop even after running for several minutes and, as I was looking into the data files it was producing, no new files appeared. It was like it blocked on a table with a large number of records, which didn’t make any sense. Then I restarted the Apache server and I tried the import all over again. The same thing was happening. I finally decided to let it run for more time and the script finally stopped. But the data imported was incomplete; a part of the records in the large table I thought script blocked on, and every table and database from there on were missing, with no PHP or MySQL error returned.
Then I thought the script needed even more time to run, so I increased the value of the PHP configuration variable max_execution_time, but with the same result.

The solution. It seems that the execution time limit for the import script in phpMyAdmin is defined by the variable $cfg[‘ExecTimeLimit’] in <path_to_phpMyAdmin>/libraries/config.default.php and the value of this variable should be a lot greater than its default value of 300 seconds when importing a great amount of data. In my case it needed about an hour (3600 seconds) to complete. So you have to set this variable depending on the amount of data you are importing.
You might also need to set the MySQL configuration variable max_allowed_packet (in my case, in C:\Program Files\MySQL\MySQL Server 5.1\my.ini) to a greater value, if you have large queries in the data file you want to import, for avoiding MySQL error 2006, ‘mysql server has gone away’.

mysqldump – with exec() function from php outputs empty file

This error occurs on any operating system (windows, linux). The problem is that instead of getting a sql file with the database data you get a empty (0 kb.) file.

So we have the following code:

$command = "mysqldump --opt --skip-extended-insert --complete-insert -h ".$DB_HOST." -u ".$DB_USER." -p ".$DB_PASS." ".$DB_NAME." > backup.sql";

exec($command, $ret_arr, $ret_code);
echo "ret_arr: <br />";
print_r($ret_arr);

and we get an empty file and no output.

So we will fix this error in a few steps:

1. First we need to make sure that we have access to mysqldump command. For Linux machines this command is accessible from anywhere if not you will have to find the place where mysqldump file is (usually the bin folder of mysql).

In order to do this we have to get some output from our command so we will strip all the options from the command and we will remain with this:

$command = "mysqldump"; // mysqldump.exe on Windows

So execute the php script. It’s ok if you get output like this:

Array
(
    [0] => Usage: mysqldump [OPTIONS] database [tables]
    [1] => OR     mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
    [2] => OR     mysqldump [OPTIONS] --all-databases [OPTIONS]
    [3] => For more options, use mysqldump --help
)

If you don’t see something like that then you must check to see the path to the mysqldump command.

If you are in windows make sure you append the full path to the command. If you have a folder like I have C:\\Program Files\\MySQL\\MySQL Server 4.1\\bin\\mysqldump.exe with spaces in it you must make sure that you enclose the command between quotes like this:

$command = "\"C:\\Program Files\\MySQL\\MySQL Server 4.1\\bin\\mysqldump.exe\" --opt --skip-extended-insert --complete-insert -h ".$DB_HOST." -u ".$DB_USER." -p ".$DB_PASS." ".$DB_NAME." > backup.sql";

If append the right path to the command and you still cannot get the output then this article can’t help.

2. Make sure you have the rights to create the sql file. This step is mostly for Linux machines where it is very possible that you may try to create a file from php in a folder where you don’t have writing rights.

So to test this after the previous step is done you can do the following: append to the previous command extra options so that the output is not returned but instead written in a file. So we have the previous command:

In Windows:

$command = "\"C:\\Program Files\\MySQL\\MySQL Server 4.1\\bin\\mysqldump.exe\" > backup.sql";

In Linux:

$command = "mysqldump > backup.sql";

After running the file “backup.sql” should  be created.

3.  You must now correct your statement. This means that we must use the long versions of the options like this:

Windows:

$command = "\"C:\\Program Files\\MySQL\\MySQL Server 4.1\\bin\\mysqldump.exe\" --opt --skip-extended-insert --complete-insert --host=".$DB_HOST." --user=".$DB_USER." --password=".$DB_PASS." ".$DB_NAME." > backup.sql";

Linux:

$command = "mysqldump --opt --skip-extended-insert --complete-insert --host=".$DB_HOST." --user=".$DB_USER." --password=".$DB_PASS." ".$DB_NAME." > backup.sql";

The fix: The options for mysqldump when called from php must be in the longer version. Instead of –u use –user, instead of –p use –password and so on.

#1005 – Can’t create table

Full error message: #1005 – Can’t create table ‘.\my_db\#sql-7c4_444.frm’.

Using MySQL version 4.1.22-community-nt, I created two tables (`table1` and `table2`) in a database (let’s call it `my_db`) as follows:

CREATE TABLE `table1` (
`idtable1` int(10) unsigned NOT NULL auto_increment,
`table1_str` varchar(50) NOT NULL default '',
PRIMARY KEY  (`idtable1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `table2` (
`idtable2` int(10) unsigned NOT NULL auto_increment,
`idtable1_fk` int(10) NOT NULL,
`table2_str` varchar(50) NOT NULL default '',
PRIMARY KEY  (`idtable2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Then I tried to add a foreign key constraint like this:

ALTER TABLE `table2`
ADD CONSTRAINT `table2_ibfk_1` FOREIGN KEY (`idtable1_fk`) REFERENCES `table1` (`idtable1`) ON DELETE CASCADE ON UPDATE CASCADE;

And then I got the error.

The solution in my case was adding the unsigned attribute to the `idtable1_fk` field in `table2` for having the same type as the field `idtable1` it references in `table1`:

ALTER TABLE `table2` CHANGE `idtable1_fk` `idtable1_fk` int(10) unsigned NOT NULL;

After that I ran the foreign key constraint query:

ALTER TABLE `table2`
ADD CONSTRAINT `table2_ibfk_1` FOREIGN KEY (`idtable1_fk`) REFERENCES `table1` (`idtable1`) ON DELETE CASCADE ON UPDATE CASCADE;

And then it worked. But if you don’t have the same problem but you get the same error message you might already have a foreign key constraint with the given name. For example, if I run again the foreign key constraint query I will get the same error. Be careful if you use phpMyAdmin as a visual interface for MySQL, because it seems to me that it does not show us all the foreign key constraints we added to a table. If you want to see which foreign key constraints a table has, you could export the structure of that table and analyze the foreign key constraints queri(es).

Hope this works for you, too.

Conclusion: We should make sure that the possible values of the foreign key field are in the same range as the possible values of the field referenced by that foreign key and that there is no foreign key constraint with the same name as the constraint we are trying to add.

How to use specific language characters with PHP and MySQL (example: Romanian)

Problem: Using specific characters from European languages like Romanian, Bulgarian, Czech and so on (usually the ones without support in ISO 8859-1) rises errors when displaying the content in browsers turning special characters in unrecognizable ones.

My fix for this problem is using UTF-8 character set encoding for every page of the website and the MySQL tables that contain the fields you are using. Also all the html encodings from PHP use the UTF-8 character set encoding (this is not mandatory).

If you already have the database, but with the default character set (latin1) and collation (latin1_swedish_ci) for the tables with text fields (of type CHAR, VARCHAR, TEXT etc) in which you need to have special characters, you should change the character set of each of those tables like this:

ALTER TABLE my_table CONVERT TO CHARACTER SET utf8;

If you don’t have the database then you should create it and when you create a table that you need to use with specific language characters, you should specify the character set for that table:

CREATE TABLE `my_table` (
`idmy_table` tinyint(3) unsigned NOT NULL auto_increment,
`my_field` varchar(255) NOT NULL default '',
PRIMARY KEY  (`idmy_table`)
) CHARSET=utf8;

The most important thing is that in PHP, after opening a database connection, before executing any query to the database, you should ensure that this code is executed

mysql_query("SET NAMES utf8", $my_conn);

This tells the server what character set the client is using for sending SQL statements and the character set the server should use to return the results to the client.

A simple example:

<?php
$my_conn = @mysql_connect("localhost", "user", "pass")
or die("There was a problem connecting to MySQL. Please try again later.");
if(!@mysql_select_db("test", $my_conn))
{
die ("There was a problem connecting to the database. Please try again later.");
}
mysql_query("SET NAMES utf8", $my_conn);
if(!empty($_GET['mystr']))
{
// insert the string into the database
$str = htmlspecialchars($_GET['mystr'], ENT_QUOTES, "UTF-8");
$query = "INSERT INTO my_table_t (my_field) VALUES('".$str."')";
$result = mysql_query($query, $my_conn);
if($result)
{
// save the id of the table row inserted
$last_insert_id = mysql_insert_id($my_conn);
// get the last inserted value
$query = "SELECT my_field FROM my_table_t WHERE idmy_table = '".$last_insert_id."'";
$result = mysql_query($query, $my_conn);
if($result && $row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$db_string = $row['my_field'] ;
}
}
}
elseif(!empty($_GET['searchstr']))
{
$str = htmlspecialchars($_GET['searchstr'], ENT_QUOTES, "UTF-8");
$query = "SELECT * FROM my_table_t WHERE my_field LIKE '%".$str."%'";
$result = mysql_query($query, $my_conn);
if($result)
{
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$search_results[$row['idmy_table']] = $row['my_field'];
}
}
}
mysql_close($my_conn);
?>
<html>
<head>
<title>Page title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<body>
<?php
if(!empty($db_string))
{
echo "<strong>Inserted string</strong>: $db_string<br />";
}
?>
<form method="get" action="">
String to insert into the database <input type="text" name="mystr"/>
<input type="submit" value="GO"/>
</form>
<?php
if(!empty($search_results))
{
echo "<strong>Search results</strong>:<br />";
foreach($search_results as $id => $value)
{
echo $value."<br />";
}
}
?>
<form method="get" action="">
Search query <input type="text" name="searchstr"/>
<input type="submit" value="GO"/>
</form>
</body>
</html>

Tip: The search in Romanian language over the database (tested with MySQL LIKE operator) works like a charm when searching words that have special characters or not.

For example: In Romanian language the word “peasant” is written as “ţăran” and someone who searches it gets the same result for the search terms “taran” or “ţăran” or “ţaran” or “tărân” and so on – so this is the real magic.

UPDATE: You may also need to add a header to the php script if you use ob_start or similar php functions like this:

header("Content-type: text/html; charset=UTF-8");

this usually fixes the encoding selection in Internet Explorer for this case.

org.hibernate.HibernateException: identifier of an instance of members.Appointment was altered from 8 to 8

Full error message:

Exception occurred during event dispatching:
org.hibernate.HibernateException: identifier of an instance of members.Appointment was altered from 8 to 8
at org.hibernate.event.def.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:58)
at org.hibernate.event.def.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:157)
at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:113)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:196)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at members.AppointmentDialog.jButtonSaveActionPerformed(AppointmentDialog.java:279)
at members.AppointmentDialog.access$000(AppointmentDialog.java:21)
at members.AppointmentDialog$1.actionPerformed(AppointmentDialog.java:101)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:5517)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
at java.awt.Component.processEvent(Component.java:5282)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3984)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:153)
at java.awt.Dialog$1.run(Dialog.java:535)
at java.awt.Dialog$2.run(Dialog.java:563)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.Dialog.show(Dialog.java:561)
at java.awt.Component.show(Component.java:1302)
at java.awt.Component.setVisible(Component.java:1255)
at admin.AdminOptionsForm.jButtonSetAppointmentActionPerformed(AdminOptionsForm.java:238)
at admin.AdminOptionsForm.access$800(AdminOptionsForm.java:24)
at admin.AdminOptionsForm$9.actionPerformed(AdminOptionsForm.java:145)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:5517)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
at java.awt.Component.processEvent(Component.java:5282)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3984)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

In Java, I had a class Appointment mapped to a MySQL table `appointment` using Hibernate as follows:

<hibernate-mapping>
<class name="members.Appointment" table="appointment">
<id name="idAppointment" column="idappointment" type="short">
<generator class="native"/>
</id>
<many-to-one name="member" column="idmember" not-null="true" foreign-key="fk_idmember"/>
<property name="startDate" type="timestamp" column="start_date"/>
<property name="duration" type="short" column="duration" length="3"/>
<property name="cancelled" type="boolean"/>
</class>
</hibernate-mapping>

I was getting the error when inserting a new appointment into the database.

The problem was that the idAppointment member variable in the Java class and the idappointment field in the MySQL database table were of the type int. So why the hell did I have the type short in the mapping? The answer is simple: because of the copy paste. So the correct code is:

<id name="idAppointment" column="idappointment">
<generator class="native"/>
</id>

Conclusion: copy paste is sometimes evil.

java.sql.SQLException: Cannot convert value ‘0000-00-00 00:00:00’ from column 9 to TIMESTAMP

Full error message:

Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not execute query
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.doList(Loader.java:2223)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at admin.MembersTableModel.<init>(MembersTableModel.java:43)
at admin.AdminOptionsForm.initComponents(AdminOptionsForm.java:98)
at admin.AdminOptionsForm.<init>(AdminOptionsForm.java:32)
at managemembers.Main.main(Main.java:45)
Caused by: java.sql.SQLException: Cannot convert value '0000-00-00 00:00:00' from column 9 to TIMESTAMP.
at com.mysql.jdbc.ResultSet.getTimestampFromBytes(ResultSet.java:6864)
at com.mysql.jdbc.ResultSet.getTimestampInternal(ResultSet.java:6899)
at com.mysql.jdbc.ResultSet.getTimestamp(ResultSet.java:6218)
at com.mysql.jdbc.ResultSet.getTimestamp(ResultSet.java:6256)
at com.mchange.v2.c3p0.impl.NewProxyResultSet.getTimestamp(NewProxyResultSet.java:3394)
at org.hibernate.type.TimestampType.get(TimestampType.java:30)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:163)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:154)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:81)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2096)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1380)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1308)
at org.hibernate.loader.Loader.getRow(Loader.java:1206)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:580)
at org.hibernate.loader.Loader.doQuery(Loader.java:701)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)
... 11 more

My example:

// the Java class

public class Member  {
// some private member attributes
private Date addedDate;
// proper getter and setter methods
}

<!– the Hibernate mapping–>

<hibernate-mapping>
<class name="managemembers.Member" table="member">
<!-- some mappings here-->
<property name="addedDate" type="timestamp" column="added_date"/>
</class>
</hibernate-mapping>

# The MySQL table

CREATE TABLE `member` (
# some fields here
`added_date` DATETIME,
) ;

So I was mapping a java.util.Date field in the POJO to a MySQL DATETIME field.

The error occured while I was trying to retrieve the data from the member database table.

The problem was that I had DATETIME values in the database with all-zero components (0000-00-00 …), so the solution was to set all the added_date field values with all-zero components to NULL and to be careful to set a valid DATETIME value or NULL into the added_date field each time I inserted a new row.

Conclusion: You have 2 choices: either set the date field in the table to a NULL value either set it to a valid date.