Condition Using Controller in Code Igniter - codeigniter

I'm trying to create a function, it exists and does not exist in the search feature. Condition does not exist, will display Error 404. Condition, exists. Then it will display from search. But in the code I wrote, it only shows Error 404.
This is my model:
function search_album($keyword){
$result=$this->db->query("SELECT tbl_album.*,DATE_FORMAT(album_date,'%d %M %Y') AS date FROM tbl_album WHERE album_title LIKE '%$keyword%'");
return $result;
}
This is my controller:
function search(){
$keyword=str_replace("'", "", $this->input->post('xfilter',TRUE));
$x['data']=$this->model_album->search_album($keyword);
if(empty($x) && empty($keyword)){
$this->load->view('view_contents',$x);
}
else if (!empty($x) && !empty($keyword)){
$this->load->view('view_error_404');
}
}
I've tried from this source, but it doesn't work. Can you help me?

There are several errors in your code:
ONE: You have interchanged your if statements. Like, if the search did not return any data and the keyword was not supplied, it is supposed to display the "view_error_404", otherwise, it is supposed to load data into the view "view_contents".You did the vice versa I have corrected that for you in the code below.
TWO: You are checking if $x is empty which will never be empty as you have initialized $x['data']. Note that the model can return empty data, such that $x['data'] is empty. Instead, check if the search result is empty by replacing empty($x) with empty($x['data'])
THREE: In your model, you are returning the query builder class, but not the actual data from the query statement. instead, replace return $result; with return $result->result();
FOUR:
From your if statements, you need to add an else statement so that if the 2 conditions are never met, it can execute. With your current implementation, there is a state which will not meet first or second conditions and will lead to a blank screen.
if(empty($x['data']) && empty($keyword)){
$this->load->view('view_error_404');
}else if (!empty($x['data']) && !empty($keyword)){
$this->load->view('view_contents',$x);
}else{
$this->load->view('view_error_404'); // replace this code with your preference
}

you need to mention search function in routes.php file like this:-
$routes['search'] ='your_controller_name/search';

without knowing your function model_album->search_album($keyword) and assuming it returns a string or array, you don't need to worry about checking for the keyword, since without a keyword the function should return false or empty.
anyway you mixed up your if/else conditions, since you are checking for not empty results to return a 404, instead of empty result returning the 404.
this should do it:
if(empty($x)){
$this->load->view('view_error_404');
}
else {
$this->load->view('view_contents',$x);
}

Related

Assign value to a variable using || operator with if condition in Ruby

I am trying to write logic for a search query. There are many different conditions with different parameters. One parameter sent from form is code. So there are code values in two different tables: competitions and responses. What I need is to check the params[:code] value first in competitions table and if it does not exist then check in responses table. If it does not exist in either table then it should return nil. I am trying to write it in a single if statement. The code I tried is below:
competitions = Competition.includes(:event, :responses)
if params[:code].present?
competitions = (competitions.where(code: params[:code])) ||
(competitions.joins(:responses).where(responses: { code: params[:code] }))
The above code checks only the value of competitions.where(code: params[:code]). If that value is [], then it is not evaluating the second condition. What changes should I do to make the above code work as per the requirements mentioned above?
competitions.where(code: params[:code]) returns a Relation object which is always truthy.
Luckily enough, it implements #presence method, returning either the value if it’s not blank, or nil. So, this should work:
competitions.where(code: params[:code]).presence || ...

dd works but echo does not for an object passed as a parameter to a function in Laravel

