...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
February 26, 2012

Override parent CSS Rule of 'overflow:hidden'

Question by Starx

I am display thumbnails on a div with overflow:hidden as its style attribute.

When I click one thumbnail, I replace the image with its larger view (which creates a zoom effect) but since some of the images are quite big, it gets cut off by its parent division.

So, I want that particular thumbnail to defy its parent rule and get out and show its 100%self.


The main reason for me, to bump this question, is to get/provide a good working solution. The best one is found is this.

Answer by Starx

The easiest and more efficient method to do this, was to add the following property to the image to get the job done.

position: absolute

After it has absolute positioning, its jumps out of its container till it finds another relative container, thus defying its parent rule.

I am created a simple demo [here] to illustrate this situation and the solution.

Read more
February 25, 2012

PHP Update page on POST

Question by Sami Dz Hamida

I have this little problem that when I POST something the page only updates after you refresh the page or change the page.

Example:

Money:
$1,000 -> (echo $money;)

if($_POST['add_money']){
    mysql_query("UPDATE users SET money=money+ '1000' WHERE username = '".$name."'");
    echo "You added $1,000 to your money";
}

“Money” will still say $1,000 unless I change page or refresh.

I’m sure it something so small but I just cant seem to find out how to do it.

Thank you in advanced.

Answer by Starx

Your code should work the way it is. Try this to confirm any errors

if($_POST['add_money']){
    $query = "UPDATE users SET money=money+ '1000' WHERE username = '".$name."'";
    $result = mysql_query($query) or die(mysql_error());
    if($result) {
       echo "You added $1,000 to your money";
    }
}
Read more
February 24, 2012

explain this css please

Question by max4ever

I am developing a css for printing in IE8, since i don’t have advanced css selectors( http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/ ) i concatenate them like this

I need to modifiy certain columns in a table(e.g. make 8th column red, 9th longer, 10 shorter… ecc)

The question is if i use

td+td+td{ /*instead of td:nth-child(3) on modern browsers*/
 set something...
}

all the td from the 3rd one to the last one have that “set something”

so to fix it i have to do

td+td+td+td{
 unset something
}

So i fixed it, but wondering why it acts like this?

Answer by Starx

+ denotes adjacent selectors.

td+td { } Generally means, if a td is preceded by another td then apply certain rule

One more example:

a + p {} Generally means, if p comes after a then apply certain rule.

So the style sheet you are using

td+td+td will apply the style to every td after the third elements. This might be a little complicated to be clear about. Lets see an example with sets of <td>

<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>

Your rule

td + td + td {
    /* apply something */
}

The above rule will apply to two different sets

  1. First one, adjacent sibling from <td>1</td> to <td>3</td> matches td+td+td

  2. Second one, adjacent sibling from <td>2</td> to <td>4</td> also matches td+td+td

So at the end, all the selectors from <td>3</td> end up getting the style

To cancel this effect, you reset the rule adding fourth selector on the style sheet.
i.e

td + td+ td + td {
  /* cancel the effect
  This will catch <td>-4</td> and apply the reset rule */
}

Hope that explains it.


Further Reading

  1. W3 Org
  2. Good Explanation with examples
  3. One more to fully clarify
Read more

Two (almost) identical pieces of code produce separate results

Question by Marc Towler

I have been working on a little MVC project to assist in my self-learning and I have come across an issue that completely baffled me. I made a blog section in this MVC-ish system and pulled user permissions from an ACL with no problem whatsoever.
I moved onto creating a member section and as soon as i added any permissions checking I get the following error from Chrome:

No data received
Unable to load the web page because the server sent no data.
Here are some suggestions:
Reload this web page later.
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.

I thought it was weird, so I double checked my error logs and nothing had shown up. So I decided to copy and paste the working blog code into the member file, reloaded and i got the EXACT same error, the only difference between the two files right now is the file name and the class name.
Here is the Blog code:

<?php
class blog extends frontController {
    public $model;
    public $user;

    public function __construct()
    {
        parent::__construct();

        $this->model = $this->autoload_model();
        $this->user  = $this->load_user();
        $this->user->getUserRoles();
    }

