Learn , Share , Enjoy

MySQL FullText Searching

Suppose you want to search a keyword in 5 different columns or almost in all the fields of the table, then MySQL
provides us with fulltext indexing and searching method.

Before using this method , you need to add FullText to the columns in which you want to search.

ALTER TABLE member ADD FULLTEXT(firstname, lastname,address);

Then comes your main query :

SELECT firstname, lastname,address FROM member
WHERE MATCH (firstname,lastname,address) AGAINST (’test’);

The Match will look for “exact match” in the above 3 columns and on successfull match it will return that row.

Suppose in member table there is a an entry with firstname = test then the output will be :

firstname lastname address

test abc xyz

Suppose you want to use wildcards then modify your query :

SELECT firstname, lastname,address FROM member
WHERE MATCH (firstname,lastname,address) AGAINST (’*test*’);


Custom Events in jquery

we can fire custom events in jquery and set an event handler for each event .

This enables loose coupling and code reuse . This can be used to achieve the observer design pattern .

$(’#txtAddress’).keyup(function() {

$(document).trigger(’ADDRESS_CHANGE’);

});

$(’#txtCity’).keyup(function() {

$(document).trigger(’CITY_CHANGE’);

});

to now bind the event :

$(document).bind(’ADDRESS_CHANGE’, function(e) {
UpdateName();
UpdateOtherText(e);
});

Hack Away ;)


How to use MySQL FOUND_ROWS()?

MySQL has  a function called FOUND_ROWS which is faster than any other function for counting rows which is returned by the latest query, it is used same as MySQL “LASTINSERT_ID()”.

For example: if we are developing a pagination script  and we want the total number of results returned by the Query, at the same case in pagination we use LIMIT for paging the record using the above function it will not return the limit results it will return the total available results.

How to use? suppose we have 20 records in our table and we are fetching only 10 records in a page, then the $total will return total 20 not 10.

$sql = “SELECT SQL_CALC_FOUND_ROWS * FROM tablename LIMIT 1, 10 “;

$results = mysql_query($sql);

$total = mysql_query(’SELECT FOUND_ROWS() as total’);


Css Hack

I spent about 35 minutes on this one and still havent found a logic to it .

But this hack should be remembered .

consider the markup : <div id = a ><input/><div id = “a_child” ></div>    </div>

if you need to give a bottom border to the div with id = a and expect it to come below the div with id = “a_child”  , then the following css needs to be in place :

#a{  height:auto;overflow:hidden;}

Thanks to vineet and jimit  to get out of this one ..


word wrap for an editable div

To make a div or a paragraph editable set the attribute -  contenteditable = true

give a fixed width to the div : -   width:100px ;

after 100px the word should wrap down , for this add the css property :

word-wrap:break-word;

Happy Hacking :)


Simple way of converting a jquery object to javascript object

Sometimes while using jquery we need to get the javascript object of a dom element to call javascript functions on them.
For eg suppose we want to find the scrollHeight of a div. In case this div is given an id then it can be very easily done using
var divObj = document.getElementById(”myid”);
var sH = divObj.scrollHeight;

