saquery.com
a web developer' s kung fu…
Encode MySql distinct union data to JSON with PHP

To get a distinct dataset in MySql and embed it into Javascript in JSON format with PHP we need 3 Steps.

SQL Source Code

1st. A SQL query to get a unique domain-name list. The Sql Query Command will extract the domain-name from string columns REFERRER and URL. Then we can bring together the two datasets with the UNION DISTINCT command. The last important is the ORDER BY clause which will sort the whole result.


(SELECT  SUBSTRING_INDEX(REPLACE(REPLACE(REFERER,'http://',''),'https://',''),'/',1) AS DOMAIN FROM SAQ_CLICK_STATISTICS)  
UNION DISTINCT 
(SELECT  SUBSTRING_INDEX(REPLACE(REPLACE(URL,'http://',''),'https://',''),'/',1) AS DOMAIN FROM SAQ_CLICK_STATISTICS  order by DOMAIN)   order by DOMAIN ASC;

PHP Source Code

2nd. Based on the WordPress API we can fetch the rows as follows.

$res = $wpdb->get_results($sql);
$domains=array();
foreach ($res as $row) $domains[]=$row->DOMAIN;

Javascript Source Code

3rd. To embed the PHP data into Javascript code we simply call json_encode.

$(function() {
var 
	limitTags=["5","10","20","40","80","160"],
	availableTags = <?php echo json_encode($domains); ?>;

Vote this page

Leave a Reply