Posts Tagged ‘mysql’

PHP Class Pagination alias Pengaturan Data per Halaman

This item was filled under [ Code Snippet, MySQL, PHP ]

Screenshot sebagai berikut:

Berikut php class pagination, pada script disertakan juga keterangan komentar pada file script.

<?php
class JinPagination {
	// fungsi pengaturan/option $this->blabla = "value nya blabla"
	function setOption($field, $value) {
		$this->$field = $value;
	}
	// fungsi paginasi generate array berupa total jumlah halaman, pagination, data dan posisi start 
	// berguna untuk diatur secara fleksible terutama untuk berbasis menggunakan template
	function build() {
		// SETUP
		$tabel = $this->tabel;
		$where = $this->where;
		$limit = $this->limit;
		$order = $this->order;
		$page = $this->page;
 
		// SETUP OPTIONAL
		if(!isset($this->web_url_page)) { $web_url_page = "?page="; } else { $web_url_page = $this->web_url_page; }
		if(!isset($this->adjacents)) { $adjacents = "3"; } else { $adjacents = $this->adjacents; }
		if(!isset($this->txt_prev)) { $txt_prev = "&laquo; prev"; } else { $txt_prev = $this->txt_prev; }
		if(!isset($this->txt_next)) { $txt_next = "next &raquo;"; } else { $txt_next = $this->txt_next; }
		if(!isset($this->txt_titik)) { $txt_titik = "..."; } else { $txt_titik = $this->txt_titik; }
 
		$query = mysql_query("SELECT * FROM ".$tabel." ".$where."");
		//$total_pages = mysql_fetch_array(mysql_query($query));
		//$total_pages = $total_pages['num'];
		$total_pages = mysql_num_rows($query);
 
		if($page) {
			$start = ($page - 1) * $limit; 			//first item to display on this page
		} else {
			$start = 0;								//if no page var is given, set start to 0
		}
		// Get data.
		$query = "SELECT * FROM ".$tabel." ".$where." ".$order." LIMIT ".$start.", ".$limit."";
		$hasil = mysql_query($query);
 
		/* Setup page vars for display. */
		if ($page == 0) $page = 1;					//if no page var is given, default to 1.
		$prev = $page - 1;							//previous page is page - 1
		$next = $page + 1;							//next page is page + 1
		$lastpage = ceil($total_pages/$limit);		//lastpage is = total pages / items per page, rounded up.
		$lpm1 = $lastpage - 1;						//last page minus 1
 
		/* 
			Now we apply our rules and draw the pagination object. 
			We're actually saving the code to a variable in case we want to draw it more than once.
		*/
		$pagination = "";
		if($lastpage > 1) {
			$pagination .= "<div class=\"pagination\">";
			//previous button
			if ($page > 1) {
				$pagination .= "<a href=\"".$web_url_page.$prev."".$extra_href."\">" . $txt_prev . "</a>";
			} else {
				$pagination .= "<span class=\"disabled\">" . $txt_prev . "</span>";	
			}
			//pages
			if ($lastpage < 7 + ($adjacents * 2)) {
				//not enough pages to bother breaking it up
				for ($counter = 1; $counter <= $lastpage; $counter++) {
					if ($counter == $page) {
						$pagination .= "<span class=\"current\">".$counter."</span>";
					} else {
						$pagination .= "<a href=\"".$web_url_page.$counter."".$extra_href."\">".$counter."</a>";
					}
				}
			}
			elseif($lastpage > 5 + ($adjacents * 2)) {
				//enough pages to hide some
				if($page < 1 + ($adjacents * 2)) {
					//close to beginning; only hide later pages
					for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) {
						if ($counter == $page) {
							$pagination .= "<span class=\"current\">".$counter."</span>";
						} else {
							$pagination .= "<a href=\"".$web_url_page.$counter."".$extra_href."\">$counter</a>";
						}
					}
					$pagination .= $txt_titik;
					$pagination .= "<a href=\"".$web_url_page.$lpm1."".$extra_href."\">".$lpm1."</a>";
					$pagination .= "<a href=\"".$web_url_page.$lastpage."".$extra_href."\">".$lastpage."</a>";		
				}
				elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
					//in middle; hide some front and some back
					$pagination .= "<a href=\"".$web_url_page."1".$extra_href."\">1</a>";
					$pagination .= "<a href=\"".$web_url_page."2".$extra_href."\">2</a>";
					$pagination .= $txt_titik;
					for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) {
						if ($counter == $page) {
							$pagination .= "<span class=\"current\">".$counter."</span>";
						} else {
							$pagination .= "<a href=\"".$web_url_page.$counter."".$extra_href."\">".$counter."</a>";
						}
					}
					$pagination .= $txt_titik;
					$pagination .= "<a href=\"".$web_url_page.$lpm1."".$extra_href."\">".$lpm1."</a>";
					$pagination .= "<a href=\"".$web_url_page.$lastpage."".$extra_href."\">".$lastpage."</a>";
				} else {
					//close to end; only hide early pages
					$pagination .= "<a href=\"".$web_url_page."1".$extra_href."\">1</a>";
					$pagination .= "<a href=\"".$web_url_page."2".$extra_href."\">2</a>";
					$pagination .= $txt_titik;
					for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
						if ($counter == $page) {
							$pagination .= "<span class=\"current\">".$counter."</span>";
						} else {
							$pagination .= "<a href=\"".$web_url_page.$counter."".$extra_href."\">".$counter."</a>";
						}
					}
				}
			}
 
			//next button
			if ($page < $counter - 1) {
				$pagination .= "<a href=\"".$web_url_page.$next."".$extra_href."\">" . $txt_next . "</a>";
			} else {
				$pagination .= "<span class=\"disabled\">" . $txt_next . "</span>";
				$pagination .= "</div>\n";
			}
		}
		// hasil dari fungsi build()
		return array(	"pagination" 	=> $pagination, 
						"total" 		=> number_format($total_pages),
						"hasil"			=> $hasil,
						"start"			=> $start
					);
	}
}
 
 
// Penggunaan Class
// koneksi DB
// asumsikan kita sudah terkoneksi dengan database MySQL
 