    public function index()
    {
        //Will only list the latest post ;)
        if(!$this->user->hasPermission('blog_access'))
        {
            $array = $this->model->list_posts();

            if(empty($array))
            {
                $this->variables(array(
                    'site_title' => 'View Blog Posts',
                    'post_title' => 'Sorry but there are no posts to display'
                ));
            } else {
                $this->variables(array(
                    'site_title' => 'View Blog Posts',
                    'list'       => $array[0],
                    'post_title' => $array[0]['entry_title'],
                    'link'       => str_replace(' ', '_',$array[0]['entry_title']),
                ));
            }
        } else {
            $this->variables(array(
                'site_title' => 'Error :: Design Develop Realize',
                'body'       => 'Sorry, but you do not have permission to access this',
            ));
        }

        $this->parse('blog/list', $this->toParse);
    }

This is the member file:

<?php

class member extends frontController {
    public $model;
    public $user;

    public function __construct()
    {
        parent::__construct();

        $this->model = $this->autoload_model();
        $this->user  = $this->load_user();
        $this->user->getUserRoles();
    }

    public function index()
    {
        //Will only list the latest post ;)
        if(!$this->user->hasPermission('blog_access'))
        {
            //$array = $this->model->list_posts();

            if(empty($array))
            {
                $this->variables(array(
                    'site_title' => 'Design Develop Realize :: View Blog Posts',
                    'post_title' => 'Sorry but there are no posts to display'
                ));
            } else {
                $this->variables(array(
                    'site_title' => 'Design Develop Realize :: View Blog Posts',
                    'list'       => $array[0],
                    'post_title' => $array[0]['entry_title'],
                    'link'       => str_replace(' ', '_',$array[0]['entry_title']),
                ));
            }
        } else {
            $this->variables(array(
                'site_title' => 'Error :: Design Develop Realize',
                'body'       => 'Sorry, but you do not have permission to access this',
            ));
        }

        $this->parse('blog/list', $this->toParse);
    }

In the member class, if I comment out $this->user = $this->load_user(); then the error disappears!!!
Just for reference here is that function:

protected function load_user()
{
    if(!$this->loader->loaded['acl'])
    {
        $this->loader->loadCore('acl');
    }

    return $this->loader->loaded['acl'];
}

Any help or suggestions would be appreciated as I am stumped!

PS yes I do have error reporting set to cover everything and no it does not log anything!

EDIT: Because all files go through index.php I have placed the error reporting there:

<?php
error_reporting(E_ALL);
ini_set('date.timezone', "Europe/London");

require_once('system/library/loader.php');

$loader = new loader();
$loader->loadCore(array('frontController', 'routing'));

EDIT 2: loadCore() is below

public function loadCore($toLoad, $params = false)
{
    //important task first, check if it is more then 1 or not
    if(is_array($toLoad))
    {
        //more then one so lets go to the task!
        foreach($toLoad as $file)
        {
            if(file_exists('system/library/' . $file . '.php'))
            {
                require_once('system/library/' . $file . '.php');

                if($params)
                {
                    $this->loaded[$file] = new $file($params);
                } else {
                    $this->loaded[$file] = new $file;
                }
            } else {
                trigger_error("Core File $file does not exist");
            }
        }
    } else {
        //Phew, less work, it is only one!
        if(file_exists('system/library/' . $toLoad . '.php'))
        {
            require_once('system/library/' . $toLoad . '.php');

            if($params)
            {
                echo(__LINE__); exit;
                $this->loaded[$toLoad] = new $toLoad($params);
            } else {
                $this->loaded[$toLoad] = new $toLoad;
            }
        }
    }
}

Update: I modified loadCore so that if it was the acl being called it would use a try…catch() and that has not helped as it will not display an error just the same chrome and IE pages

Update 2: I have spoken with my host and it seems that everytime this error occurs, apache logs the following (not sure why I cannot see it in my copy of the logs!)

[Wed Feb 22 08:07:11 2012] [error] [client 93.97.245.13] Premature end
of script headers: index.php

Answer by Starx

“Premature end of script headers” are internal server errors. Which generally occurs when script breaks and does not send any HTTP headers before send the error messages. There might be several causes to this.

