...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
July 23, 2013

How to call a function of a class from other function file?

Mollo’s Question:

I know thats not the best title for my question but I coulnd’t come up with a better one (Suggestions are welcome)

Well, this is my situation, I have 3 files:

1) classDBConn.php – In this file is where I connect to the DB and have some functions like this:

class DBConn{
var $conexion;
private $querySql;
var $respuesta;
var $resultado;
function __construct() { 
    $this->conexion = @mysqli_connect('localhost', 'root', 'pass', 'dataBase');
    if(!$this->conexion){
        die('error de conexion('.mysqli_connect_errno().')'.mysqli_connect_error());    
    }
}
function checkBracketGanador($id_torneo){
    $this->querySql = "SELECT COUNT(id_ganador) FROM brackets WHERE id_torneo = '$id_torneo'";
    $this->respuesta = mysqli_query($this->conexion,$this->querySql);
    $this->resultado = mysqli_fetch_array($this->respuesta);
    return $this->resultado[0];
}
// More functions with queries

Note: queries and functions are fine

2)inc_conf.php – In this file is where I create the session and object DBConn. Code:

session_start();
include('classDBConn.php');
$functionsDBConn= new DBConn();
$id_usuario = isset($_SESSION["IDUSUARIO"]) ? $_SESSION["IDUSUARIO"] : false;

3) workingOn.php – In this file is where I make calls to DBConn in order to use those queries. If I do a call like this is just fine:

$res = $functionsDBConn->checkBracketGanador($id_torneo);
echo $res;

But, if I do it inside a function is where everything goes wrong

function test(){
    $res = $functionsDBConn->checkBracketGanador($id_torneo);
    return $res;
}
$a = test();
echo $a;

I keep getting this error:

Fatal error: Call to a member function checkBracketGanador() on a non-object in …/someFolder/workingOn.php on line 67

I’ve tried making public functions in classDBConn but didn’t work

What I’m doing is calling the function outside the function and sending the result as a parameter to the other function but thats exactly what I want to avoid

Any help is appreciate. Thanks in advance.

This is to do with scope.

I assume you instantiate $functionsDBConn = new DBConn(); outside the function at the same level as

$a = test();

If so you have 2 options

One:

function test(){
    global $functionsDBConn;
    $res = $functionsDBConn->checkBracketGanador($id_torneo);
    return $res;
}

$functionsDBConn = new DBConn();
$a = test();
echo $a;

Two:

function test(&$functionsDBConn){
    $res = $functionsDBConn->checkBracketGanador($id_torneo);
    return $res;
}
$functionsDBConn = new DBConn();
$a = test($functionsDBConn);
echo $a;

Basically you have to make the object you instantiated visible within the scope of your test() function by either telling the test() function it is available within the global scope global $functionsDBConn; or passing it into the function as a parameter.

You could also make checkBracketGanador() a static method but lets not get to complex all in a rush.

Use global keyword inside the function. The variable inside the function will not call values outside its scope.

function test(){
    global $functionsDBConn;
    $res = $functionsDBConn->checkBracketGanador($id_torneo);
    return $res;
}
Read more

How to get value from text input on blur of field

Sehummel’s Question:

I’m trying to write some Javascript to get the value from two text inputs, which should be fairly straightforward. But something is amiss. Here is my code:

<script>
    jQuery(function() {
        jQuery('#fromPicker, #toPicker').datepicker({ dateFormat : 'yy-mm-dd' });

        jQuery('#submit').attr('disabled', 'disabled');

        jQuery('#toPicker').on('blur', function() {
            var fromDate = jQuery('#fromPicker').val();
            var toDate = jQuery('#toPicker').val();
            console.log(toDate);

            if (fromDate !== '' && toDate !== '') {
                if (isValidDate(fromDate) && isValidDate(toDate)) {
                    jQuery('#submit').removeAttr('disabled');
                } else {
                    alert('You must enter dates in the format "yyyy-mm-dd"');
                }
            } 
        });
    });

    function isValidDate(dt) {
        if (dt.match(/^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/)) {
            return true;
        }
    }
</script>

When I console.log(toDate) however, I get an empty string. But if I do another blur event again (focus and unfocus the field with the data still in it), I get the correct value. Any ideas why it doesn’t work the first time?

The two text inputs have IDs of #fromPicker and #toPicker and are jQueryUI datepickers.

SOLUTION:

What ultimately did what I wanted was this:

jQuery(function() {
jQuery(‘#fromPicker, #toPicker’).datepicker({
dateFormat : ‘yy-mm-dd’
});

    jQuery('#submit').on('click', function() {
        var fromDate = jQuery('#fromPicker').val();
        var toDate = jQuery('#toPicker').val();

        if (fromDate !== '' && toDate !== '') {
            if (isValidDate(fromDate) && isValidDate(toDate)) {
                // do nothing
            } else {
                alert('You must enter dates in the format "yyyy-mm-dd"');
                return false;
            }
        } else {
            return false;
        }
    });
});