I passed an object in a function in laravel.
I tried to assign the value of a property to a variable. It pops an error.
When I tried to figure out what was going on I tried to dd ()the value it worked.
But when I tried to echo the same it does not.
What am I mising.
On using this,
location1 and location2 are two objects of the location class.
The function is here:
function geodistance($location1,$location2){
dd($location1->lat);
$lat1=$location1->lat;
}
it prints
"28.612072"
But when I change the same function to
function geodistance($location1,$location2){
echo($location1->lat);
$lat1=$location1->lat;
}
The output error is:
Trying to get property 'lat' of non-object
Even the function
function geodistance($location1,$location2){
echo $location1->lat;
$lat1=$location1->lat;
}
gives the same output
The aim to remind you is to assign the value to a variable like so.
function geodistance($location1,$location2){
$lat1=$location1->lat;
}
When I echo $location1 from within the function geodistance() gives out and error which makes sense.
function geodistance($location1,$location2){
echo $location1;
$lat1=$location1->lat;
Object of class App\MyClasses\city could not be converted to string
When I dd ($location1 from the funciton like so it gives the right result.
function geodistance($location1,$location2){
dd($location1);
$lat1=$location1->lat;
like so:
city {#13410 ▼
+id: 2245
+info: "{}"
+name: "New Delhi"
+lat: "28.612072"
+lon: "77.22978"
+timezone: null
+weightedrating: null
+country_id: 1
}
It seems i am missing out something very trivial. :(
As pointed out by #salman zafar and #apokryfos, the mistake was that I was passing an array.
When I was doing a dd, after processing the first data the programme was terminated.
The array that was passed was not completely correct. The last data point in my array was not an object of the same class.
So the data ended up being corrupted when using echo. Echo would print one data after another but eventually it would get a wrong input.
The best way to catch these errors (after so much experimenting) is to write the values of the variable in a text file on each iterartion.
What that does is that it catches the error in your text file and u get to know after how many iterations the programme stopped.
Hope this helps others from making such obviously glaring mistakes which are tough to catch (atleast for me since this was the first of such errors)

Xquery - return only distinct attributes from if/then

I've been trying to write a query to get distinct attribute values after using if/then to determine whether I'll use the element in the first place. Here's my example xml and the query i've written so far:
<donors>
<donor donor_id="x21" cn_id="x12">
<homeless>$1201</homeless>
<conservation>$300</conservation>
<cancerResearch>$250</cancerResearch>
</donor>
<donor donor_id="x23" cn_id="x13">
<homeless>$121</homeless>
<conservation>$30</conservation>
<cancerResearch>$50</cancerResearch>
</donor>
<donor donor_id="x24" cn_id="x14">
<homeless>$1201</homeless>
<cancerResearch>$250</cancerResearch>
</donor>
<donor donor_id="x25" cn_id="x12">
<homeless>$1201</homeless>
<conservation>$300</conservation>
<cancerResearch>$250</cancerResearch>
</donor>
</donors>
I want to first get all donors who have a child "conservation". I've done the following for that:
<conservationists>
{
for $x in //donor
return
if(exists($x/conservation))
then <conservationist cn_id="{$x/#cn_id}/>
else ()
}
</conservationists>
I tried wrapping the whole thing in distinct-values but that just gave nothing, and every where else I tried doing something to that effect I just ended up with an end tag.
This is one possible way :
<conservationists>
{
for $x in distinct-values(//donor[conservation]/#cn_id)
return
<conservationist cn_id="{$x}"/>
}
</conservationists>
xpathtester demo
The expression distinct-values(//donor[conservation]/#cn_id) returns distinct values of cn_id attribute from donor elements that have at least one conservation child element.

How to show in CodeIgniter only the second parameter in form validation message?

E.g. I have this line in my language form_validation file:
$lang['min_length'] = "%s must be at least %s characters in length.";
And I want the output to be like this:
$lang['min_length'] = "This field must be at least %s characters in length.";
However, the problem is that it looks like this when echoed:
This field must be at least Your name characters in length.
which is wrong because it takes the first %s instead of the second %s.
How can I force CI to take the second %s? Is it possible?
Since the min_length is a standard function in the Form Validation Library and treated through this library, you can only do so by changing the core library.
But there is an easier way - using a callback function with the Form Validation Library:
$this->form_validation->set_rules('your_field', 'The Field label', 'callback_my_min_length[10]');
Then within your controller, add this:
public function username_check($str, $min_length)
{
if ( mb_strlen($str) >= $min_length)
{
return TRUE;
}
else
{
$this->form_validation->set_message('my_min_length', 'This field must be at least '.$min_length.' characters in length.');
return FALSE;
}
}
This is how I would do it.

Codeigniter: URI segments

How do I create an if statement saying something like this?
Basically, how do you use the URI class to determine if there is a value in any segment?
$segment = value_of_any_segment;
if($segment == 1{
do stuff
}
I know this is pretty elementary, but I don't totally understand the URI class...
Your question is a little unclear to me, but I'll try to help. Are you wondering how to determine if a particular segment exists or if it contains a specific value?
As you are probably aware, you can use the URI class to access the specific URI segments. Using yoursite.com/blog/article/123 as an example, blog is the 1st segment, article is the 2nd segment, and 123 is the 3rd segment. You access each using $this->uri->segment(n)
You then can construct if statements like this:
// if segment 2 exists ("articles" in the above example), do stuff
if ($this->uri->segment(2)) {
// do stuff
}
// if segment 3 ("123" in the above example) is equal to some value, do stuff
if ($this->uri->segment(3) == $myValue) {
// do stuff
}
Hope that helps! Let me know if not and I can elaborate or provide additional information.
Edit:
If you need to determine if a particular string appears in any segment of the URI, you can do something like this:
// get the entire URI (using our example above, this is "/blog/article/123")
$myURI = $this->uri->uri_string()
// the string we want to check the URI for
$myString = "article";
// use strpos() to search the entire URI for $myString
// also, notice we're using the "!==" operator here; see note below
if (strpos($myURI, $myString) !== FALSE) {
// "article" exists in the URI
} else {
// "article" does not exist in the URI
}
A note regarding strpos() (from the PHP documentation):
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
I hope my edit helps. Let me know if I can elaborate.

Resources