Category Archives: PHP

Create Category and Sub Category Tree in PHP

Create table


CREATE TABLE IF NOT EXISTS `category` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `parent` int(11) NOT NULL,
  PRIMARY KEY (`cid`)
);

Create code file


<?php

$dbname = 'category';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';

$con = mysql_connect($dbhost,$dbuser,$dbpass);
$db =  mysql_select_db($dbname, $con) or die(mysql_error());

function fetchCategoryTreeList($parent = 0, $user_tree_array = '') {
 
    if (!is_array($user_tree_array))
    $user_tree_array = array();
 
  $sql = "SELECT `cid`, `name`, `parent` FROM `category` WHERE 1 AND `parent` = $parent ORDER BY cid ASC";
  $query = mysql_query($sql);
  if (mysql_num_rows($query) > 0) {
     $user_tree_array[] = "<ul>";
    while ($row = mysql_fetch_object($query)) {
	  $user_tree_array[] = "<li>". $row->name."</li>";
      $user_tree_array = fetchCategoryTreeList($row->cid, $user_tree_array);
    }
	$user_tree_array[] = "</ul>";
  }
  return $user_tree_array;
}
?>

<ul>
  <?php
  $res = fetchCategoryTreeList();
  foreach ($res as $r) {
    echo  $r;
  }
?>
</ul>


Advertisements

Get Last Inserted ID in PHP MySQL


$query = "SELECT c_id FROM category ORDER BY c_id DESC LIMIT 1;";	  
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {  
	echo $c_id = $row['c_id'];
} 

Insert and Display form Data Using JOIN in PHP

Create table ‘category’


CREATE TABLE category
(
c_id int AUTO_INCREMENT,
c_name varchar(255),
b_name varchar(255),
PRIMARY KEY (c_id)
);

Create table ‘product’


CREATE TABLE product
(
p_id INT(11) AUTO_INCREMENT,
c_id INT(11),    
p_name varchar(255),
p_price INT(11),
p_color varchar(255),
PRIMARY KEY (p_id)
);

Create “category.php”


<?PHP include 'connect.php'; ?>

<form method="post">
  Product Category
  <input type="text" name="category">
  </br>
  </br>
  Brand Name
  <input type="text" name="bname">
  </br>
  </br>
  <input type="submit" name="add_category" value="Add Category" />
</form>
<?php 
if(isset($_POST['add_category'])){
	$product_category = $_POST['category'];
	$brand_name = $_POST['bname'];
	$query2 = "INSERT INTO `category` (`c_name`,`b_name`) VALUES ('".$product_category."','".$brand_name."')";
	$result2 = mysql_query($query2) or die(mysql_error());
}

?>

Create “product.php”


<?php include 'connect.php'; ?>

<form method="post">
  Category Name
  <?php 
  $category = "SELECT c_name, c_id FROM category";
	$cat_result = mysql_query($category);
	?>
  <select name="category">
    <?php
	while($cat_row = mysql_fetch_array($cat_result)) { ?>
    <option value="<?php echo $cat_row['c_id']; ?>"><?php echo $cat_row['c_name']; ?></option>
    <?php }	?>
  </select>
  </br>
  </br>
  Product Name
  <input type="text" name="pname">
  </br>
  </br>
  Product Price
  <input type="text" name="price">
  </br>
  </br>
  Product Color
  <input type="checkbox" value="red" name="color[]" />
  Red,
  <input type="checkbox" value="blue" name="color[]" />
  Blue,
  <input type="checkbox" value="black" name="color[]" />
  Black</br>
  </br>
  <input type="submit" name="add_product" value="Add Product" />
</form>
<?php
if(isset($_POST['add_product'])){
	$c_id = $_POST['category'];
	$product_name = $_POST['pname'];
	$product_price = $_POST['price'];
	$product_color = implode(', ',$_POST['color']);
	
	$query1 = "INSERT INTO `product` (`c_id`,`p_name`,p_price,p_color) VALUES ('".$c_id."','".$product_name."','".$product_price."','".$product_color."')";
	$result1 = mysql_query($query1) or die(mysql_error());
}