function isValidDate(dt) {
    if (dt.match(/^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/)) {
        return true;
    }
} </script>

I dont see any reason for your code not to work but instead of blur event, try onselect event of the datepicker instead

jQuery('#toPicker').datepicker( {
    onSelect: function(date) {
        alert(date);
        // Do other stuff
    },
    // ....
);
Read more

How can I separately style CSS 'content' elements?

Eric’s Question:

I have a nav list that looks like this:

Home / About / Locations / Contact

I’m coding it as a simple <ul> and using something like this for the separators:

#nav li:after {
    content: "/";
}

However… the designer wants the current page that you’re on (the ‘active’ item in the nav) to be shown in bold and ask change to a different font. Something like this:

Home / About / Locations / Contact

This is easy enough to do with a separate style specifically for the active <li> item. However, here’s the problem: the separator character (“/”) also changes to bold and the new font, since it is considered to be part of the <li> item. This is bad… I want the separators to always look the same, regardless of which page is active. Is there a way to change that, or override the formatting on the separator? (Or a better way to code this with CSS that will accomplish what I’m trying to do?)

You can tell the / to have a normal font weight.

#nav li:after {
    content: "/";
    font-weight: normal;
}
Read more
July 22, 2013

How to prevent Zend Framework 1 from resolving a controller name with a dot on its end?

Artem Gordinsky’s Question:

I have a website that runs on Zend Framework 1.12. It has a controller named ‘users’. When I enter its name incorrectly — http://mywebsite/userss — I rightfully get an error saying that such controller does not exist. When I add a dot to the end of its name, however:
http://mywebsite/users., an error says that a viewscript called users./index.phtml does not exist. Interesting thing is, it still gets the controller (users) correctly.

I have two questions regarding this matter:

  1. How and why does it ignore a dot at the end, and still gets a controller correctly?
  2. Is there a way to reject such controller names, without any modifications to the framework’s core?

Excellent question, but to answer this we have dig the source of Zend Framework and initially back To 2007, a function _formatName() was specially designed to remove such anomalies from the URL name. May be it was earlier than this but I don’t know that.

This particular piece is from Zend Framework 0.1.4 (Historic Right??) 🙂

protected function _formatName($unformatted)
{
    $unformatted = str_replace(array('-', '_', '.'), ' ', strtolower($unformatted));
    $unformatted = preg_replace('[^a-z0-9 ]', '', $unformatted);
    return str_replace(' ', '', ucwords($unformatted));
}

Here you see -, _, and . removed on the very first step.

Even today, this function is set to remove - and . but not the _

Here is current Zend Framework 1.x version of that function

protected function _formatName($unformatted, $isAction = false)
{
    // preserve directories
    if (!$isAction) {
        $segments = explode($this->getPathDelimiter(), $unformatted);
    } else {
        $segments = (array) $unformatted;
    }

    foreach ($segments as $key => $segment) {
        $segment = str_replace($this->getWordDelimiter(), ' ', strtolower($segment));
        $segment = preg_replace('/[^a-z0-9 ]/', '', $segment);
        $segments[$key] = str_replace(' ', '', ucwords($segment));
    }

    return implode('_', $segments);
}

Just like before the URI Segment is clean out in this line

$segment = str_replace($this->getWordDelimiter(), ' ', strtolower($segment));

The function getWordDelimeter() returns an array of array('-', '.');[line] thus removing them first thing in the URL, which answers your first question. About the second question, you can modify this line and remove the . from it.

protected $_wordDelimiter = array('-', '.');

After this the Despatcher will no longer find the controller or any URI component with . on it.

Read more

MYSQL Order by with case

Anil D’s Question:

I have a Product Table which has following structure.

   ProductID     ProductName     ProductType
   1             Irrigation      1  
   2             Landscape       2  
   3             Sleeving        3  
   4             Planting        4  

Now i need to returns rows in order of product type 3,2,4,1
For this i used MYSQL FIELD method which works fine like this

   Select * from product order by FIELD(producttype,3,2,4,1)

This is working fine,

My problem is if the productname is empty for producttype 3, then it should take next productname which is not empty, so in such case result order should be 2,4,1,3.

So first condition is records need to be in following order of product type

Sleeving      3
Landscape     2
Planting      4
Irrigation    1                

But if Productname for producttype 3 is empty then order need to be

Landscape     2
Planting      4
Irrigation    1
              3

And further Productname for producttype 2 is empty then order need to be

Planting      4
Irrigation    1
              3
              2

From this result i just need to pick first record.

I hope i clear my point

Any help would be appreciated