// Setting CSS
$isi = "";
$isi .= "
<style>
/* optional */
body {
	background-color:#fff;
	font-size:11px;
	font-family:Verdana;
	margin:0;
	padding:0;
	color:#555555;
}
/* END - optional */
 
/* PAGINATION */
div.pagination {
	padding: 3px 0 3px 0;
	margin: 0;
}
 
div.pagination a {
	padding: 2px 5px 2px 5px;
	margin: 2px;
	border: 1px solid #AAAADD;
 
	text-decoration: none; /* no underline */
	color: #000099;
}
div.pagination a:hover, div.pagination a:active {
	border: 1px solid #000099;
 
	color: #000;
}
div.pagination span.current {
	padding: 2px 5px 2px 5px;
	margin: 2px;
		border: 1px solid #000099;
 
		font-weight: bold;
		background-color: #000099;
		color: #FFF;
	}
	div.pagination span.disabled {
		padding: 2px 5px 2px 5px;
		margin: 2px;
		border: 1px solid #EEE;
 
		color: #DDD;
	}
/* END - PAGINATION */
</style>
";
// optional CSS display
echo $isi;
// bikin object
$hal = new JinPagination;
// setup paginasi
$hal->setOption("tabel", "jaw_airport"); // nama tabel database
$hal->setOption("where", "WHERE `cek_aktif`='1'"); // where kondisi, kosongkan jika tidak memakai WHERE
$hal->setOption("limit", "10"); // LIMIT tampilan per halaman
$hal->setOption("order", "ORDER BY `code` DESC"); // urutan, kosongkan jika tidak memakai urutan
$hal->setOption("page", $_REQUEST["page"]); // setup untuk ambil variable angka halaman (berguna jika menggunakan SEO url, ubah sesuai dgn kebutuhan)
$hal->setOption("web_url_page", "?page="); // setup alamat url (berguna jika menggunakan SEO url, ubah sesuai dgn kebutuhan)
// optional setup
$hal->setOption("adjacents", "5"); // tampil berapa angka ke kanan dan ke kiri nya, jika kita diposisi tengah halaman
$hal->setOption("txt_prev", "&laquo; sebelumnya"); // mengubah text "prev" menjadi "sebelumnya"
$hal->setOption("txt_next", "berikutnya &raquo;"); // mengubah text "next" menjadi "berikutnya"
// generate hasil pagination
$hal_array = $hal->build();
// setup penomoran
$no = $hal_array["start"] + 1;
// tampilkan
echo "<h1>Demo Data Pagination</h1>";
echo $hal_array["pagination"]; // tampilkan pagination diatas
echo "<br /><br />";
// data
while($data = mysql_fetch_array($hal_array["hasil"])){
	echo $no . ". " . $data['code'] . " - ".$data['nama']." <br>";
	$no++;
}
echo "<br />";
echo "total: " . $hal_array["total"]; // tampilkan total data
echo $hal_array["pagination"]; // tampilkan pagination dibawah
?>

