Sorgu Sonucunu Excel’e Aktarmak

<?PHP
error_reporting(4);
class ExportToExcel
{
	function exportWithPage($php_page,$excel_file_name)
	{
		$this->setHeader($excel_file_name);
		require_once "$php_page";
	}
	function setHeader($excel_file_name)
	{
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=$excel_file_name");
		header("Pragma: no-cache");
		header("Expires: 0");
	}
	function exportWithQuery($qry,$excel_file_name,$conn)//to export with query
	{
		$tmprst=mysql_query($qry,$conn);
		$header="<center><table border=1px><th>Tablo Dökümü</th>";
		$num_field=mysql_num_fields($tmprst);
		while($row=mysql_fetch_array($tmprst,MYSQL_BOTH))
		{
			$body.="<tr>";
			for($i=0;$i<$num_field;$i++)
			{
				$body.="<td>".$row[$i]."</td>";
			}
			$body.="</tr>";	
		}
		$this->setHeader($excel_file_name);
		echo $header.$body."</table";
	}
}
$conn=mysql_connect('localhost','root','')or die('bağlanmadı');
mysql_select_db('test');


//ÖRNEK
$exp=new ExportToExcel();

//$exp->exportWithPage("export_file.php","test.xls");

$qry="select * from qa_users";
$exp->exportWithQuery($qry,"test.xls",$conn);

?>

 

Google Map Koordinat Bulucu

<?php

if($_POST){
print_r($_POST);
exit;
}
?>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
  
  var placeSearch,autocomplete;
  var component_form = {
    'street_number': 'short_name',
    'route': 'long_name',
    'locality': 'long_name',
    'country': 'long_name',
    'postal_code': 'short_name'
  };
  
  function initialize() {
    autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), { types: [ 'geocode' ] });
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      fillInAddress();
    });
  }
  
  function fillInAddress() {
    var place = autocomplete.getPlace();
	var lat = place.geometry.location.lat();
	var lng = place.geometry.location.lng();
    for (var component in component_form) {
      document.getElementById(component).value = "";
      document.getElementById(component).disabled = false;
	document.getElementById("long").value = lng;
	document.getElementById("lat").value = lat;
    }
    
    for (var j = 0; j < place.address_components.length; j++) {
      var att = place.address_components[j].types[0];
      if (component_form[att]) {
        var val = place.address_components[j][component_form[att]];
        document.getElementById(att).value = val;
      }
    }
  }
    
  function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
      });
    }
  }

</script>
</head>
<body onload="initialize()">
	
  <div id="locationField">
    <input id="autocomplete" placeholder="Adresinizi Giriniz" onFocus="geolocate()" type="text"></input>
  </div>
  <form action="streetfindexportinput.php" method="post">
	Sokak No:<input id="street_number" disabled="true"/><br>
	Güzergah:<input id="route" disabled="true"/><br>
    Semt:<input id="locality" disabled="true"/><br>
    Posta<input id="postal_code" disabled="true"/><br>
    Ülke<input id="country" disabled="true"/><br>
    <input type="hidden" name="lng"  id="long" />
    <input type="hidden" name="lat"  id="lat" />
   <button type="submit">Gönder</button>
	</form>
	
  </body>
</html>

 

Google Map Arama ve Marker Ekleme

 

<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<?php
if($_POST){
?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title></title>
  <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
  <script type='text/javascript' src="http://maps.google.com/maps/api/js?sensor=true&.js"></script>
  <script type='text/javascript' src="https://raw.github.com/HPNeo/gmaps/master/gmaps.js"></script>
  <style type='text/css'>
    html,
body,
#map {
    display: block;
    width: 70%;
    height: 90%;
}
  </style>
<script type='text/javascript'>//<![CDATA[ 
$(function(){
    
    var options = {
      center : new google.maps.LatLng(<?php echo $_POST["lat"]; ?>, <?php echo $_POST["lng"]; ?>),
      zoom : 15
    };
	
    var div = document.getElementById('map');
    var map = new google.maps.Map(div, options);
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(<?php echo $_POST["lat"]; ?>,<?php echo $_POST["lng"]; ?>),
        map: map,
        title: ''
    });

});
//]]></script>

</head>
<body>
  <div id="map"></div>