This is a very complex query and will never [citation needed] work as you need, because it should identity the next value in another row which can be anything. It is possible with views, functions, pivoting and many joins but as the number of rows, I dont think it can give a result.

However, to answer directly, YES Order BY with CASE is possible

Select * from product order by 
   CASE WHEN productname IS NULL then FIELD(producttype, 2, 4, 1, 3)
   CASE WHEN productname IS NOT NULL THEN FIELD(producttype, 3, 2, 4, 1)

Again, This is not full query and is not the solution

If your rows are limited you can chain up your queries like this

Select * from product order by 
   CASE WHEN productname IS NULL then FIELD(producttype, 2, 4, 1, 3)
   CASE WHEN (SELECT productname n FROM product WHERE producttype = '2') IS NULL THEN FIELD (4, 1, 3, 2)

As you see I have fixed the query to search for the row with ‘2’ as product type in it. You can know them by making another query and pivoting it the main query.

Again it is not neccessary, process the rows server side it will very very easier than this.

Read more

Increment value in array php

Cipherous’s Question:

I am trying to make a function that grabs all the days that have events that are in a database for a certain user. For instance if there were two events on Jan 23, 2013 it would add Jan 23, 2013 to the array. I got it to work so it adds all the days (without adding the same day twice) but now I want to be able to say how many dates are on each day. So on Jan 23, 2013 it would say they have two events in that day.

I hope this makes sense… I have some code for further aid.

PHP Function (grabbing each day that has events)

//gets upcoming days that have events for a user
    public function get_upcoming_days_with_events() {
        $return_array = array();
        $date_in=null;
        $user_id = $this->session->userdata('id');
        $query =$this->db->select()->from('events')->where('user_id', $user_id)->get();
        foreach ($query->result_array() as $event => $row) {
            $date = strtotime($row['date_due']);
            if (sizeof($return_array) != 0) {
                foreach ($return_array as $date_in_array => $row) {
                    $d = $row['full_date'];
                    if (date('Y-m-d', $date) == $d) {
                        //date is already in array
                        //increment the number of assignments on this day
                        $row['number_of_assignments'] += 1;
                        $date_in = true;
                    } else{
                        $date_in = false;
                    }
                }
            }
            if ($date_in == false) {
                $return_array[] = array(
                    'day' => date('d', $date),
                    'month' => date('m', $date),
                    'full_date' => date('Y-m-d', $date),
                    'number_of_assignments' => 1
                );
            }
        }
        return $return_array;
    }

So with this I want to be able to increment $return_array[‘number_of_assignments’] if my function notices that a certain day has more than one event.

Let me know if you need any more info…

Thanks! 🙂

We can save the info in return_array by index of date, if the date info have not been set into return_array, we make an empty info. Each time, we simply increase number_of_assignments.

 public function get_upcoming_days_with_events()
 {
     $return_array = array();
     $user_id = $this->session->userdata('id');
     $query =$this->db->select()->from('events')->where('user_id', $user_id)->get();
     foreach ($query->result_array() as $event => $row)
     {
         $date = strtotime($row['date_due']);
         $date_key = date('Y-m-d', $date);
         if (!isset($return_array[$date_key]))
         {
             $new_item = array(
                 'day' => date('d', $date),
                 'month' => date('m', $date),
                 'full_date' => $date_key,
                 'number_of_assignments' => 0,
             );
             $return_array[$date_key] = $new_item;
         }
         $return_array[$date_key]['number_of_assignments']++;
     }
     $return_array = array_values($return_array);
     return $return_array;
 }

Function: array_count_values() can help you with this, it gives total number of occurance of a value in an array.

For example:

$a = array("apple", "banana", "apple");
var_dump(array_count_values($a)); 

Will output

array(
   [apple] => 2,
   [banana] => 1
);

So instead of trying to filter out duplicate events, add them all on the array and then use array_count_values() at last to know their occurenses.

Read more
July 21, 2013

Joining tables in sql query for a search

User1874212’s Question:

Alright this is a total mess and I’m so lost right now. I’m trying to have a search for a site in which you can search for a word and it will go through a table called designs to search the table through multiple columns for the word. I had that working until I decided that I would like the option to also search for the username of another member. in the design table, there is a column named user in which that matches up with the id inside of users. I hope that makes sense because I really don’t want to have to draw out a table..