Demo lainnya: klik disini
Download file contoh script komplit nya:

  class.pagination.rar (2.5 KiB, 2,601 hits)

semoga bermanfaat… :mrgreen:

Tambahan:

untuk pagination Style, dapat Anda pilih disini: some-styles-for-your-pagination

1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 4.83 out of 5)
Loading ... Loading ...
Popularity: 7,545 views
Tagged with: [ , , ]

How to Protect from double posting insert MySQL

This item was filled under [ Code Snippet, MySQL, PHP ]

Cara untuk supaya proteksi dari double posting suatu form ke dalam database menggunakan tehnik SESSION.
1. Set a session in the form page

session_start();
$_SESSION[post_only_once] = 1;
echo '
 < form method="post">
  Name < input type="text" name="name">
  < input type="submit" value="submit" name="submit">
 < /form>
';

2. Check the session before doing INSERT into MySQL.

if($_SESSION[post_only_once] == 1) {
  // here doing insert to mysql
}
unset($_SESSION[post_only_once]); // remove the session after insert
1 Star2 Stars3 Stars4 Stars5 Stars (7 votes, average: 4.86 out of 5)
Loading ... Loading ...
Popularity: 9,531 views
Tagged with: [ , , ]

CSV2MySQL convert from CSV file into MySQL database

This item was filled under [ Code Snippet, Javascript, MySQL, PHP ]

Bagaimana cara convert dari CSV ke dalam database MySQL menggunakan PHP.
Silahkan lihat langkah2 dibawah ini:

How to convert from CSV file into MySQL database using PHP?
Plus how to create a table and fields into database with PHP?
Here it is..
We need 3 files php, and 2 file jpg (the jpg is just for menu).

index.php

<?php
// UPLOAD CSV CUSTOM
// Ver. 1.0
// by Jawaad
// http://www.nusansifor.com
// File: index.php
 
@session_start();
//@ob_start(); 
//@ob_implicit_flush(0); 
 
@error_reporting(E_ALL ^ E_NOTICE);
@ini_set('display_errors', true);
@ini_set('html_errors', false);
@ini_set('error_reporting', E_ALL ^ E_NOTICE);
 
define('jin', true);
 
// CONECT DATABASE
@mysql_connect("localhost", "root", "") OR die ("NOT CONNECT DATABASE");
@mysql_select_db("nama_database") OR die ("CONNECTED, BUT NO DATABASE");
 
 
 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns='http://www.w3.org/1999/xhtml' lang='en' xml:lang='en:us'>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>UPLOAD CSV CUSTOM</title>
    <style type="text/css" media="screen">
      body {
        background: #fff;
        color: #888;
        font: 100% georgia,times,serif;
      }
      h1 {
        font-weight: normal;
        margin: 0;
        padding: 0 0 .5em 0;
      }
      h2 {
        font-weight: normal;
        margin: 0;
        padding: 0 0 .5em 0;
      }
 