?>

Create “result.php”


<?php
include 'connect.php';
$query = "SELECT product.*, category.* 
		  FROM product 
		  JOIN category 
		  ON product.c_id=category.c_id";	  

$result = mysql_query($query);

?>

<table border="1">
<tr>
  <td>Product ID</td>
  <td>Product Name</td>
  <td>Product Price</td>
  <td>Product Color</td>
  <td>Product Category ID</td>
  <td>Product Category </td>
  <td>Brand Name</td>
</tr>
<?php while($row = mysql_fetch_array($result)) { ?>
<tr>
  <td><?php echo $row['p_id']; ?></td>
  <td><?php echo $row['p_name']; ?></td>
  <td><?php echo $row['p_price']; ?></td>
  <td><?php echo $row['p_color']; ?></td>
  <td><?php echo $row['c_id']; ?></td>
  <td><?php echo $row['c_name']; ?></td>
  <td><?php echo $row['b_name']; ?></td>
</tr>
<?php } ?>

Create “connect.php”


<?php

$dbname = 'php';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';

$con = mysql_connect($dbhost,$dbuser,$dbpass);
$db =  mysql_select_db($dbname, $con) or die(mysql_error());
 
?>

Insert Update Delete Search (Radio, Checkbox, Imge) with Pagination in PHP

Create database

CREATE DATABASE IF NOT EXISTS `test` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;

Create table