</body>
</html>
<?php
}else{
?>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
  
  var placeSearch,autocomplete;
  var component_form = {
'street_address' : 'long_name',
'route' : 'long_name',//sadece sokak varsa
'country' : 'long_name',//ülke
'administrative_area_level_1' : 'long_name',//il
'administrative_area_level_2' : 'long_name',//ilçe
'administrative_area_level_3' : 'long_name',
'locality' : 'long_name',//il
'sublocality' : 'long_name',//alt bölge
'neighborhood' : 'long_name',//sadece ilçe varsa
'postal_code' : 'long_name',//posta kodu
'street_number' : 'long_name'
  };
  
  function initialize() {
    autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), { types: [ 'geocode' ] });
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      fillInAddress();
    });
  }
  
  function fillInAddress() {
    var place = autocomplete.getPlace();
	var lat = place.geometry.location.lat();
	var lng = place.geometry.location.lng();
	
	var name = place.name;
    var phone = place.formatted_phone_number;
    var fullAddress = place.formatted_address;

    for (var component in component_form) {
      document.getElementById(component).value = "";
      document.getElementById(component).disabled = false;
	document.getElementById("long").value = lng;
	document.getElementById("lat").value = lat;
	document.getElementById("fa").value = fullAddress;
	
    }
    
    for (var j = 0; j < place.address_components.length; j++) {
      var att = place.address_components[j].types[0];
      if (component_form[att]) {
        var val = place.address_components[j][component_form[att]];
        document.getElementById(att).value = val;
      }
    }
  }
    
  function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
      });
    }
  }

</script>
</head>
<body onload="initialize()">
	
  <div id="locationField">
    <input id="autocomplete" placeholder="Adresinizi Giriniz" onFocus="geolocate()" type="text"></input>
  </div>
  <form action="" method="post">
	Full Adres:<input id="fa" name="fa"/><br>
Cadde<input id="street_address" disabled="true"/><br>
Sokak<input id="route" disabled="true"/><br>
Ülke<input id="country" disabled="true"/><br>
İl<input id="administrative_area_level_1" disabled="true"/><br>
İlçe<input id="administrative_area_level_2" disabled="true"/><br>
Köy<input id="administrative_area_level_3" disabled="true"/><br>
Bölge<input id="locality" disabled="true"/><br>
Alt Bölge<input id="sublocality" disabled="true"/><br>
Mahalle<input id="neighborhood" disabled="true"/><br>
Posta<input id="postal_code" disabled="true"/><br>
Sokak No<input id="street_number" disabled="true"/><br>

Enlem<input type="text" name="lat"  id="lat" /><br>
Boylam<input type="text" name="lng"  id="long" /><br>
   <button type="submit">Gönder</button>
	</form>
	
  </body>
</html>
<?php } ?>

 

Sorgu Sonrası Yönlendirme ile Güvenlik

Özellikle insert yaparken, flood engellemek için bunu kesinlikle uygulamalısınız.

Veritabanı bağlantınızı baglan.php dosyasında hazırlayın ve mysql_query sorgusunu düzenleyin.

<?php
include("baglan.php");
$sql_kontrol =mysql_query("select or update or insert or delete vs...");
mysql_error();

if (!empty($_SERVER['HTTP_REFERER'])){//yönlendirme
  header("Location: ".$_SERVER['HTTP_REFERER']);
}else{
  header("Location: 404.html?err=referer");
}
?>

 

İki Tablo Arasındaki Farkı Bulmak

Mantık gayet basit. Birbiriyle eşleşmeyen varsa dışarıda kalıyor.

Örneğin böyle bir tablomuz olduğunu düşünürsek

CREATE TABLE urun (`id` int);
INSERT INTO urun (`id`) 
VALUES	(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);

CREATE TABLE urundetay (`id` int, `uid` int);
INSERT INTO urundetay (`id`,`uid`) 
VALUES	(1, 1),	(2, 2),	(3, 3),	(4, 4),	(5, 5),	(6, 7);

Yöntem 1

SELECT u.id FROM urun as u 
WHERE NOT EXISTS (SELECT * FROM urundetay as d WHERE d.uid = u.id )

Yöntem 2

SELECT u.id FROM urun as u 
LEFT OUTER JOIN urundetay as d ON u.id = d.uid
where d.uid IS NULL

Çıktısı

+-----+
| id  |
+-----+
|  6  |
|  8  |
|  9  |
|  10 |
+-----+

 

Eski Tarayıcılarda HTML5 Kullanabilmek

script tagı içerisinde bu kodları ekliyoruz

 (function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag(); a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}</style>"; c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode|| "undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video",version:"3.6.2",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment(); for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);

sayfa kodlarınızı ekleyerek test edebilirsiniz.

 <header>ulusanyazilim.com</header>
    <nav>Anasayfa</nav>
    <article>
        <section>
            HTML5
        </section>
    </article>
    <aside>
        Reklamlar
    </aside>
 <footer>Copyright</footer>

 

Çift Kayıtları Bulmak

Yapmış olduğum bir örneği paylaşmak istiyorum.

Flood engellememiş iseniz, bu şekilde çift kayıtları silme veya düzenleme imkanınız olabilir.

select f.* from firma as f,
	( select link,count(1) as linkSayisi 
		from firma 
		group by link 
		having count(1)>1
	) as f2 
where f.link=f2.link 
ORDER BY `f`.`link` ASC

