CSV Export

$header = "product_id,sku,name,cost,rrp,our_price,sale_price,clearance_price,supplier_gross_price,supplier_net_price\n";
$data  = $header;
$sql = "SELECT * FROM products ORDER BY product_id ASC";
$rs = mysql_query($sql);
while($row = mysql_fetch_assoc($rs)){
	$data .= $row['product_id'].",".$row['sku'].",".$row['name'].",".$row['cost'].",".$row['rrp'].",".$row['our_price'].",".$row['sale_price'].",".$row['clearance_price'].",".$row['supplier_gross_price'].",".$row['supplier_net_price']."\n";
}

$file_name = "product_price.csv";
ob_clean();
echo $data;
header("Content-type: application/csv"); 
header("Content-Disposition: attachment; filename=$file_name");
header("Pragma: no-cache");
header("Expires: 0");

important Queries

1)->Copy one table data to another into same database
==================================================
insert into products(product_id,manufacturer_ref,sku,name,long_desc,dimension_unit,notes,rrp,our_price,sale_price,clearance_price,other_stock,weight,range_name,supplier,family)
select product_id,product_ref,product_name,product_short_description,product_description,product_dimensions,product_additional_notes,product_rrp,product_price,product_sale_price,product_clearance_price,product_stock,product_weight,product_range,product_supplier,family_id from products_live

2)->Copy one table data to another into same database and concat two field
=======================================================================
insert into products_t(title,description,price,link,image_link)
 select product_short_description,product_description,product_rrp,
 CONCAT('http://www.lighting-by-gabrielli.co.uk/products/',
	REPLACE((SELECT name FROM categories WHERE categories.category_id = products.category_id), ' ', '-'),
	'/',product_id,'/',product_name,'/'),
 CONCAT ('http://www.lighting-by-gabrielli.co.uk/_images/products/',product_id, '_2.jpg')
 from products

3)->Copying one database table to another database table on same server
=========================================================================
$mss_sc = array("mss_ltd"=>array( "host_name"=> "localhost","username" => "root","password" => "","db_name" => "grand_kitchen")
				);
	foreach($mss_sc as $site_name => $site_val){
		$conn = mysql_connect($site_val['host_name'],$site_val['username'],$site_val['password']) or die(mysql_error());
		mysql_select_db($site_val['db_name'],$conn)or die("error in select in db");
		///// for creating and inserting product ////////////////////////////
		mysql_query("DROP TABLE products");
		mysql_query("CREATE TABLE products LIKE mss_sc.products") or die(mysql_error());
		mysql_query("INSERT INTO products SELECT * FROM mss_sc.products") or die(mysql_error());
		///// for creating and inserting category ////////////////////////////
		mysql_query("DROP TABLE category");
		mysql_query("CREATE TABLE category LIKE mss_sc.category") or die(mysql_error());
		mysql_query("INSERT INTO category SELECT * FROM mss_sc.category") or die(mysql_error());
		mysql_close($conn);
	}

4)->Copying one database table to another database table on diffrent server
=========================================================================
$mss_sc = array("grand-kitchens"=>array("host_name"=> "grand-kitchens.co.uk",
								  "username" => "web150-majestic",
								  "password" => "majestic123!",
								  "db_name" => "web150-majestic"),
			    "mss_ltd"=>array( "host_name"=> "217.199.187.63",
								  "username" => "cl51-gkgranite",
								  "password" => "2VEB-Ry2N",
								  "db_name" => "cl51-gkgranite")
				);

$dblink1=mysql_connect('92.60.121.118', 'mss_sc', 'mss_sc') or die(mysql_error()); // connect server 1
mysql_select_db('mss_sc',$dblink1) or die(mysql_error());  // select database 1

	foreach($mss_sc as $site_name => $site_val){
		$dblink2=mysql_connect($site_val['host_name'], $site_val['username'], $site_val['password']) or die(mysql_error()); // connect server 2
		mysql_select_db($site_val['db_name'],$dblink2) or die(mysql_error()); // select database 2

				///// for creating and inserting product ////////////////////////////
				$table='products';
				mysql_query("DROP TABLE IF EXISTS $table",$dblink2) or die(mysql_error());
				$tableinfo = mysql_fetch_array(mysql_query("SHOW CREATE TABLE $table  ",$dblink1)); // get structure from table on server 1
				mysql_query(" $tableinfo[1] ",$dblink2); // use found structure to make table on server 2
				$result = mysql_query("SELECT * FROM $table  ",$dblink1); // select all content
				while ($row = mysql_fetch_array($result, MYSQL_ASSOC) ) {
					   mysql_query("INSERT INTO $table (".implode(", ",array_keys($row)).") VALUES ('".implode("', '",array_values($row))."')",$dblink2); // insert one row into new table
				}
				///// for creating and inserting category ////////////////////////////
				$table='category';
				mysql_query("DROP TABLE IF EXISTS $table",$dblink2) or die(mysql_error());
				$tableinfo = mysql_fetch_array(mysql_query("SHOW CREATE TABLE $table  ",$dblink1)); // get structure from table on server 1
				mysql_query(" $tableinfo[1] ",$dblink2); // use found structure to make table on server 2
				$result = mysql_query("SELECT * FROM $table  ",$dblink1); // select all content
				while ($row = mysql_fetch_array($result, MYSQL_ASSOC) ) {
					   mysql_query("INSERT INTO $table (".implode(", ",array_keys($row)).") VALUES ('".implode("', '",array_values($row))."')",$dblink2); // insert one row into new table
				}
			mysql_close($dblink2);
	}