/*- Menu Tabs J--------------------------- */
 
    #tabsJ {
      float:left;
      width:100%;
      background:#fff;
      font-size:93%;
      line-height:normal;
	  border-bottom:1px solid #24618E;
      }
    #tabsJ ul {
	margin:0;
	padding:10px 10px 0 50px;
	list-style:none;
      }
    #tabsJ li {
      display:inline;
      margin:0;
      padding:0;
      }
    #tabsJ a {
      float:left;
      background:url("tableftJ.gif") no-repeat left top;
      margin:0;
      padding:0 0 0 5px;
      text-decoration:none;
      }
    #tabsJ a span {
      float:left;
      display:block;
      background:url("tabrightJ.gif") no-repeat right top;
      padding:5px 15px 4px 6px;
      color:#24618E;
      }
    /* Commented Backslash Hack hides rule from IE5-Mac \*/
    #tabsJ a span {float:none;}
    /* End IE5-Mac hack */
    #tabsJ a:hover span {
      color:#FFF;
      }
    #tabsJ a:hover {
      background-position:0% -42px;
      }
    #tabsJ a:hover span {
      background-position:100% -42px;
      }		
    </style>
    <script type="text/javascript">
function addElement() {
  var ni = document.getElementById('myDiv');
  var numi = document.getElementById('theValue');
  var num = (document.getElementById("theValue").value -1)+ 2;
  numi.value = num;
  var divIdName = "my"+num+"Div";
  var newdiv = document.createElement('div');
  newdiv.setAttribute("id",divIdName); //  + num + 
  newdiv.innerHTML = "<input type=hidden name=\"kode[" + num + "]\" value=\"" + num + "\"><input type=text name=\"field" + num + "\"> <select name=\"tipe" + num + "\"><option>TEXT</option><option>LONG-TEXT</option><option>NUMERIC</option><option>NUMERIC-2-DECIMAL</option><option>DATE</option><option>DATE-TIME</option></select> <a href=\"javascript:;\" onclick=\"removeElement(\'"+divIdName+"\')\">[- del]</a><p>";
  ni.appendChild(newdiv);
}
 
function removeElement(divNum) {
  var d = document.getElementById('myDiv');
  var olddiv = document.getElementById(divNum);
  d.removeChild(olddiv);
}
</script>
</head>
 
<body>
      <h1>UPLOAD CUSTOM CSV INSERT TO MYSQL</h1>
<div id="tabsJ">
  <ul>
    <li><a href="?do=upload_csv" title="Upload CSV"><span>Upload CSV</span></a></li>
    <li><a href="?do=create_table" title="Create New Table"><span>Create New Table</span></a></li>
  </ul>
</div>
<?php
switch($_REQUEST["do"]) {
	case "upload_csv":
		include ("upload_csv.php");
	break;
	case "create_table":
		include ("create_table.php");
	break;
 
	default:
		include ("upload_csv.php");
}
 
?>
 
 
	 </body>
</html>

upload_csv.php

<?php
// UPLOAD CSV CUSTOM
// Ver. 1.0
// by Jawaad
// http://www.nusansifor.com
 
if(!defined('jin')) { die('nice try..'); }
 
if($_POST[upload_csv]=="1") {
	$table_name="`".$_POST[table_name]."`";
	if(!$_FILES["file_csv"]["name"]) {
		echo "<script>alert('Please Browse File.. CSV.');</script>";
	} else if(substr($_FILES["file_csv"]["name"], -3) != "csv") {
		echo "<script>alert('File ".substr($_FILES["file_csv"]["name"],-3)." not support. Please use CSV extension');</script>";
	} else if($_FILES["file_csv"]["size"]>=1672864) {
		echo "<script>alert('File size is too big. File max 1.5 MB');</script>";
	} else {
		// READ FIELD FROM TABEL
		$sql_tabel = mysql_query("SELECT * FROM ".$table_name."");
		$numfields = mysql_num_fields($sql_tabel);
		$field_name = "";
		for ($i=0; $i < $numfields; $i++) {
			$get_field = mysql_field_name($sql_tabel, $i);
			if($i == 1) {
				$field_name .= "`".$get_field."`";
			} elseif($i > 1) {
				$field_name .= ", `".$get_field."`";
			}
		}
		copy($_FILES["file_csv"]["tmp_name"], "tmp/".$_FILES["file_csv"]["name"]);
	  	$ifile = fopen("tmp/".$_FILES["file_csv"]["name"],"r");
	  	$no=1;
		$jum_value = $numfields - 1;
	  	while (($file_list = fgetcsv($ifile, 1000, ",")) !== FALSE) {
			if($no > 1) {
				$field_value = "";
				for ($i=0; $i < $jum_value; $i++) {
						if($i == 0) {
							$field_value .= "'".$file_list[$i]."'";
						} else {
							$field_value .= ", '".$file_list[$i]."'";
						}
				}
					$sql = "INSERT INTO ".$table_name." (".$field_name.") VALUES (".$field_value.")";
					$ex = mysql_query($sql) OR die ("<br>ERROR, DATA TIDAK BISA MASUK...<br>");
					if(!$ex) {
						echo "<script>alert(\"Sorry, Error....\");location.href='?do=upload_csv';</script>";
					} else {
						echo "<script>alert(\"Succesed.\");location.href='?do=upload_csv';</script>";
					}
			}
			$no++;
		}
		fclose($ifile);
		unlink("tmp/".$_FILES["file_csv"]["name"]) OR die ("Cannot DEL file tmp/".$_FILES["file_csv"]["name"]);
	}
}
?>
 
