...

Hi! I’m Starx

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

Delete MySql rows, or mark "dead"?

Question by johnnietheblack

I’ve always had a weird feeling in my gut about actually deleting rows from certain types of tables.

For example, if I have a table of Users…when they delete their account, rather than fully deleting their row, I have been marking as “dead” or inactive. This allows me to retain a record of their existence if I ever need it again.

In situations like this – considering performance, overhead, etc – should I delete the row, or simply mark as inactive?

Which is more “common”?

Answer by Eric Petroelje

Personally, I almost always use “soft deletes” as you describe.

If space is a concern, I’ll have a job that will periodically clean up the soft-deleted records after they’ve been deleted for a certain amount of time.

Answer by Starx

Data are very valuable to be permanently deleted from the database. Mark as dead.

I generally give status for such cases. In this pattern

  1. 0 Inactive
  2. 1 Active
  3. 2 Trashed
Read more

Join 2 arrays in object with repeated keys

Question by DannYO

I have 2 arrays of the same length like this:

a = [12,21,21,13,13,13,13,31];
b = [4,7,4,6,2,9,4,1];

The first array are the keys and the second array the values, but if the key is repeated the the values should be grouped in the corresponding key instead of being replaced.
The object should look like so:

o = {
    12: [4],
    21: [7,4],
    13: [6,2,9,4],
    31: [1]
}

And here what I tried:

var o = {};
for ( var index in a) {
    o[a[index]] = [];
    o[a[index]].push(b[index]);
}

Answer by T.J. Crowder

Don’t use for..in to loop through arrays (unless they’re sparse arrays and you know what you’re doing; details).

Other than that, you’re on the right track, but you have to check to see whether the array already exists before overwriting it. So:

var o = {}, key, entry;
for (index = 0; index < a.length; ++index) {
    // Get the key
    key = a[index];

    // Get the entry's array if it already exists
    entry = o[key];
    if (!entry) {
        // It doesn't exist, create it and remember it in the object
        o[key] = entry = [];
    }

    // Put this value in it
    entry.push(b[index]);
}

Or a couple of small optimizations:

var o = {}, key, entry, len;
for (index = 0, len = a.length; index < len; ++index) {
    // Get the key
    key = a[index];

    // Get the entry's array if it already exists
    entry = o[key];
    if (!entry) {
        // It doesn't exist, create it and remember it in the object,
        // including this value as we go
        o[key] = [b[index]];
    }
    else {
        // Already existed, add this value to it
        entry.push(b[index]);
    }
}

If you’re using an ES5-enabled environment (or you include an ES5 shim), you can use forEach:

var o = {};
a.forEach(function(key, index) {
    var entry;

    // Get the entry's array if it already exists
    entry = o[key];
    if (!entry) {
        // It doesn't exist, create it and remember it in the object,
        // including this value as we go
        o[key] = [b[index]];
    }
    else {
        // Already existed, add this value to it
        entry.push(b[index]);
    }
});

Answer by Starx

Here is a function you can use from phpjs.com for this

function array_combine (keys, values) {
    // Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values  
    var new_array = {},        keycount = keys && keys.length,
        i = 0;

    // input sanitation
    if (typeof keys !== 'object' || typeof values !== 'object' || // Only accept arrays or array-like objects    typeof keycount !== 'number' || typeof values.length !== 'number' || !keycount) { // Require arrays to have a count
        return false;
    }

    // number of elements does not match    if (keycount != values.length) {
        return false;
    }

    for (i = 0; i < keycount; i++) {        new_array[keys[i]] = values[i];
    }

    return new_array;
}
Read more

ways to hide/show a div with a toggle in jQuery

Question by Tom

i’m looking into implementing something similar to the li’s in chrome extension page.
Should i use jQuery slideToggle? maybe someone can provide some sort of a sample
code i could start off with? (i’m new to jQuery)

Answer by aziz punjani

You don’t need any complicated plugins, you can do all of this with jquery. Here is a quick sample i whipped out. It’s simple really.

The html

<div id="outer"> 
    <p>Some outer content </p>
   <div id="inner">Slider Content </div> 
</div> ​

The css

#outer{
   height: 200px; 
   width: 200px; 
   background-color: brown; 
   overflow: hidden; 
   position: relative;     
}
#inner{ 
    height: 200px;
    width: 100%;     
    background-color: green;
    position: absolute; 
    top: 100%; 
}

The JS

  $('#outer').hover(
    function(){
       $('#inner').animate({ top: '0%' }, 'easein' );  
    }, 
    function(){
       $('#inner').animate({ top: '100%' }, 'easein' );  
    }        
   ); ​

Here it is in action.

Answer by Starx

Its extremely hard to answer your question. But showing and hiding a div is very easy, just use .toggle()

$("#mydiv").toggle();
Read more

Codeiginiter array $data view

Question by Uffo

So I need an array from my data that I can foreach on the view, an array like this: album_name,cover_image

Here is my code:

function myFunction(){

    $alb = array();

    foreach($albums as $album)
    {
        //if($album[0]['count'] > 0){
        $alb[]['album_name'] = $album['name'];

        foreach($this->get_fbimages($facebook,$album['id']) as $img)
        {
            $alb[]['cover'] = $img[0]['picture'];
        }   
    }

    return $alb;
}

and I do array_merge($data,myFunction());

Answer by Starx

The structure of your array is invalid, to the result you want.

Try it this way.

function myFunction(){

    $alb = array();

    foreach($albums as $album)
    {
        $tempArray['album_name'] = $album['name'];
        foreach($this->get_fbimages($facebook,$album['id']) as $img)
        {
            $tempArray['cover'][] = $img[0]['picture'];
        }

        $alb[] = $tempArray;

    }

    return $alb;
}
Read more

Javascript and JQuery conflict

Question by Fox Mulder

I’m not very expert in using javascript and jquery but I’m working with them for a client.
I have encountered a problem using two script: the first one makes a top panel sliding, the second is in a form. This one is used in order to hide or show a particular field basing on the drop down list choice.

I’ve found that if I disable the first script (the panel), the second script is working fine and vice versa. I tried usign JQuery noConflict() in the head of the page but nothing happened.

Here the code of the first script (sliding panel):

$(document).ready(function () {
    // Lets make the top panel toggle based on the click of the show/hide link  
    $("#sub-panel").click(function () {
        // Toggle the bar up 
        $("#top-panel").slideToggle();
        // Settings
        var el = $("#shText");
        // Lets us know whats inside the element
        var state = $("#shText").html();
        // Change the state  
        state = (state == 'Nascondi' ? '<span id="shText">Entra</span>' : '<span id="shText">Nascondi</span>');
        // Finally change whats insdide the element ID
        el.replaceWith(state);
    }); // end sub panel click function
}); // end on DOM

Here the JS code for the form (hide/show field):

$document.addEvent('domready', function () {

    $('motivo_contatto').addEvent('change', function () {
        if ($('motivo_contatto').value == 'Invia CV') {
            $('upload_file').style.visibility = 'visible';
        } else {
            $('upload_file').style.visibility = 'hidden';
        }
    });
    $('upload_file').style.visibility = 'hidden';
});

});

Can anyone help me ? Thank you and have a nice day!

Answer by Tom

you’re using 2 different ways to add things to happen to the document ready event:

$(document).ready(function(){ ... });

and

$document.addEvent('domready', function() { ... });

maybe if you just use one it works; maybe the code below will work; I put it all in the first option to run code on document ready:

I edited below code and removed all mootools code; so it might work now.

$(document).ready(function(){
    // Lets make the top panel toggle based on the click of the show/hide link  
    $("#sub-panel").click(function(){
        // Toggle the bar up 
        $("#top-panel").slideToggle();  
        // Settings
        var el = $("#shText");  
        // Lets us know whats inside the element
        var state = $("#shText").html();
        // Change the state  
        state = (state == 'Nascondi' ? '<span id="shText">Entra</span>' : '<span id="shText">Nascondi</span>');          
        // Finally change whats insdide the element ID
        el.replaceWith(state); 
    }); // end sub panel click function

    document.getElementById('motivo_contatto').onchange = function() {
        if(document.getElementById('motivo_contatto').value == 'Invia CV') {
            document.getElementById('upload_file').style.visibility = 'visible';
        } else {
            document.getElementById('upload_file').style.visibility = 'hidden';
        }
    };
    document.getElementById('upload_file').style.visibility = 'hidden';
}); // end on DOM

Answer by Starx

Mixing up two different libraries. Not a good idea.

If you want to keep on following on that pattern, wrap one of the function on a different function and call if from another.

Like:

function moo()  {

    $('motivo_contatto').addEvent('change', function () {
            if ($('motivo_contatto').value == 'Invia CV') {
                $('upload_file').style.visibility = 'visible';
            } else {
                $('upload_file').style.visibility = 'hidden';
            }
        });
        $('upload_file').style.visibility = 'hidden';
    });

}

Then call it from another

$(document).ready(function () {
    moo(); // Call the moo function


    // Lets make the top panel toggle based on the click of the show/hide link  
    $("#sub-panel").click(function () {
        // Toggle the bar up 
        $("#top-panel").slideToggle();
        // Settings
        var el = $("#shText");
        // Lets us know whats inside the element
        var state = $("#shText").html();
        // Change the state  
        state = (state == 'Nascondi' ? '<span id="shText">Entra</span>' : '<span id="shText">Nascondi</span>');
        // Finally change whats insdide the element ID
        el.replaceWith(state);
    }); // end sub panel click function
}); // end on DOM

Check this answer, if you want to use both libraries side by side

Read more

How to add CSS3 rounded corners with modernizr?

Question by Alok Jain

I am trying to add CSS3 based rounded corner support in IE7 and IE8 on following page

Test URL: http://jaspreetkaur.com/postjoint

I have included modernizr library, but it’s not working. Is there any code that i need add to make it working in IE?

Answer by Nix

As others have said, Modernizr won’t make legacy browsers able to support CSS3. It only checks for support, plus other neat features, such as HTML5shiv, so that you can use HTML5 markup.

To enable CSS3 features in older browsers, you might try CSS3 Pie, but I find it some times creates more problems than it solves. I usually just don’t let older browsers see all the fancy stuff, such as rounded corners. It’s just a minor design feature, not critical to the overall functionality or layout.

http://css3pie.com/

Answer by Starx

1. IE8, IE7 do not support CSS3 rounder corners.

2. Mordernizr, is only a script, that enable HTML5 features across different browsers

CSS3 tag for rounder corner is

-webkit-border-radius: 5px; /* for safari */
-moz-border-raidus: 5px; /* for firefox < 4 */
border-radius: 5px; /* for all other that support it */
Read more

Adding A Dynamic Link In Php

Question by Iain Simpson

I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn’t work ?..

echo '<a href="./customer-files/';
        echo $customerID;
        echo '/';
        echo $filename->getFilename();
        echo '">';
              echo $filename->getFilename();
    echo '</a>';

Answer by Quentin

I’d approach it like this:

$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "<a href="./customer-files/$safe_customer_id/$safe_filename">$safe_label</a>";

Answer by Starx

Concatenation is your friend. Use a . to combine multiple string expression into one.

echo '<a href="./customer-files/'.$customerID.'/'.$filename->getFilename().'">'.$filename->getFilename()/'</a>';

Even better way would be

$filename = $filename -> getFilename(); //cache the filename
echo "<a href='/$customerId/$filename'>$filename</a>";
  // ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.
Read more

Which one is better approach window.parent.location.href or window.top.location

Question by Haseeb Akhtar

I am working in a project where I have to redirect on Error Page in a particular scenario. For that I have created Error.aspx page. Right now I am using
window.top.location.href = “../Error.aspx” and it generate http://localhost/app_web/Error.aspx
and its working fine except once (which shows Message http://xyz/ErrorPage.aspx‘ does not exist. ). So can anyone suggest which is the better option for this.

Thanks

Answer by Kolink

top is “better than” parent if your intent is to framebust your page into the top level, because your page may be inside a frame that is itself inside a frame.

As for your relative path problem, you may want to try:

var local = location.pathname.split("/");
local.pop(); // remove the filename
local.pop(); // remove the containing directory
local.push("Error.aspx");
local = location.protocol+"//"+location.hostname+"/"+local.join("/");
top.location.href = local;

Answer by Starx

It depends on what you are trying to do.

  1. window.parent.location

    is used to change the location of the parent window.

  2. window.top.location

    • It is a property of the object ‘window’.
    • It returns the location of the topmost window in the window hierarchy.
    • If a window has no parent, top is a reference to itself (window === window.top)
Read more

show server time using php and jquery ajax

Question by Shrestha Sunil

I was trying to show the date and time of server using php and jquery ajax. following are the jquery script to show datetime

<script type= "text/javascript" src="jquery-1.4.1.min.js"> </script>
    <script type= "text/javascript">
$(document).ready(function() {
function update() {
  $.ajax({
   type: 'POST',
  url: 'datetime.php',
  timeout: 1000,
  success: function(data) {
      $("#timer").html(''); 
    window.setTimeout(update, 1000);
   },
  });
 }
});

</script>

<div id="timer"> </div>

following are php script for datetime.php

 <?php

  $msg = date('d/m/Y h:i:s');
  echo $msg;

 ?>

I don’t what is going wrong. It’s not showing output. Any help

Answer by Starx

You have almost got it. Just update this line

$("#timer").html(data); 

Usage:

$(document).ready(function() {

    function update() {
      $.ajax({
       type: 'POST',
       url: 'datetime.php',
       timeout: 1000,
       success: function(data) {
          $("#timer").html(data); 
          window.setTimeout(update, 1000);
       },
      });
     }
     update();

});
Read more

Spinner Minimum Time Delay Jquery

Question by Both FM

The following java-script is working fine (Jquery)

$(document).ready(function(){
$('#c_area').load($('.m_top:first').attr('href'))   
});
$('.m_top').click( function(){
$("#myDiv").html('<img src="images/loading.gif" alt="Wait" />');
var name= $(this).attr('href');
$('#c_area').hide().load(name).fadeIn('normal');                
$("#myDiv").html('');
return false;
});

I want to show the loading image (spinner) for 2 seconds minimum, because when page has already loaded, while click again on link, loading image (spinner) not display again because the page already loaded.

minimum time = 2 second

maximum time = until the contents loaded

Answer by Starx

Use delay(). Give the number of seconds in milliseconds like

$('#c_area').delay(2000).hide().load(name).fadeIn('normal');   
            //^ delay for 2 sec then hide      

Here is your solution.

I used the setTimeout() to trigger the function after 2 seconds.

$('.m_top').click( function(){          

    var name= $(this).attr('href');
    $('#c_area').html('<img src="images/loading.gif" alt="Wait" />');
    setTimeout( function() {
       $("#c_area").hide().load(name).fadeIn("normal");
    },2000);

    $("#myDiv").html('');
    return false;
});
Read more
...

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