but what if we want to find the scrollHeight of tbody element inside a table inside the div#myid
in jquery we traverse it using $(”#myid>table>tbody”)

var sH = $(”#myid>table>tbody”)[0].scrollHeight;

This will return us the 1st element of the array. If there is only one such tbody, it will give us the required Object to call the function


Getting first day of the month in mysql

Here is a small trick to get first day of the month
SELECT DATE_SUB(now(),INTERVAL (DAY(now())-1) DAY)

This will give you the first day of the current month. You can also get first day of the month for a given date just pass the date instead of now()
SELECT DATE_SUB('2010-08-10',INTERVAL (DAY('2010-08-10')-1) DAY)


TD border for empty cell in IE

IE does not allow to create a border around an empty cell hence a wise trick to apply here is in the script part write the following code .

$(document).ready(function(){

$(”td:empty”).html(”&nbsp; “);
}

The code replaces all empty cell data with blank spaces( &nbsp;) and creating a border around empty data


condition to determine if a javascript variable has been defined or not

In php to determine if a certain variable is set we use the function,


isset($variable)



it returns a boolean value.
To do the same thing in javascript, use the following condition,


if(typeof variable != ‘undefined’){
alert(’This variable is not defined yet’);
}
else {
alert(’The variable is defined’);
}


Fire Bug for every browser

Paste the following code in your [head]  section and firebug will run in any browser :

[script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'] [/script]

Replace [] with <> accordingly

C trick

value of a variable which was last initialised can be printed without specifying variable name !!!
#include
#include

void main()
{
int a,b,c;
clrscr();
printf(”Enter No. C:”);
scanf(”%d”,&c);
printf(”%d”); /* printf(”%d”,c) is not required*/
getch();
}


Adding your own custom functions to jquery

hide(),show(),empty()…this are predefined functions of jquery.
So, to add your own function , you just have to write small piece of code :

$.fn.myFunction = function() {
return $(this).addClass(’changed’);
}

And now, use it like this:

$(’.changePlease’).myFunction();

:D


What is (function($){…})(jquery) ??

All jQuery plugins code is wrapped in this anonymous function.So what exactly this function do ??
Well,my little research shows that this allows the use of $ within this function without conflicting with other JavaScript libraries who are using it. Basically, since we are setting $ as a parameter, $ will overwrite any globally defined variables/references of $ in that particular anonymous function.

// Assume “$” is a prototype reference
(function ($) {
// Here “$” is a jQuery reference
})(jQuery)


mysql manual from command line

the mysql manual can be accessed  from the command line itself as follows :

help “<search term>”;


explicitly call super class constructor in php

Unlike Java , the constructor of the super class will not be called implicitly in PHP .

To call the parent class constructor from the child class we can use :

parent::construct();


MySQL – The GROUP_CONCAT() function

GROUP_CONCAT() function is used to concatenate column values into a single string.
Example:
Table ‘abc’ has following columns:
id customer_id
3 14
3 15
3 16
4 18
4 18

You can use this query:
SELECT id,GROUP_CONCAT(customer_id) FROM abc WHERE id = 3 GROUP BY id;

output:
id customer_id
3 14,15,16

It is useful when you want PHP array without looping inside PHP:


How to destroy or remove Tiny MCE control from jquery dialog on ajax request?

To use tiny mce in a jquery dialog and clear the contents of tinymce  on close of the overlay use the following function :

$(”id-for-dialog”).bind( “dialogclose or dialogbeforeclose”, function(event, ui) {
tinyMCE.execCommand( ‘mceRemoveControl’, true, ‘id-for-editor’ );
});

This will enable loading of new content into the tinymce editor whenever the jquery dialog reopens .


sending additional data to server along with jquery’s .serializeArray object

Many times we use jquery’s .serializeArray function to send form field values by $.post or $.ajax methods. Suppose we want to send some other data besides serialized form data, it can be done by pushing additional objects into the array returned by .serializeArray as follows

var data = $(”#my-form”).serializeArray();
data.push({ ‘name’:'category_id’ , ‘value’:this.categoryId });
data.push({ ‘name’:'entity_id’, ‘value’:this.entityId });

the elements returned by serializeArray are objects with properties ‘name’ and ‘value’ .. Once the post request is sent these can be accessed on the server side as $_POST['category_id'] and $_POST['entity_id'] just like the other parameters.

This method is better over hidden input field method particularly when dynamic values are needed to be set to the hidden form fields using javascript.


toggleText for jQuery

Unfortunately JQuery doesn’t have function to toggle text of a given element :( . But here is a trick by which you can add toggleText function to your jQuery.

jQuery.fn.toggleText = function(a, b) {
return this.each(function() {
jQuery(this).text(jQuery(this).text() == a ? b : a);
});
};

code:
$(element).toggleText('Preview','Back');


Convert ‘null’ to 0 in mysql

To convert a null value to zero returned by a mysql query use the function COALESCE(value,…)

Mysql Query :

SELECT COALESCE(column_that_might_be_null,0) as column_with_null_converted_to_zero FROM table_with_column_that_might_be_null;


A simple trick for adding html code using js

If you want to add a relatively large chunk of html code to the DOM using javascript, and if you find it annoying to write the markup as a string in js, here is a simple trick!

write the mark up normally in the html and use inline display:none to hide it

[html]

….

[html]

now in js (using jquery)

//for inserting dynamic html, insert all the required values in the dummy div first and then assign the inner content to a variable

$(”.htmltoadd>p”).html(’Hello World’);

var myhtml = $(”.htmltoadd”).html();

$(”#required-container”).html(myhtml’);


Adding date and time in PHP

I came across a situation where i want to end an event exactly after two days and before an hour of third day ( i.e. 11:00 pm on third day). After searching on google and checking the date function in php manual i came to this solution

$new_date = ( strtotime(’-1 hour’,strtotime ( ‘+3 day’ , strtotime (date ( ‘Y-m-d’ ) ) ) ));

This will return a unix timestamp which will give you 11:00 pm of third day.
eg. if todays date is 27/05/2010 07:08:15 then it will give you 29/05/2010 23:00:00


Background Opacity to be set in CSS

Ever wondered how you could change the opacity of the background or adjust the alpha quantity for it here is a trick to do so :
e.g.If you want to set a background for body then
in the CSS this is what should follow

body
{background rgba(82,82,82,0.7)}

here ‘rgb’ is for the red,green,blue values respectively and ‘a’ is the alpha/opacity for the background


How to attach callback functions

To attach a callback function in js :

function test(callback){

//some code for test function

if(callback && typeof callback == ‘function’){
callback.call();
}

}

test(doendtest);

The endtest function will execute after the test function .


Using conditions in mysql queries

If we want to use “if then” conditions in our code, in some cases, it can be done in mysql queries itself. For eg .
SELECT IFNULL(a,b) ) as val
In the above statement, the value of val will be equal to “a” if “a” is not null or it will be “b” if “a” is null.

another peculiar eg is “(SELECT IFNULL(special_price,p.price) ) as current_price” where the value of special_price is coming from another query in the same sql string (multiple queries).


passing a string as get param in curl response

while using curl in application for requesting the remote URL, be careful it doesn’t contain any white space, if it contains the white space it will show you a 400 error!.. To solve  of this, replace blank space  in the url with “+” .  Hope this trick is useful .

Happy Coding !


how to bind a function to different UI elements on multiple events

suppose there are 2 buttons with id’s of “test” and “test4″
we want to bind the function with name as “getmember” on click of “test” and mouseout of “test4″ then
$(’#test’)['click'](getmember);
$(’#test4′)['mouseout'](getmember);

Hope this is useful :)


Switch off autocomplete for all inputs and select boxes

For a lot of forms we need to switch off autocomplete by the browser . This should be done for payment details forms .
This can be easily done by a jquery one liner .
$(’input,select’).attr(”autocomplete”,”off”);


mysql storage engines

myisam is the default storage engine . it is optimised for speed .innodb is optimised for data integrity . I am not sure which one to use when :) (feel free to comment on this ) . To change from myisam to innodb -
ALTER TABLE tbwithMyISAM CHANGE TYPE=InnoDB


using jquery’s ui draggable with jquery’s .live method

To use jquery ui draggable on dom elements that will be added to the doc later, the initialization can be done on its mouseover event by using .live() method of jquery

as in

$(”#newdiv”).live(’mouseover’,function(){

$(this).draggable({

stop: function(){
//do something
}

});

});


eclipse shortcut

to view the defination of a method , just press the ctrl key and click on the method name .


Determine element is visible or not

if($(’element:visible’).length < 1){
alert(’Element is In Visible’);
}
else{
alert(’Element is Visible’);
}


Retriving multiple values from a single field of your database

if your having a field in your table which holds multiple values and you want to display the same.then use “spliti”
example:
company_dept is the field name.
$sql=”SELECT *from table_name”;
$ex=mysql_query($sql)
$result=mysql_fetch_array($ex);

$cmp_dept=$result['company_dept'];//when you echo this will display all the values
suppose you want single value then

$dept=spliti(”,”, $cmp_dept, 5);//this will split a string into array

$cnt=count($dept);//this will count the number of elements in the array

for output:print_r($dept)
or echo $dept[0];

spliti is case insensitive whereas split is not.
for more info visit:http://www.php.net/manual/en/function.spliti.php


Inserting multiple values from a listbox into the database

if you have a listbox called “department” and want to insert multiple values from the listbox into the database,then:
when the user submits the form,store the value in a variable
$company_dept=$_POST['department'];
query:INSERT into table_name values(’”.join(”,”,$company_dept).”‘)


validate email in javascript

var str = $(”#email”).val();
if((str.indexOf(”.”) > 2) && (str.indexOf(”@”) > 0) && ((str.indexOf(”.”) + 1) < str.length-1)){
alert(”valid”);
}
else{
alert(”Invalid”);
}


Eclipse shortcut

To comment out a line of html code in eclipse IDE , use the following shortcut
ctrl + /


Email check in php

function isValidEmail($email){
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]
+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

Make your css dynamic

To implement constants in css , let your php script output as css by passing the following headers :

header(’content-type:text/css’);
header(”Expires: “.gmdate(”D, d M Y H:i:s”, (time()+900)) . ” GMT”);


Using Column alias in where clause

select (basicsal + hra) as salary from employee where salary > 5000
It will give error (Unkown column salary in where clause.
Instead you can use :
select (basicsal + hra) as salary from employee having salary > 5000


Wordpress – different single.php for different categories

if you have a category called photos and another category called videos , you need to format the single.php differently for each category . this is easy and you can just write the following code in single.php :

if ( in_category(’2′) ) {
include(TEMPLATEPATH . ‘/single-kodetricks.php’);
}
else
include(TEMPLATEPATH . ‘/single-blog.php’);


To display 2 decimal after , Javascript

to display 2 decimal after any number use toFixed() function of javascript
eg. var num = 25;
alert(num.toFixed(2));
it will give 25.00 instead of only 25


Website speed

we can minimise all the js and place it in a single file at the end of the project .
this will reduce the number of http requests and save response time


Post A Trick !

How does "Kodetricks" work?

We at kodeplay like to share knowledge. With Kodetricks, even you can join us. All you need to do is post a programming related trick if you have one or rate a trick if you like someone else's.


Find us on

Technology

Contact Us