veya

SELECT dil,link, COUNT(link) AS adet 
FROM firma 
GROUP BY link,dil 
HAVING ( COUNT(link) > 1 ) 
ORDER BY adet desc

 

Eski Tarayıcılar için Placeholder Kullanımı

Öncelikle jquery kütüphanemizi script tagı ile çağırıyoruz.

http://code.jquery.com/jquery-1.10.2.min.js

script tagı içerisine kodlarımızı yazıyoruz.

;(function(window, document, $) {

    var isInputSupported = 'placeholder' in document.createElement('input');
    var isTextareaSupported = 'placeholder' in document.createElement('textarea');
    var prototype = $.fn;
    var valHooks = $.valHooks;
    var propHooks = $.propHooks;
    var hooks;
    var placeholder;

    if (isInputSupported && isTextareaSupported) {

        placeholder = prototype.placeholder = function() {
            return this;
        };

        placeholder.input = placeholder.textarea = true;

    } else {

        placeholder = prototype.placeholder = function() {
            var $this = this;
            $this
                .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
                .not('.placeholder')
                .bind({
                    'focus.placeholder': clearPlaceholder,
                    'blur.placeholder': setPlaceholder
                })
                .data('placeholder-enabled', true)
                .trigger('blur.placeholder');
            return $this;
        };

        placeholder.input = isInputSupported;
        placeholder.textarea = isTextareaSupported;

        hooks = {
            'get': function(element) {
                var $element = $(element);

                var $passwordInput = $element.data('placeholder-password');
                if ($passwordInput) {
                    return $passwordInput[0].value;
                }

                return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
            },
            'set': function(element, value) {
                var $element = $(element);

                var $passwordInput = $element.data('placeholder-password');
                if ($passwordInput) {
                    return $passwordInput[0].value = value;
                }

                if (!$element.data('placeholder-enabled')) {
                    return element.value = value;
                }
                if (value == '') {
                    element.value = value;
                    // Issue #56: Setting the placeholder causes problems if the element continues to have focus.
                    if (element != document.activeElement) {
                        // We can't use `triggerHandler` here because of dummy text/password inputs :(
                        setPlaceholder.call(element);
                    }
                } else if ($element.hasClass('placeholder')) {
                    clearPlaceholder.call(element, true, value) || (element.value = value);
                } else {
                    element.value = value;
                }
                // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
                return $element;
            }
        };

        if (!isInputSupported) {
            valHooks.input = hooks;
            propHooks.value = hooks;
        }
        if (!isTextareaSupported) {
            valHooks.textarea = hooks;
            propHooks.value = hooks;
        }

        $(function() {
            // Look for forms
            $(document).delegate('form', 'submit.placeholder', function() {
                // Clear the placeholder values so they don't get submitted
                var $inputs = $('.placeholder', this).each(clearPlaceholder);
                setTimeout(function() {
                    $inputs.each(setPlaceholder);
                }, 10);
            });
        });

        // Clear placeholder values upon page reload
        $(window).bind('beforeunload.placeholder', function() {
            $('.placeholder').each(function() {
                this.value = '';
            });
        });

    }

    function args(elem) {
        // Return an object of element attributes
        var newAttrs = {};
        var rinlinejQuery = /^jQueryd+$/;
        $.each(elem.attributes, function(i, attr) {
            if (attr.specified && !rinlinejQuery.test(attr.name)) {
                newAttrs[attr.name] = attr.value;
            }
        });
        return newAttrs;
    }

    function clearPlaceholder(event, value) {
        var input = this;
        var $input = $(input);
        if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
            if ($input.data('placeholder-password')) {
                $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
                // If `clearPlaceholder` was called from `$.valHooks.input.set`
                if (event === true) {
                    return $input[0].value = value;
                }
                $input.focus();
            } else {
                input.value = '';
                $input.removeClass('placeholder');
                input == document.activeElement && input.select();
            }
        }
    }

    function setPlaceholder() {
        var $replacement;
        var input = this;
        var $input = $(input);
        var id = this.id;
        if (input.value == '') {
            if (input.type == 'password') {
                if (!$input.data('placeholder-textinput')) {
                    try {
                        $replacement = $input.clone().attr({ 'type': 'text' });
                    } catch(e) {
                        $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
                    }
                    $replacement
                        .removeAttr('name')
                        .data({
                            'placeholder-password': $input,
                            'placeholder-id': id
                        })
                        .bind('focus.placeholder', clearPlaceholder);
                    $input
                        .data({
                            'placeholder-textinput': $replacement,
                            'placeholder-id': id
                        })
                        .before($replacement);
                }
                $input = $input.removeAttr('id').hide().prev().attr('id', id).show();
                // Note: `$input[0] != input` now!
            }
            $input.addClass('placeholder');
            $input[0].value = $input.attr('placeholder');
        } else {
            $input.removeClass('placeholder');
        }
    }

}(this, document, jQuery));

