Form Validation w/ sql + codeigniter - php

I'm working on creating a callback function in codeigniter to see if a certain record exists in the database, and if it does it'd like it to return a failure.
In the controller the relevent code is:
function firstname_check($str)
{
if($this->home_model->find_username($str)) return false;
true;
}
Then in the model I check the database using the find_username() function.
function find_username($str)
{
if($this->db->get_where('MasterDB', array('firstname' => $str)))
{
return TRUE;
}
return FALSE;
}
I've used the firstname_check function in testing and it works. I did something like
function firstname_check($str)
{
if($str == 'test') return false;
true;
}
And in that case it worked. Not really sure why my model function isn't doing what it should. And guidance would be appreciated.

if($this->home_model->find_username($str)) return false;
true;
Given that code snippet above, you are not returning it true. If that is your code and not a typo it should be:
if($this->home_model->find_username($str)) return false;
return true;
That should fix it, giving that you did not have a typo.
EDIT:
You could also just do this since the function returns true/false there is no need for the if statement:
function firstname_check($str)
{
return $this->home_model->find_username($str);
}

So the solution involved taking the query statement out of if statement, placing it into a var then counting the rows and if the rows was > 0, invalidate.
Although this is a more convoluted than I'd like.

I find your naming kind of confusing. Your model function is called 'find_username' but it searches for a first name. Your table name is called 'MasterDB'. This sounds more like a database name. Shouldn't it be called 'users' or something similar? I'd write it like this :
Model function :
function user_exists_with_firstname($firstname)
{
$sql = 'select count(*) as user_count
from users
where firstname=?';
$result = $this->db->query($sql, array($firstname))->result();
return ((int) $result->user_count) > 0;
}
Validation callback function :
function firstname_check($firstname)
{
return !$this->user_model->user_exists_with_firstname($firstname);
}

Related

Protect routes dynamically, based on id (laravel, pivot table)

This topic has been discussed a lot here, but I don't get it.
I would like to protect my routes with pivot tables (user_customer_relation, user_object_relation (...)) but I don't understand, how to apply the filter correctly.
Route::get('customer/{id}', 'CustomerController#getCustomer')->before('customer')
now I can add some values to the before filter
->before('customer:2')
How can I do this dynamically?
In the filter, I can do something like:
if(!User::hasAccessToCustomer($id)) {
App::abort(403);
}
In the hasAccessToCustomer function:
public function hasCustomer($id) {
if(in_array($id, $this->customers->lists('id'))) {
return true;
}
return false;
}
How do I pass the customer id to the filter correctly?
You can't pass a route parameter to a filter. However you can access route parameters from pretty much everywhere in the app using Route::input():
$id = Route::input('id');
Optimizations
public function hasCustomer($id) {
if($this->customers()->find($id)){
return true;
}
return false;
}
Or actually even
public function hasCustomer($id) {
return !! $this->customers()->find($id)
}
(The double !! will cast the null / Customer result as a boolean)
Generic approach
Here's a possible, more generic approach to the problem: (It's not tested though)
Route::filter('id_in_related', function($route, $request, $relationName){
$user = Auth::user();
if(!$user->{$relationName}()->find($route->parameter('id')){
App::abort(403);
}
});
And here's how you would use it:
->before('id_in_related:customers')
->before('id_in_related:objects')
// and so on

codeigniter returning false from models

Just wondering if it is necessary to use else {return false;} in my codeigniter model functions or if () {} is enough and it returns false by default in case of failure?
controller:
if ($this->model_a->did()) {
$data["results"] = $this->model_a->did();
echo json_encode($data);
}
model:
public function did()
{
//some code here
if ($query && $query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
in your controller -- test the negative condition first - if nothing came back from the method in your model
if ( ! $data["results"] = $this->model_a->did() ) {
$this->showNoResults() ; }
else { echo json_encode($data); }
so thats saying - if nothing came back - then go to the showNoResults() method.
If results did come back then its assigned to $data
However - in this situation in the model i would also put ELSE return false - some people would say its extra code but for me it makes it clearer what is happening. Versus methods that always return some value.
I think this is more of a PHP question than a CodeIgniter question. You could easily test this by calling your model methods and var_dump-ing the result. If you return nothing from a method in PHP, the return value is NULL.
As much i have experience in CI returning false is not a plus point, because if you return false here then you need to have a condition back in controller which is useless you should be doing like this will save you at least some code of lines
if ($query && $query->num_rows() > 0) {
return $query->result_array();
} else {
return array();
}
so returning an array will save you from many other errors, like type error.

Getting the value of a row in CodeIgniter

I am trying to get the value of a row in the database but not working out that well. I not sure if can work like this.
I am just trying to get the value but also make sure it from the group config and the key.
Model
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Want to be able to return any thing in the value
))->row();
}
In the controller I would do this:
function index() {
$data['title'] = $this->document->getTitle();
$this->load->view('sample', $data);
}
First, you have this line set to this:
$data['title'] $this->document->getTitle();
That should be an = assignment for $this->document->getTitle(); like this:
$data['title'] = $this->document->getTitle();
But then in your function you should actually return the setting value from your query with row()->setting:
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Should return this row information but can not.
))->row()->setting;
}
But that said, I am unclear about this:
->where('value'=> ) // Should return this row information but can not.
A WHERE condition is not a SELECT. It is a condition connected to a SELECT that allows you to SELECT certain values WHERE a criteria is met. So that should be set to something, but not really sure what since your code doesn’t provide much details.
Found Solution Working Now. For Getting Single Item From Database In Codeigniter
Loading In Library
function getTitle($value) {
$this->CI->db->select($value);
$this->CI->db->where("group","config");
$this->CI->db->where("key","config_meta_title");
$query = $this->CI->db->get('setting');
return $query->row()->$value;
}
Or Loading In Model
function getTitle($value) {
$this->db->select($value);
$this->db->where("group","config");
$this->db->where("key","config_meta_title");
$query = $this->db->get('setting');
return $query->row()->$value;
}

