I created the following table for user to user subscriptions.
CREATE TABLE IF NOT EXISTS `subscriptions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`subscribed_to` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_subscription` (开发者_如何学JAVA`user_id`,`subscribed_to`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=76 ;
I'm disallowing identical rows by making the columns user_id
and subscribed_to
unique. If a user tries to resubmit the same data I get:
A Database Error Occurred Error Number: 1062
Duplicate entry '62-88' for key 'unique_subscription'
INSERT INTO subscriptions (user_id, subscribed_to, date) VALUES ('62', '88', '2011-07-11 19:15:13')
Line Number: 330
I'm preventing the database error by checking if an identical row exists before trying to insert data.
$query = "SELECT COUNT(*) FROM subscriptions WHERE (user_id = '62' AND subscribed_to = '88')";
if ($query > 0)
{
//display already subscribed message
}
else
{
//insert new row
}
The database already checks the table and returns an error. The select count(*)
query above seems redundant. Do I really need to check the table once more in my application? Is there a way to capture the database error if it occurs, and do something with that in my application?
If you have an idea how please share an example. I haven't a clue how this is done..!
Check out PHP function mysql_error
You can wrap the db call within a try catch
statement for functions that throw exceptions to prevent your application from crashing.
PHP function mysql_query
does not throw exception on error, but returns FALSE
. You can check the return value and execute mysql_error
to find out the trouble or log it.
精彩评论