sayfa kodlarımızı ekliyoruz

<form>
    <input id="input" name="" type="text" placeholder="Birşeyler Arayın.."/>
</form>

en alta script tagı içerisine kodlarımızı ekliyoruz.

 $(function() {
        $('input, textarea').placeholder();
        var html;
        if ($.fn.placeholder.input && $.fn.placeholder.textarea) {
         html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> and <code>textarea</code> elements.</strong> The plugin won’t run in this case, since it’s not needed. If you want to test the plugin, use an older browser ;)';
        } else if ($.fn.placeholder.input) {
         html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> elements, but not for <code>textarea</code> elements.</strong> The plugin will only do its thang on the <code>textarea</code>s.';
        }
        if (html) {
         $('<p class="note">' + html + '</p>').insertAfter('form');
        }
     });

 

Localhost ve Web Seçmeli Veritabanı

Tek bir uygulamayı hem localhost’da düzenleyip hem sitenizde yayınlarken büyük kolaylık. Veritabanı bilgilerini değiştirmeden ikisinde birden rahatlıkla çalışabileceksiniz.

<?php header('Content-Type: text/html; charset=utf-8');
function remote_connect($dbhost,$dbuser,$dbpass,$dbname,$lang){
if($lang="en"){//Eng Lang
$error_db_connect_www='<!--Could not connect to the online database-->';
$error_dbselect_www='<!--Online database not selected-->';
$connect_ok_www='<!--Connected to the online database-->';
$error_db_connect_local='<!--Could not connect to the local database-->';
$error_dbselect_local='<!--Local database not selected-->';
$connect_ok_local='<!--Connected to the local database-->';
}
if($lang="tr"){//Tr Dil
$error_db_connect_www='<!--Çevrimiçi veritabanı ile bağlantı sağlanamadı-->';
$error_dbselect_www='<!--Çevrimiçi veritabanı seçilemedi-->';
$connect_ok_www='<!--Çevrimiçi veritabanına bağlanıldı-->';
$error_db_connect_local='<!--Yerel veritabanı ile bağlantı sağlanamadı-->';
$error_dbselect_local='<!--Yerel veritabanı seçilemedi-->';
$connect_ok_local='<!--Yerel veritabanına bağlanıldı-->';
}
        $connect = @mysql_connect($dbhost["www"], $dbuser["www"] , $dbpass["www"]);
        if(!$connect){
            echo $error_db_connect_www;
        }
        $db = @mysql_select_db( $dbname["www"] , $connect);
        if($db){
            echo $connect_ok_www;
        }
        else{
            echo $error_dbselect_www;
    $connect = @mysql_connect($dbhost["local"], $dbuser["local"] , $dbpass["local"]);
        if(!$connect){
            echo $error_db_connect_local;
        }
    $db = @mysql_select_db( $dbname["local"] , $connect);
        if($db){
            echo $connect_ok_local;
        }
        else{
            echo $error_dbselect_local;
        }
    }
}
$db_host=array();
$db_user=array();
$db_pass=array();
$db_name=array();
//www Connect
$db_host["www"] =   "localhost";        
$db_user["www"] =   ""; 
$db_pass["www"] =   "";
$db_name["www"] =   "p";
//Local Connect
$db_host["local"]   =   "localhost";        
$db_user["local"]   =   "root"; 
$db_pass["local"]   =   "";
$db_name["local"]   =   "survivor";
$lang ="tr"; //en
remote_connect($db_host,$db_user,$db_pass,$db_name,$lang);

?>

 

Eklentisiz WordPress Meta Etiketi ile Seo Oluşturmak

Temanızın içindeki header.php‘yi açıp head tagları arasına yapıştırın. Kendinize göre değiştirebilirsiniz.

<meta name="resource-type" content="document" />
<meta http-equiv="content-type" content="text/html;" />
<meta http-equiv="content-language" content="tr-TR" />
<meta name="author" content="Ulusan" />
<link rel="author" href="https://plus.google.com/+MehmetAliUlusan/posts"/>
<meta name="contact" content="ulusanyazilim@gmail.com" />
<meta name="copyright" content="Copyright (c)2006-2018 UlusanYazılım. All Rights Reserved." />
<meta name="description" content="<?php if ( is_single() ) {
		single_post_title('', true); 
} else {
		bloginfo('name'); echo " - "; bloginfo('description');
}
?>" />
<?php
function csv_tags() {
	$posttags = get_the_tags();
	foreach((array)$posttags as $tag) {
		$csv_tags .= $tag->name . ',';
	}
	if($csv_tags == ","){$csv_tags="";}
	$csv_tags .=",ulusanyazilim";
	return $csv_tags;
}?>
<meta name="keywords" content="<?php echo csv_tags(); ?>" />