<form method="post" enctype="multipart/form-data">
<br><br>
<h2>Upload CSV</h2>
<table border="0" cellspacing="0" cellpadding="3">
<tr>
	<td valign="top">Table Name</td><td valign="top">: <input name="table_name"></td>
</tr>
<tr>
	<td valign="top">File CSV</td><td valign="top">: <input type="file" name="file_csv" value="1"></td>
</tr>
<tr>
	<td valign="top" colspan="2">
		<input type="hidden" name="upload_csv" value="1">
		<input type="submit" name="submit" value="UPLOAD .CSV">
	</td>
</tr>
</table>
</form>

create_table.php

<?php
// UPLOAD CSV CUSTOM
// Ver. 1.0
// by Jawaad
// http://www.nusansifor.com
// file: create table
 
if(!defined('jin')) { die('nice try..'); }
 
?>
 
<form method="post">
<br><br>
<h2>Create Table</h2>
Table Name: <input name="table_name">
<input type="hidden" value="0" id="theValue" /><a href="javascript:;" onclick="addElement();">+ Add field</a>
<p>
<div id="myDiv"> </div>
 
 
<input type="hidden" name="create_table" value="1">
<input type="submit" name="submit" value="Create Table">
</form>
 
 
<?php
if($_POST[create_table]=="1") {
	//$kode = array($_POST[kode]);
	$table_name = $_POST[table_name];
	echo "Check <b>".$table_name."</b><br>";
	//print_r($_POST[kode]);
	if($table_name != "" && $_POST[kode] != "") {
		foreach ($_POST[kode] as $field_arr) {
			$field =  $_POST["field".$field_arr.""];
			$tipe = $_POST["tipe".$field_arr.""];
				 if($tipe == "TEXT") {$db_tipe = "varchar(255),";}
			elseif($tipe == "NUMERIC") {$db_tipe = "bigint(20),";}
			elseif($tipe == "NUMERIC-2-DECIMAL") {$db_tipe = "float(10,2),";}
			elseif($tipe == "LONG-TEXT") {$db_tipe = "text NOT NULL,";}
			elseif($tipe == "DATE") {$db_tipe = "date NOT NULL,";}
			elseif($tipe == "DATE-TIME") {$db_tipe = "datetime NOT NULL,";}
			$the_fields .= "`" . $field . "` " . $db_tipe . "\n";
		}
		$sql = "
					CREATE TABLE IF NOT EXISTS `".$table_name."` (
						`id` bigint(20) NOT NULL auto_increment,
						".$the_fields."
						PRIMARY KEY  (`id`)
					) ENGINE=MyISAM  DEFAULT CHARSET=latin1;
		";
		$ex = mysql_query($sql);
		if(!$ex) {
			echo "Sorry,... Error...<br>";
		} else {
			echo "Table  <b>".$table_name."</b> created.<br>";
		}
	} else {
		echo "Sorry,... Error... Please fill the table name and the fields...<br>";
	}
}
?>

Image files:

Download file lengkap:

  CSV2MySQL.V.1.0.rar (6.4 KiB, 1,925 hits)

semoga membantu :mrgreen:

1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 5.00 out of 5)
Loading ... Loading ...
Popularity: 6,249 views
Tagged with: [ , , , , ]
Page 2 of 212

Halaman ini di eksekusi dalam waktu 3.771 detik! (sedeng lah segini mah...)