0

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?

3 Answers 3

2

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');
Sign up to request clarification or add additional context in comments.

Comments

0

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.
}

1 Comment

Thanks for the answer Martijn, but i was asking if there were another way to accomplish this maybe something built-in inside codeigniter!
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.