CREATE TABLE IF NOT EXISTS `tbl1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(11) NOT NULL,
  `number` varchar(11) NOT NULL,
  `pass` varchar(11) NOT NULL,
  `cpass` varchar(11) NOT NULL,
  `city` varchar(11) NOT NULL,
  `gender` varchar(11) NOT NULL,
  `job` varchar(50) NOT NULL,
  `image` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=132 ;

Create index.php

<form name="f1" method="post" enctype="multipart/form-data">
  name
  <input type="text" name="name" id="name">
  <br>
  Number
  <input type="text" name="number" id="number">
  <br>
  password
  <input type="text" name="pass" id="pass">
  <br>
  conform pass
  <input type="text" name="cpass" id="cpass">
  <br>
  city
  <select name="city" id="city">
    <option></option>
    <option value="junagadh">junagaadh</option>
    <option value="keshod">Keshod</option>
  </select>
  <br>
  Gender
  <input type="radio" name="gender" value="male" id="gender" />
  Male
  <input type="radio" value="female" name="gender" id="gender" />
  Female<br>
  job
  <input type="checkbox" name="job[]" value="developer" id="developer" />
  Developer
  <input type="checkbox" name="job[]" value="designer" id="designer" />
  Designer<br>
  <input type="file" name="image" id="image" />
  <input type="submit" name="insert" value="insert">
  <br>
</form>
<?php

$cn = mysql_connect("localhost","root","");
$db = mysql_select_db("test",$cn);

if(isset($_POST['insert']))
{
	$name = $_POST["name"];
	$number = $_POST["number"];
	$pass = $_POST["pass"];
	$cpass = $_POST["cpass"];
	$city = $_POST["city"];
	@$gender = $_POST["gender"];
	@$job = implode(",",$_POST["job"]);
	
	$image = $_FILES['image']['name'];
	$define_name = "image_".microtime().".jpg";
	move_uploaded_file($_FILES['image']['tmp_name'],"upload/".$define_name);
	
	$q = "INSERT INTo `tbl1` (`name`, `number`, `pass`, `cpass`, `city`, `gender`, `job`, `image`)
		  VALUES ('".$name."', '".$number."', '".$pass."', '".$cpass."', '".$city."', '".$gender."', '".$job."', '".$define_name."')";

	$r = mysql_query($q);
}
echo '<a href="display.php">Display Records</a>';
?>

Create display.php


<form method="post" action="search_all.php">
  Search
  <input type="text" name="search_all" />
  <input type="submit" name="submit" value="submit" />
</form>
<?php
	$cn = mysql_connect("localhost","root","");
	$db = mysql_select_db("test",$cn);
	
	$q = "SELECT * FROM `tbl1`";
	$r = mysql_query($q);
	 
		$row2 = mysql_num_rows($r);
		$limit = 2;
		$page_devide = ceil($row2/$limit);
		if(!isset($_GET['page']))
		{
			header("location:display.php?page=1"); 
		}
		else
		{
			$page = $_GET['page'];
		}
			$start = ($page-1)*$limit;
			$q2 = "select * from tbl1 limit $start,$limit";
			$r2 = mysql_query($q2);
	?>
<table border="1">
  <tr>
    <td>name</td>
    <td>number</td>
    <td>pass</td>
    <td>cpass</td>
    <td>city</td>
    <td>gender</td>
    <td>job</td>
    <td>Image</td>
    <td>Edit</td>
    <td>Delete</td>
  </tr>
  <?php while($row = mysql_fetch_array($r2)) { ?>
  <tr>
    <td><?php echo $row['name']; ?></td>
    <td><?php echo $row['number']; ?></td>
    <td><?php echo $row['pass']; ?></td>
    <td><?php echo $row['cpass']; ?></td>
    <td><?php echo $row['city']; ?></td>
    <td><?php echo $row['gender']; ?></td>
    <td><?php echo $row['job']; ?></td>
    <td><img src="upload/<?php echo $row['image']; ?>" width="50" height="50"></td>
    <td><a href="edit.php?hid=<?php echo $row['id']; ?>">Edit</a></td>
    <td><a href="delete.php?hid=<?php echo $row['id']; ?>&image=<?php echo $row['image']; ?>">Delete</a></td>
  </tr>
  <?php } ?>
  <?php 
	
		for($i=1;$i<=$page_devide;$i++)
		{
			?>
  <a href="display.php?page=<?php echo $i; ?>"><?php echo $i;?></a>
  <?php	
		}
	?>
</table>

Create delete.php

<?php
$cn = mysql_connect("localhost","root","");
$db = mysql_select_db("test",$cn);
$id = $_REQUEST['hid'];
$image = $_REQUEST['image'];
$q="DELETE FROM tbl1 WHERE id=".$id; 
$r=mysql_query($q) or die(mysql_query());
unlink("upload/".$image);
header("location:display.php");
?>

Create edit.php

<?php

$cn = mysql_connect("localhost","root","");
$db = mysql_select_db("test",$cn);

if(isset($_REQUEST['hid']))
{
	$id = $_REQUEST['hid'];
	$q = "SELECT * FROM `tbl1` WHERE `id` = '".$id."'";
	$r = mysql_query($q);
}
	while($row = mysql_fetch_array($r))
	{
		$id = $row['id'];
		$name = $row['name'];
		$number = $row['number'];
		$pass = $row['pass'];
		$cpass = $row['cpass'];
		$city = $row['city'];
		$gender = $row['gender'];
		$job = explode(",",$row['job']);
		$image = $row['image']; 
	}
?>

<form name="f1" method="post" enctype="multipart/form-data">
  <input type="hidden" name="id" value="<?php echo $id; ?>">
  name
  <input type="text" name="name" id="name" value="<?php echo $name;  ?>">
  <br>
  Number
  <input type="text" name="number" id="number" value="<?php echo $number;  ?>">
  <br>
  password
  <input type="text" name="pass" id="pass" value="<?php echo $pass;  ?>">
  <br>
  conform pass
  <input type="text" name="cpass" id="cpass" value="<?php echo $cpass;  ?>">
  <br>
  city
  <select name="city" id="city">
    <option></option>
    <option value="junagadh" <?php if($city == "junagadh") { ?> selected="selected">
    <?php } ?>
    junagaadh</option>
    <option value="keshod" <?php if($city == "keshod"){ ?> selected="selected" <?php } ?>>Keshod</option>
  </select>
  <br>
  Gender
  <input type="radio" name="gender" value="male" id="gender" <?php if($gender == "male"){ ?> checked="checked" <?php } ?> />
  Male
  <input type="radio" value="female" name="gender" id="gender" <?php if($gender == "female") { ?> checked="checked" <?php } ?> />
  Female<br>
  job
  <input type="checkbox" name="job[]" value="developer" id="developer" <?php if(in_array("developer",$job)){ ?> checked="checked" <?php } ?> />
  Developer
  <input type="checkbox" name="job[]" value="designer" id="designer" <?php if(in_array("designer",$job)){ ?> checked="checked" <?php } ?> />
  Designer<br>
  <input type="file" name="image" id="image" />
  <img src="upload/<?php echo $image; ?>" width="50" height="50"><br>
  <input type="submit" name="edit" value="edit">
  <br>
  <input type="hidden" name="old_image" value="<?php echo $image; ?>" />
</form>
<?php

if(isset($_POST['edit']))
{
		$id = $_POST['id'];
		$name = $_POST['name'];
		$number = $_POST['number'];
		$pass = $_POST['pass'];
		$cpass = $_POST['cpass'];
		$city = $_POST['city'];
		@$gender = $_POST['gender'];
		@$job = implode(",",($_POST['job']));
		
		$image = $_FILES['image']['name'];
		$define_name = "image_".microtime().".jpg";
		
		$old_image = $_REQUEST['old_image'];
		unlink("upload/".$old_image);
		
		move_uploaded_file($_FILES['image']['tmp_name'],"upload/".$define_name);
		
		$q = "UPDATE `tbl1` SET `name` = '".$name."', `number` = '".$number."', `pass` = '".$pass."',   	
			 `cpass` = '".$cpass."', `city` = '".$city."', `gender` = '".$gender."', `job` = '".$job."',
			 `image` = '".$define_name."' WHERE `id` = '".$id."'";
			 
		
		$r = mysql_query($q)or die(mysql_query());

		header("location:display.php");
}

?>

Create search_all.php

<?php

$cn = mysql_connect("localhost","root","");
$db = mysql_select_db("test",$cn);

$q = "SELECT * 
FROM  `tbl1` 
WHERE  `name` LIKE  '%".$_POST['search_all']."%'
OR  `number` LIKE  '%".$_POST['search_all']."%'
OR  `pass` LIKE  '%".$_POST['search_all']."%'
OR  `cpass` LIKE  '%".$_POST['search_all']."%'
OR  `city` LIKE  '%".$_POST['search_all']."%'
OR  `gender` LIKE  '%".$_POST['search_all']."%'
OR  `job` LIKE  '%".$_POST['search_all']."%'
OR  `image` LIKE  '%".$_POST['search_all']."%'";

$r = mysql_query($q);
?>

<table border="1">
  <tr>
    <td>name</td>
    <td>number</td>
    <td>pass</td>
    <td>cpass</td>
    <td>city</td>
    <td>gender</td>
    <td>job</td>
    <td>Image</td>
    <td>Edit</td>
    <td>Delete</td>
  </tr>
  <?php while($row = mysql_fetch_array($r)) { ?>
  <tr>
    <td><?php echo $row['name']; ?></td>
    <td><?php echo $row['number']; ?></td>
    <td><?php echo $row['pass']; ?></td>
    <td><?php echo $row['cpass']; ?></td>
    <td><?php echo $row['city']; ?></td>
    <td><?php echo $row['gender']; ?></td>
    <td><?php echo $row['job']; ?></td>
    <td><img src="upload/<?php echo $row['image']; ?>" width="50" height="50"></td>
    <td><a href="edit.php?hid=<?php echo $row['id']; ?>">Edit</a></td>
    <td><a href="delete.php?hid=<?php echo $row['id']; ?>&image=<?php echo $row['image']; ?>">Delete</a></td>
  </tr>
  <?php } ?>
</table>

php.ini – change for uploading large database

SQL ERROR: Script timeout passed, if you want to finish import, please resubmit same file and import will resume

php> php.ini

Find:
post_max_size = 8M
upload_max_filesize = 2M
max_execution_time = 30
max_input_time = 60
memory_limit = 8M

Change to:
post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 300
max_input_time = 540
memory_limit = 1000M

Refrence: http://askubuntu.com/questions/411505/script-timeout-passed-if-you-want-to-finish-import-please-resubmit-same-file-a

export database from custom file

export-mysql-database-sql-backup.php

<?php
//EXPORT_TABLES("your_host","db_user","db_pass","db_name" );
EXPORT_TABLES("127.0.0.1","swiftpub_cms","-;DTUXI$~ucc","swiftpub_cms" );  //or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3")

//https://github.com/tazotodua/useful-php-scripts
function EXPORT_TABLES($host,$user,$pass,$name,  $tables=false, $backup_name=false ){
	
	$mysqli = new mysqli($host,$user,$pass,$name); $mysqli->select_db($name); $mysqli->query("SET NAMES 'utf8'");
	$queryTables = $mysqli->query('SHOW TABLES'); while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; }	if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); }
	foreach($target_tables as $table){
		
		$result	= $mysqli->query('SELECT * FROM '.$table);
		$fields_amount=$result->field_count;  $rows_num=$mysqli->affected_rows;
		
		$res = $mysqli->query('SHOW CREATE TABLE '.$table);
		
		if(!$res) {
	    	//echo $link->error;
		} else {
		    $TableMLine=$res->fetch_row();
		}

		$content = (!isset($content) ?  '' : $content) . "\n\n".$TableMLine[1].";\n\n";
		for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) {
			while($row = $result->fetch_row())	{ //when started (and every after 100 command cycle):
				if ($st_counter%100 == 0 || $st_counter == 0 )	{$content .= "\nINSERT INTO ".$table." VALUES";}
					$content .= "\n(";
					for($j=0; $j<$fields_amount; $j++)  { $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); if (isset($row[$j])){$content .= '"'.$row[$j].'"' ; }else {$content .= '""';}	   if ($j<($fields_amount-1)){$content.= ',';}		}
					$content .=")";
				//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
				if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {$content .= ";";} else {$content .= ",";}	$st_counter=$st_counter+1;
			}
		} $content .="\n\n\n";
	}
	$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
	header('Content-Type: application/octet-stream');	header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"".$backup_name."\"");  echo $content; exit;
}
?>

Pattern Programs

<?php  
for($x=1;$x<=5;$x++)  
{  
   for ($y=1;$y<=$x;$y++)  
    {  
     echo "*";  
        if($y< $x)  
         {  
           echo " ";  
         }  
     }  
 echo "
";  
}  
*  
* *  
* * *  
* * * *  
* * * * *
<?php  
$n=5;  
for($i=1; $i<=$n; $i++)  
{  
for($j=1; $j<=$i; $j++) { echo ' * '; } echo ' '; } for($i=$n; $i>=1; $i--)  
{  
for($j=1; $j<=$i; $j++) { echo ' * '; } echo ' '; } ?>  
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * 
* * * * 
* * * 
* * 
*
<?php  
$n = 5;   
echo "n = " . $n . "
";  
$count = 1;  
for ($i = $n; $i > 0; $i--)   
{  
  for ($j = $i; $j < $n + 1; $j++)   
   {  
     printf("%4s", $count);  
     $count++;  
   }   
    echo "
";  
   }  
?> 

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

for($i=1;$i<=5;$i++){
for($j=1;$j<=$i;$j++){
echo $j;
}
echo "</br>";
}

1
12
123
1234
12345

%d bloggers like this: