Showing posts with label en. Show all posts
Showing posts with label en. Show all posts

Tuesday, July 20, 2010

Top 20+ Best Mysql Pratices

This is a great article about mysql best pratices. You just must take a look.

Direct link: http://net.tutsplus.com/tutorials/other/top-20-mysql-best-practices/

Using jQuery to search in HTML

What are we going to do?


How?


The example HTML structure
<div id="search">
            <input type="text" name="q" />
</div>

        <ul id="content">
            <li>Donec posuere lobortis urna, sit amet adipiscing purus blandit vel.</li>
            <li>Morbi in sem quis dui placerat ornare. Pellentesque odio nisi.</li>
            <li>Praesent dapibus, neque id cursus faucibus. </li>
            <li>Phasellus ultrices nulla quis nibh. Quisque a lectus.</li>
            <li>Duis tempus turpis in neque sagittis at adipiscing. Nulla congue turpis ac turpis aliquet placerat.</li>
            <li>Pellentesque fermentum dolor.</li>
        </ul>

JS

$(function(){

        /**
        * Fix to disable case-sensitive
        **/
        $.expr[':'].icontains = function(obj, index, meta, stack){
            return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
        };

        $("div#search input[type=text]").keydown(function(e){
            var $input = $(this);
            if($input.val() != ''){
                $('ul#content li').hide();
                $('ul#content li:icontains('+$input.val()+')').show();
            }
        });
    });

Optional CSS
body{
                margin:0;
            }

            div#search{
                background:#ddd;
                border-bottom:1px solid #bbb;
                padding:3px 10px;
            }

            div#search input[type=text]{
                border:1px solid #aaa;
                width:100%;
                font-size:16px;
            }

            ul#content{
                margin:0;
                padding:0;
                list-style:none;
            }

            ul#content li{
                background:#E0EDFF;
                border-bottom:1px solid #BACCE6;
                padding:3px 5px;
            }

Example of use

A good place to use this technique is on a chat list. You'll search all your contacts without refreshing or sending many ajax requests. Just asking your HTML!

Using Keyboard Shortcuts On You Web Application With jQuery

Here's the basic code:

$(function(){
  $('body').keydown(function(e){
      e.preventDefault();
      if(e.keyCode==13){ // enter
        // action
      }
  });
});
Note: You may use it for a specifc element instead of 'body', for example an input.

At the end of the post you'll find how to do this with "CTRL+Key" actions.

But what are the keycode's? And where do I find them?

Right Here:
Key Pressed Key Code
backspace8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222

Using "CTRL + Key" Actions

var isCtrl = false;
$(document).keyup(function (e) {
if(e.which == 17)
isCtrl=false;
}).keydown(function (e) {
if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
 //run code for CTRL+S return false;
 } 
});

Monday, July 19, 2010

MySql - Updating Duplicated Entries Made Easy

Our example table
CREATE  TABLE IF NOT EXISTS `mydb`.`Counter` (
  `idCounter` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(30) NULL ,
  `hits` INT NULL ,
  PRIMARY KEY (`idCounter`)
);

Our SQL code
INSERT INTO Counter (idCounter,name, hits) VALUES (1,'myBlog',1) 
ON DUPLICATE KEY UPDATE hits=hits+1

As simple as that

CSS3 Cross-Browser

.box_round {
     -moz-border-radius: 12px; /* FF1+ */
  -webkit-border-radius: 12px; /* Saf3+, Chrome */
          border-radius: 12px; /* Opera 10.5, IE 9 */
}

.box_shadow {
     -moz-box-shadow: 0px 0px 4px #ffffff; /* FF3.5+ */
  -webkit-box-shadow: 0px 0px 4px #ffffff; /* Saf3.0+, Chrome */
          box-shadow: 0px 0px 4px #ffffff; /* Opera 10.5, IE 9.0 */
}

.box_gradient {
  background-image: -moz-linear-gradient(top, #444444, #999999); /* FF3.6 */
  background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #444444),color-stop(1, #999999)); /* Saf4+, Chrome */
            filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#444444', EndColorStr='#999999'); /* IE6,IE7 */
        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#444444', EndColorStr='#999999')"; /* IE8 */
}

.box_rgba {
  background-color: #B4B490;
  background-color: rgba(180, 180, 144, 0.6);  /* FF3+, Saf3+, Opera 10.10+, Chrome */
            filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#99B4B490',EndColorStr='#99B4B490'); /* IE6,IE7 */
        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#99B4B490',EndColorStr='#99B4B490')"; /* IE8 */
}

.box_rotate {
     -moz-transform: rotate(7.5deg);  /* FF3.5+ */
       -o-transform: rotate(7.5deg);  /* Opera 10.5 */
  -webkit-transform: rotate(7.5deg);  /* Saf3.1+, Chrome */
             filter:  progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', 
                     M11=0.9914448613738104, M12=-0.13052619222005157, M21=0.13052619222005157, M22=0.9914448613738104); /* IE6,IE7 */
         -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', 
                     M11=0.9914448613738104, M12=-0.13052619222005157, M21=0.13052619222005157, M22=0.9914448613738104)"; /* IE8 */
               zoom: 1;
}
  
.box_transition {
     -moz-transition: all 0.3s ease-out;  /* FF3.7+ */
       -o-transition: all 0.3s ease-out;  /* Opera 10.5 */
  -webkit-transition: all 0.3s ease-out;  /* Saf3.2+, Chrome */
} 

@font-face {
  font-family: 'WebFont';
  src: url('myfont.eot');  /* IE6+ */
  src: local('☺'), 
        url('myfont.woff') format('woff'),  /* FF3.6 */
        url('myfont.ttf') format('truetype');  /* Saf3+,Chrome,FF3.5,Opera10+ */
}

Source: css3please.com/

Sunday, July 18, 2010

Using label as place holder for input

This is what we will create


So.. now that you see it, let's do it!

CSS
div.form{
    margin:4px;
}

div.form div.simple{
    margin:15px 0px;
}

div.form div.simple input{
    background:transparent;
    min-width:400px;
    padding:7px;
    font-size:15px;
    border:1px solid #aaa;
}

div.form label{
    color:#aaa;
    position:absolute;
    margin-left:5px;
}

Html structure
<div class="form">
    <form action="" method="post">
        <div class="simple">
            <label for="nome">Nome</label>
            <input type="text" name="nome" value="" />
        </div>

        <div class="simple">
            <label for="email">Email</label>
            <input type="text" name="email" />
        </div>

        <div class="action">
            <input type="submit" value="Send" />
        </div>
    </form>
</div>

JS for hidding the label after user inserts a value
$('form input').focus(function(){
            $(this).parent().find('label').hide();
        }).blur(function(){
            if($(this).val()==''){
                $(this).parent().find('label').show();
            }
});

And there you go! As simple as that!

Auto Content Refreshing with jQuery

jQuery is one of the most powerful tools in these days for a web developer
It's so good and so simple! Perfect for us!

So let's show you how to use jQuery to create a simple and efficient auto content refresher.

Html:
<html>
    <head>
        <title>Auto Refreshing Data</title>
        <script type="text/javascript" src="jquery.js"></script>
    </head>
    <body>
        <div id="container"></div>
    </body>
</html>

Javascript:
<script type="text/javascript">
    $(function(){
        var refreshTime = 0;
        
        function refresh(){
            $.get('refresh.php',{},function(callback){
                $('#container').html(callback);
                refreshTime = setTimeout(refresh,15000); // we set the loop
            });
        }

        function cancelRefresh(){
            clearTimeout(refreshTime);
        }
        
        refresh(); // call it for the first time
    });
</script>

Now let's explain it.
$.get() is the jQuery function that send the GET request. $.get has 3 param's, firs is the URL, second params and third is callback.
Something like this:
$.get(url, params,function(callback){...});

The url must redirects to your .php (.html, or any other programming language) that will handle your request, return the result.

The setTimeout function creates a kind of loop, recalling that function every 15000 ms.

To cancel the auto refresh simply call the function cancelRefresh();