mysql_close($dblink1);
5) ->
=========================================================================
SELECT schooname, COUNT(*), GROUP_CONCAT(jobassign.id) AS jobassignids FROM `jobassign` LEFT JOIN job ON job_id=job.`id` GROUP BY job.`id`

It will put all jobs with comma separated values in jobassignids column so we don't have to loop through the records to get all the related ids.

You can use GROUP_CONCAT where you want its a useful function.

6) -> Removing , and concat etc  
========================================================================
SELECT REPLACE( email, ',', '' ) AS email, CONCAT( REPLACE(first_name, ',', '' ), " ", REPLACE(last_name, ',', '' ) ) AS name
FROM `user` group by email LIMIT 10001 , 15000

Auto Complete Searching

Auto Complete

Php code for auto complete ————–


$product_name_string = array();

	$query_result 	= 	$db->query("SELECT * FROM products ORDER BY name");
	if($db->numRows($query_result)) {	
		while($row = $db->next_record($query_result)){
			//$product_name_string .='"'.trim($row['name']).'--'.$row['product_id'].'", ';
			array_push($product_name_string,array('label'=>$row['name'],'id'=>$row['product_id']));
		}
		$_SESSION['product_name_string'] = $product_name_string;
	}

Jquery code for auto complete ——————


$(document).ready(function(){
	////////////////// Searching Medicine ///////////////////////////////////////////
    var availableProducts = <? echo json_encode($_SESSION['product_name_string']);?>;	
    $(".search_text").live("focus", function() {
		$(".search_text").autocomplete({
			source: availableProducts,
			delay: 0,
			minLength:1,
			select: function (event, ui) { 
				productId = ui.item.id;				
				$("#product_id").val(productId);
			}			
		});	
	});

updating single field through ajax


javascript ------------->
$('.update_invoice_button').click(function(){
		var new_invoice_no = $(this).parent().find('.new_invoice_no').attr("value");		
		var fee_id = $(this).parent().find('.new_invoice_no').attr("width");		
		
		//return false;
		
			var form_data 	= {'table':'fee',
						   'where_column':'id',
						   'where_value':fee_id,
						   'update_column':'invoice_no',
						   'new_value':new_invoice_no
						   };		
			$.ajax({
				async: false,
				type: "POST",
				url: site_url+"/modules/reports/index.php?page=ajax_actions&action_page=update_field",
				data: form_data,
				success: function(result){
					var resultObj = jQuery.parseJSON(result);    		
					alert(resultObj.message)
				}
			});
		
	});

php on update_field -------------->
<?
$table 			= $_REQUEST['table'];
$where_column 	= $_REQUEST['where_column'];
$where_value 	= $_REQUEST['where_value'];
$update_column 	= $_REQUEST['update_column'];
$new_value 		= $_REQUEST['new_value'];

$sql = "UPDATE $table SET $update_column ='$new_value' WHERE $where_column=$where_value ";

$returnArray = array();
if(mysql_query($sql)){
	$returnArray['status'] = "success";	
	$returnArray['message'] = ucfirst($update_column)." updated successfully";
}else{
	$returnArray['status'] = "failure";
	$returnArray['message'] = "Error in updating, please contact admin";
}
echo json_encode($returnArray);
die;

Facebox (colorbox) through css and html

Div which is shown on facebox-------------
<div class="overlay" style="overflow: auto;">
	<div class="confirmbox" style="margin: 3% auto;display:none;">
		<span>
			<img style="cursor:pointer;float:right;" title="Close" onclick="javascript:close_overlay();" src="img/del.gif" border="0">
			<div id='content_container'></div>
		</span>
	</div>
</div>
javascript

<script type="text/javascript">
function close_overlay(){
		$('.overlay').hide('slow');	
	}		
$(document).ready(function(){

	$('.terms_link').live('click',function(){
		var content = $(this).parent().find(".terms_link_data").html();
		$('#content_container').html(content);
		$(".confirmbox").css('height','40%');
		$(".confirmbox").css('width','40%');      		
		$(".overlay").show('slow');
		$(".confirmbox").css('display','block');   
	});
});
</script>
html apply here------------
<td style='border:solid 1px #245F9B;' align="center" >
				<div style='display:none;' class="terms_link_data">
					<? echo $data['comment'];?>
				</div>
				<a href='#' style='text-decoration:none;' class='terms_link'>
					<? echo ellipsis(ucfirst($data['comment']),50);?>
				</a>
			</td>