  • One might be output buffering. May be the server you are using buffers the output by default. I will suggest turning off the output_buffering using output_buffering = off on php.ini [docs here].

  • Make sure you are sending correct HTTP headers also

    print “Content-type: text/htmlnn”;

There are few more suggestion on this link.
To learn more about this error, go here.

Hope it helps

Read more

jQuery UI Background Color Flickers in IE

Question by Aaron

I’m experiencing issues with IE (of course) and jQuery UI. I’m animating the background color and everything works fine in all other browsers, but for some reason IE flashes different colors while animating. It does the actual background color animation, but is a horrible transition. A ton of different colors randomly flash in during the transition. Has anyone experienced this issue before? Thanks!

Answer by Starx

Sometimes, for color transition, jQuery Color Plugin does the job much better. Find it here.

Regarding your question, unless you show some codes, can’t help you debug that.

Read more
February 23, 2012

Codeigniter Route to accept dynamic values

Question by mrN

I am trying to create a router which will take a dynamic value and forward it to the actual route. In normal case it would be like

$route['login'] = 'auth/login';

It is possible to catch a parameter before the login in the above parameter and pass it to as the first parameter to the actual route ? like

$route['^(.+)/login$'] = "$1/user/login";

Answer by Starx

Check out the documentation[docs]. There is a very easy way to do this.

$route['(:any)/login'] = '$1/auth/login';
Read more
February 20, 2012

My cycle and the cyclist in me

7th Standard, during the weeks between Dashain and Tihar was the first time I got my cycle, A mountain bike (during those time every bike with gears used to be called mountain bikes). I took so much pride on having it. I still remember my struggles trying to learn to ride. How I couldn’t reach my bike’s pedal and used higher slopes get moving while learning to balance. The bruises between my legs from the bike’s frame still breaks me into laugh. But they were good old times, very precious and memorable.

Since then cycling has been be a part of daily life. I don’t remember since when my daily cycling turned out into a hobby. A true hobby, where I find a missing part inside me when I am riding it. The cyclist in me is growing ever since, so is my cycle but to the best I can afford.

It sickens me how people tend to judge me, just because I ride my cycle to college, to office, to even dates(O.o). But hardly any one tries to think even for a single second, it is a desperate attempt of a man who is trying to do what he loves out of his busy schedule.

For a man to succeed in anything, there has to be a motivational factor, but sadly the only one who is motivating me towards cycling is just me. I got no team to ride off with, no support from my family (I am still considered stupid from spending 18,000 on a cycle), nothing what so ever.

Here is a funny flashback! I remember at my college, when one of my buddy Bishal brought a cool looking new bike, and one of my other friend Anju, was laughing about it. Her very words were “13000(less than $200) on a cycle, what a stupid”

I have few contacts on the pro line and get some chance to go on with them for some rides, but when I am there the first line I hear is “You are going to ride that??? That cycle is not going to work!! Try to hire this and that… blah blah blah” and so on. So irritating and frankly a lot demoralising.

I ride Motache CSJ 795 currently. If you search for that cycle in Google, I don’t think you will find any links on it. If you do, I am a lucky man. That cycle has no reputation at all on the pro cycle world here in Nepal, I cannot even imagine whether it is also regarded as a rideable bicycle on other nations. But Nepal is pretty renowned for off-road cycling, so may be I am just underestimating my country/my surname(:D). Either way, I think I have made my point.

Pro cyclist, cycle shop owners look at me on a very awkward way as if they are saying “Look at that guy, riding on such a piece of shit, and thinking he is a cyclist”. Now, comes another part. After, I am away from those mega stars and onto my daily routes, guys walking by the streets, now look at my bike and say “Wow, what a bike, look at how fast is he going!”. This world is such a funny place you know. Sometimes, it keep on wondering, am I the stupid one, or is this world completely loco.

There is a guy at my area, who dresses up like a pro and rides Trek 7200 (worth Rs: 1, 20, 000). One day after my office I met this guy at little bit ahead of TB Teaching hospital, we raced from there to the temple. We had a stiff competition, sometimes me ahead of him and vice versa. At the very last slope of Budhanilkantha temple, he pushed up and won the final round. It was a good race, he was more skilled on the uphill and sprinted faster. The next day, I was surprised to see this guy again. It was this time, I came to know he rides Trek 7200 and he came to know I ride Motache. The guy who was going neck and neck with me, suddenly drops behind me and never challenges me or be challenged since then. What a pathetic discriminative loser, even with a normal bike, I was making that guy sweat his *ss and still I am worthy enough to race with with 7 Series.

I have rode cycle that cost up to NRS: 320,000 also, but when will I own such a bike is really a surprise. I do not want to spend so much on a bike, since I am not quite involved on professional racing. Still my next cycle will probably be Cannondale Trail SL 3 and I am really looking forward to it.

Read more
February 17, 2012

Table does not show tables relations after importing database

Question by indie

I imported a MySQL dump file into my MySQL server using following command.

mysql> create database database_name;
mysql> use database_name;

In Linux command prompt,

$ mysql -u user_name -p database_name < /tmp/test1.dmp

But, while viewing the database using phyMyAdmin the newly created database_name does not show table relations. It shows only the tables, but not relations.

Is there any set up required before importing the database in mysql database?

How to extract the relations between tables?

Answer by Starx

I just went through the exact same problem.

Is there any set up required before importing the database in mysql database?

Not exactly, but it seems LAMP Server installed on Ubuntu or any Linux Distribution uses MyISAM storage engine by default while creating tables. On InnoDB supports Foreign Key relation. [more info]

To change the storage engine afterwards. [Source answer]

You have to add the line default-storage-engine = InnoDB under the [mysqld] section of your mysql config file (my.cnf or my.ini depending on your operation system) and restart the mysqld service. I don’t believe you can change this through phpMyAdmin.

On ubuntu, my.cnf is located inside /etc/mysql/.

Or, you can use mysql command

mysql> SET storage_engine=InnoDb;

After this, all the tables and database you create after this, will use InnoDB as their default storage engine, thus eliminating the issue afterwards.

How to extract the relations between tables?

After you change default engine of your database. You also have to change the default engine of your tables, because they haven’t been changed yet. Use the syntax below to change the storage engine

ALTER TABLE <table_name> ENGINE = innodb

Using phpMyAdmin