Note: You may use $.get, $.post or even $.load.

Formater Class with Regular Expressions

Here is a another useful class for formating any type of data, using regular expression.

It has two parts, one var called $formats where we store the REGEX and one funcion called format where we execute it.

class Formater{
  public static $formats=array(
    'date2sql' => array("'^([0-9]{2}).([0-9]{2}).([0-9]{4})'","$3-$2-$1"),
    'sql2date' => array("'^([0-9]{4}).([0-9]{2}).([0-9]{2})'","$3/$2/$1"),
  );

  public static function format($string,$type) {
        if (!isset(self::$formats[$type])) return $string;
        $find = self::$formats[$type][0];
        $replace = self::$formats[$type][1];

        return preg_replace($find,$replace,$string);
   }
}


// Mode of use - Como usar
$date1 = Formater::format('2010-08-01','sql2date'); // returns 01/08/2010
$date2 = Formatter::format('01/08/2010','date2sql'); // returns 2010-08-01

You may use it for anything you need, all you've to do it simply add your regex to the $formats and there you go!

This is the type of class you'll need in every project you do!

Simple $_GET and $_POST request manager

This is a really simple but extremally useful class/function.
Esta é uma função muito simples porém extremamente útil.

class Request{
  public static function getParam($name,$default = null) {
        return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $default);
    }
}

//mode of use - como usar
$var = Request::getParam('name','defaultValue');

Cleaning your HTML

What I see in the internet is that people don't know exactly how to organize their programing language inside the HTML tags.

People are using this:
$html = "
  • " . $var . "
"; echo $html; ?>


instead of:
  • <?php echo $var;?>


Another ordinary situation is this:
<table>
<?php
foreach($var as $k=>$v){
echo "<tr>";
echo "<td>".$v."</td>";
echo "</td>";
}
?>
</table>


and how to handle it:
<table>
<?php foreach($var as $k=>$v):?>
<tr>
<td><?php echo $v;?></td>
</tr>
<?php endforeach;?>
</table>


Another very usefull situation is while using if
if($a==$b){
//lot of codes here
} else {
// more code..
}


alternative:
<?php if($a==$b):?>
// code
<?php endif;?>


// or


<?php if($a==$b):?>
// codes
<?php else: ?>
// codes
<?php endif;?>



There's another if alternative that's REALLY
usefull:

$a = $b==$c ? true : false ;


These are simple but very important situation. If your code is clean everything is easier, and that's what we want, right?

Give it a try! It's really usefull to take advantage of those alternative syntaxes:

for: endfor;
foreach: endforeach;
while: endwhile;
switch: endswitch;
if: endif;

Hi! My name is..

Luiz Eduardo! I'm a web developer from Brazil and I'm starting this new project called Rint.
But wait.. what's Rint?

Rint is an attempt to let internet easier at first for web developers.

Face the facts, today is really hard to search and find good sources where you can get anything else but a full (including stuff you do not want) and complex codes and concepts. That's not cool, that's not productive. That's not what we want.

What I want to bring you here is the simpliest code and concept to let you really understand how coding works and how you may adjust it to your own project. As simple as that.

Well, I hope you enjoy this!
And as a brazilian I will publish a portuguese version of all my posts too, as bellow!

Thanks,



Luiz Eduardo! Sou desenvolvedor web do Brasil e estou começando este novo projeto chamado Rint
Mas o que é Rint?

Rint é uma tentativa de deixar a internet mais fácil, a princípio para os desenvolvedores.

Encare a realidade, hoje é muito difícil procurar e encontrar boas fontes onde você pode conseguir algo além de códigos e conceitos complexos e completos (incluindo coisas que você não quer/precisa). Isso não é bom, não é produtivo. Não é o que queremos.

O que eu quero trazer aqui para vocês são os conceitos e códigos mais simples para que você realmente entenda como as coisas funcionam e como você pode adaptá-los para seu próprio projeto. Simples assim.

Espero que vocês gostem!
Todos os meus posts estarão disponíveis também em inglês!

Valeu,