Reputation: 2775
I'm creating a web application using codeigniter and postgresql. I have this inside my database:
user
id name
unique(name)
When someone try to register with the same name, i get an error. How can i handle them, without displaying the codeigniter's error and showing instead my custom error?
If i set $db['default']['db_debug'] = FALSE;
i don't get any error of course, but is there a way to handle the db error or should i check myself if the table already contains an entry with that same name?
Upvotes: 0
Views: 4523
Reputation: 125
Use Codeigniters form validation class. is_unique[table.columnName]. This will do the work for you. Below is an example
$this->form_validation->set_rules('name', 'Name', 'is_unique[table_name.Name]');
Then just set a custom message referencing the is_unique validation like below
$this->form_validation->set_message('is_unique', 'Name already exists');
Upvotes: 2
Reputation: 16103
I dont know anything by codeigniter, but im going to assume the principle works the same:
You first make a query like SELECT id FROM tablename WHERE name='SomeName' LIMIT 1
, then you check the number of rows. This kind of checking is fairly normal. Control as much as you (sensebly) can to avoid errors down the road.
Zero rows? Safe to insert. Not zero rows? Display something like 'username allready taken'.
Example with some code:
$check = mysqli_query("SELECT id FROM tablename WHERE name='SomeName' LIMIT 1");
if( $check->num_rows!==0 ){
echo 'Username allready taken'; // echo is bad, you should process this better, but this is easy demo
}
else{
// Your normal inserting code goes here.
}
Upvotes: 0
Reputation: 486
Like Martijn said, it is a solution.
CI doesn't throw exception, so when you perform a query, it will return NULL if the statement fails.
You may want to see CodeIgniter - how to catch DB errors?
Upvotes: 0