  • Go to the operations tab after selecting a table
  • Go to the table options [See below]
  • You will see an option to change the storage engine of the table
    Image showing Table Options in Phpmyadmin
  • Change the storage engine to InnoDb and hit Go

After this, export the database using phpMyadmin or dump your database using mysqldump. it will show the relations.

Read more
February 10, 2012

Allow sortable elements to be positioned freely on the screen

Question by Ryan

I am trying to use the jQuery UI’s draggable & Sortable to make an object drag-able freely so that the object does not have to remain next to each other in a container.

I want the object to be positioned freely within its parent.

How can I achieve this?

Answer by Starx

If I got the question you were trying to ask properly. This is generally achieved from just using the draggable option only.

See this demo here.

Read more
February 8, 2012

Insert parent element ID into dynamic element

Question by GSTAR

Markup:

<iframe id="portal">
    <div id="callout-1" class="callout">
    </div>

    <div id="callout-2" class="callout">
    </div>
</iframe>

$(document).ready(function(){
    $('#page-portal').load(function(){
        $('#portal').contents().find('.callout')
        .append('<div class="edit-image" id="edit-image-1">Edit This Area</div>');
    });
});

This code dynamically inserts a div class="edit-image" into each div class="callout"

What I want to do is retreive the ID (numeric portion) from div class="callout" and dynamically insert it into the ID of div class="edit-image"

I am having trouble with this, can anyone help?

Answer by Starx

You can use .split() method of Javascript. It should look something like this

$('#portal').find('.callout').each(function(k,v) {
    id = $(this).attr("id"); 
    //take out the id of element

    temp = id.split("-"); 
    //split the string based on "-"

    idnum = temp[1]; 
    //take the second part of split i.e the integer part

    $(this).append('<div class="edit-image" id="edit-image-'+idnum+'">Edit This Area</div>'); 
    //then finally use it
});

Here is a working demo

Read more
...

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