Using if statement in PHP

I would like to do these actions step by step:
first DB update
copy file
unlink file
second DB update
It is working, but I don't know if my code is correct/valid:
$update1 = $DB->query("UPDATE...");
if ($update1)
{
if (copy("..."))
{
if (unlink("..."))
{
$update2 = $DB->query("UPDATE ...");
}
}
}
Is it possible to use if statement this way?
I found that it is usually used with PHP operators and PHP MySQL select, for example:
$select = $DB->row("SELECT number...");
if ($select->number == 2) {
...
}
Sure, your ifs work fine. What would look and flow better would be using a function like this:
function processThings() {
// make sure anything you use in here is either passed in or global
if(!$update1)
return false;
if(!$copy)
return false;
if(!$unlink)
return false;
if(!$update2)
return false;
// you made it!
return true;
}
make sure you call $DB as a global variable, plus pass in whatever strings you need etc etc

Two different functions one works one calls a non-object

I have two functions getCompanyDetails and getHostingDetails
The first database getCompanyDetails works fine but the getHostingDetails shows
Trying to get property of non-object
getCompanyDetails:
Controller: $data['companyName'] = $this->quote->getCompanyDetails()->companyName;
Model:
public function getCompanyDetails()
{
$this->db->select('companyName,companySlogan,companyContact,
companyEmail,companyWebsite,companyPhone,
companyFax,companyAddress');
$this->db->from('companyDetails');
$result = $this->db->get();
if($result->num_rows()<1)
{
return FALSE;
}else{
return $result->row();
}
}
getHostingDetails:
Controller:
$data['hostingRequired'] = $this->quote->getHostingDetails()->hostingRequired;
Model:
public function getHostingDetails()
{
$this->db->select('hostingRequired,domainRequired,domainToBeReged,
domaintoBeReged0,domainTransfer,domainToBeTransfered,
domainToBeTransfered0,currentHosting');
$this->db->from('hostingDetails');
$result = $this->db->get();
if($result->num_rows()<1)
{
return FALSE;
}else{
return $result->row();
}
}
Well, one method returns an object from $result->row() and the other false. You can't call a method on false.
false is returned when no record is found. So you need to check the return value before using it.
Well in your get functions chances is your code might return you false if there is no rows returned. You might want to check before retrieving the details. Example:
$details = $this->quote->getHostingDetails();
if($details){
$data['hostingRequired'] = $details->hostingRequired;
}
The problem is probably how you use those functions in your controller. If any of them returns FALSE, then
$this->quote->getHostingDetails()->hostingRequired;
is going to give you errors. Try
if ($row = $this->quote->getHostingDetails()) {
echo $row->hostingRequired;
}

Categories