$result = mysql_query("
SELECT designs.*, users.* 
FROM designs, users 
WHERE type LIKE '%" . mysql_real_escape_string($search1) . "%' 
OR title LIKE '%" . mysql_real_escape_string($search1) . "%' 
OR tags LIKE '%" . mysql_real_escape_string($search1) . "%' 
OR description LIKE '%" . mysql_real_escape_string($search1) . "%' 
OR users.username = " . mysql_real_escape_string($search1) . " 
ORDER BY designs.id 
DESC
");

This is what it currently looks like, and $search1 is what the user is searching.. I want to be able to display any designs that a user has made by searching for the username of the user after connecting the designs.user to users.id but it just won’t work, any ideas?

ALSO mysql_error() gives me the error that “Unknown column ‘namehere’ in ‘where clause'”

The query for inner join is this, and you have to specify the table name like designs.<columnname> to query them.

    SELECT designs.*, users.* 
    FROM designs
    INNER JOIN users on users.id = designs.user
    WHERE designs.type LIKE '%<SEARCH TEXT>%' 
    OR desings.title LIKE '%<SEARCH TEXT>%' 
    OR designs.tags LIKE '%<SEARCH TEXT>%' 
    OR designs.description LIKE '%<SEARCH TEXT>%' 
    OR users.username = '<USER ID>' 
    ORDER BY designs.id 
    DESC

Simple syntax is

INNER JOIN <table name> <alias> ON <first table>.<column name> = <second table>.<column name>

HUGE Problem is you are using mysql_* API, please these method are very vulnerable Do not USE them

If you use other API like mysqli or PDO, you dont have to use mysql_real_escape_string to make your query safe.

Read more
July 20, 2013

Fullscreen mode for a video player

Vhanjan’s Question:

I was trying to make full screen for my video player. I am using JWplayer.. what i want is a full screen like this

var player_width = $(window).width();
var player_height = $(window).height();

Code above wont work for this, i was wondering on how this will work. I was looking for some solution for this but i cant find one. I am getting this kind of result..

Updated:

The fullscreen feature you are trying to omit of youtube is coded in ActionScript in their player. JW Player does not offer this feature. However you can set full screen without measuring the window's height and width like this:

jwplayer('mediaspace').setup({
'flashplayer': '/jwplayer/player.swf',
'width': '100%',
'height': '100%',
});

One trick is too trigger browser default player by linking the direct video link on a link somewhere or on the double click of the player (can be easily done using jQuery)

Another trick is too trigger the full screen of browser as shown here

Earlier Answer:

If you attempting to resize the player based on the screen’s dimension, make sure you are getting the values after the document is loaded and that plugin is initiated after wards.

$(function() {
   var player_width = $(window).width();
   var player_height = $(window).height(); 

   //After this initiate the plugin

});

Except this, there is nothing wrong with your code.

Read more

how using parameter value to call function?

Kishor’s Question:

is there anyway to use passed parameter to call function in javascript.

eg:

var Animal = (function(){
    function Animal(type){
        this.type(); eg this.snake(); if the parameter type is "snake"
    }
    return Animal;
})();

var animal = new Animal("snake");

Thanks!

Javascript object properties act like associative arrays so this.a == this['a']

   var Animal = (function(){
        function Animal(type){
            this[type](); //eg this.snake(); if the parameter type is "snake"
        }
        return Animal;
    })();

You can reference it like an array. In your case it would be this[type]

function Animal(type){
    this[type]();
}

Additionally, if you do not know the object or if the variable is global, then you can use window like in the same context. For example

var apple = 'tasty';
var fruit = 'apple';
console.log(window[fruit]); // Will give `tasty` as output
Read more
July 19, 2013

jQuery – css() not working properly in firefox

HowToPlease’s Question:

I am using .css() to get style from a element.
But in firefox .css() is not getting value of margin and padding from element.

Please see the fiddle:
http://jsfiddle.net/howtoplease/fMTsW/

This is my jquery code:

$(document).ready(function(){
    $('input').each(function(){
        this.value = $('h3').css(this.name);
    });
});

My html code

<h3 style="margin:20px;padding:20px;font-size:30px;font-family:'open sans';">
    I am heading 3
</h3>

<input name="margin" />
<input name="padding" />
<input name="font-size" />
<input name="font-family" />

The CSS tag ‘margin & padding’ is actually a shorthand for the four separate margin/padding values, top/left/bottom/right. Use css(‘marginTop’), etc. – note they will have ‘px’ on the end if you have specified them that way.

Use parseInt() around the result to turn it in to the number value.

<input name="margin-top" />
<input name="padding-top" />

OR

<input name="marginTop" />
<input name="paddingTop" />

This will give you the value. Using this technique you can get the value of margin and padding.

This is happening because properties like margin and padding are short hand property and jQuery cannot give you these values you have use independant values such as margin-top and margin-right.

Moreover, properties with multiple words like margin-top should be accessed using marginTop i.e First letter of second word should be capital.

For a full set of values:

<input name="marginTop" />
<input name="marginRight" />
<input name="paddingTop" />
<input name="paddingRight" />
<input name="fontSize" />
<input name="fontFamily" />
Read more
...

Please fill the form - I will response as fast as I can!