Digital World Freelancer

The Digital World Freelancer group is applying latest Technologies Like HTML, CSS, CSS3, JavaScript, JQuery, PHP and more...... for website designing & developing... reach at our organization http://www.digitalworldfreelancer.com

Facebook Page

Wednesday, October 15, 2014

PHP "MySQL Functions"


• mysql_affected_rows — Get number of affected rows in previous MySQL operation
• mysql_client_encoding — Returns the name of the character set
• mysql_close — Close MySQL connection
• mysql_connect — Open a connection to a MySQL Server
• mysql_create_db — Create a MySQL database
• mysql_data_seek — Move internal result pointer
• mysql_db_name — Retrieves database name from the call to mysql_list_dbs
• mysql_db_query — Selects a database and executes a query on it
• mysql_drop_db — Drop (delete) a MySQL database
• mysql_errno — Returns the numerical value of the error message from previous MySQL operation
• mysql_error — Returns the text of the error message from previous MySQL operation
• mysql_escape_string — Escapes a string for use in a mysql_query
• mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
• mysql_fetch_assoc — Fetch a result row as an associative array
• mysql_fetch_field — Get column information from a result and return as an object
• mysql_fetch_lengths — Get the length of each output in a result
• mysql_fetch_object — Fetch a result row as an object
• mysql_fetch_row — Get a result row as an enumerated array
• mysql_field_flags — Get the flags associated with the specified field in a result
• mysql_field_len — Returns the length of the specified field
• mysql_field_name — Get the name of the specified field in a result
• mysql_field_seek — Set result pointer to a specified field offset
• mysql_field_table — Get name of the table the specified field is in
• mysql_field_type — Get the type of the specified field in a result
• mysql_free_result — Free result memory
• mysql_get_client_info — Get MySQL client info
• mysql_get_host_info — Get MySQL host info
• mysql_get_proto_info — Get MySQL protocol info
• mysql_get_server_info — Get MySQL server info
• mysql_info — Get information about the most recent query
• mysql_insert_id — Get the ID generated in the last query
• mysql_list_dbs — List databases available on a MySQL server
• mysql_list_fields — List MySQL table fields
• mysql_list_processes — List MySQL processes
• mysql_list_tables — List tables in a MySQL database
• mysql_num_fields — Get number of fields in result
• mysql_num_rows — Get number of rows in result
• mysql_pconnect — Open a persistent connection to a MySQL server
• mysql_ping — Ping a server connection or reconnect if there is no connection
• mysql_query — Send a MySQL query
• mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement
• mysql_result — Get result data
• mysql_select_db — Select a MySQL database
• mysql_set_charset — Sets the client character set
• mysql_stat — Get current system status
• mysql_tablename — Get table name of field
• mysql_thread_id — Return the current thread ID
• mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows.

Monday, October 13, 2014

Upload, Crop and Resize images with PHP!



One of the most common actions on the modern web application is upload, crop and resize of images, whether for avatar use or general use of resized images in galleries or as thumbnails.

Upload image with PHP:

We will start this tutorial with a classic image upload so you can easily understand the means and methods of how uploading files in PHP works.

In this first example we will a form for uploading files and save that file in a folder on the server, but only if that file is an image.

To upload a file, you need a form with a special input field type of file. So, open your favorite editor and paste in this code and save it as form.php:

<!DOCTYPE html>
<html>
<head>
    <title>Upload Files using normal form and PHP</title>
</head>
<body>
  <form enctype="multipart/form-data" method="post" action="upload.php">
    <div class="row">
      <label for="fileToUpload">Select a File to Upload</label><br />
      <input type="file" name="fileToUpload" id="fileToUpload" />
    </div>
    <div class="row">
      <input type="submit" value="Upload" />
    </div>
  </form>
</body>
</html>

One thing that you already noticed is probably the enctype attribute of our form. It basically prepares the form for binary data, like the contents of a file.

Next step is to create a file that will handle our uploaded images. Go ahead, create upload.php file and paste this in:

<?php
// fileToUpload is the name of our file input field
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    echo "File name: " . $_FILES['fileToUpload']['name'] . "<br />";
    echo "File type: " . $_FILES['fileToUpload']['type'] . "<br />";
    echo "File size: " . ($_FILES['fileToUpload']['size'] / 1024) . " Kb<br />";
    echo "Temp path: " . $_FILES['fileToUpload']['tmp_name'];
}


Now, open form.php in browser and try to select and upload a file. If everything went fine, you should see some info about the uploaded file when you submit a form.

Nice start, but user can now upload anything to your server and basically blow it to pieces. So, let’s modify the upload.php code to check if uploaded file is actually an image:

<?php
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    // array of valid extensions
    $validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
    // get extension of the uploaded file
    $fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension, $validExtensions)) {
        echo 'Uploaded file is allowed!';
    } else {
        echo 'You must upload an image...';
    }
}

So, we checked if the file is an image and now we can write code to move that image in some folder on the server, so change your code to this:

<?php
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    // array of valid extensions
    $validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
    // get extension of the uploaded file
    $fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension, $validExtensions)) {
        // we are renaming the file so we can upload files with the same name
        // we simply put current timestamp in fron of the file name
        $newName = time() . '_' . $_FILES['fileToUpload']['name'];
        $destination = 'uploads/' . $newName;
        if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $destination)) {
            echo 'File ' .$newName. ' succesfully copied';
        }
    } else {
        echo 'You must upload an image...';
    }
}


Before you try this out, create a folder named uploads in the directory in which the code is in.

Congratulations, you successfully uploaded and saved a file on the server.

Crop and resize images with PHP:



Now the fun part begins. We will resize the uploaded image and save resized version in uploads folder so you can easily use them later. We can do this from scratch, but there are plenty of useful libraries on the web that does an excellent job.

I will use a great ImageManipulator class by Phil Brown. Download it and put inside your working directory.

Now, update your upload.php file:


<?php
// include ImageManipulator class
require_once('ImageManipulator.php');

if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    // array of valid extensions
    $validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
    // get extension of the uploaded file
    $fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension, $validExtensions)) {
        $newNamePrefix = time() . '_';
        $manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
        // resizing to 200x200
        $newImage = $manipulator->resample(200, 200);
        // saving file to uploads folder
        $manipulator->save('uploads/' . $newNamePrefix . $_FILES['fileToUpload']['name']);
        echo 'Done ...';
    } else {
        echo 'You must upload an image...';
    }
}


The same class can be used to crop the image, so let’s change the code so the image cropped to 200×130 px. We want to crop the center of the image, so the good parts are intact, so we have to calculate crop coordinates:


<?php
// include ImageManipulator class
require_once('ImageManipulator.php');

if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
    // array of valid extensions
    $validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
    // get extension of the uploaded file
    $fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension, $validExtensions)) {
        $newNamePrefix = time() . '_';
        $manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
        $width  = $manipulator->getWidth();
        $height = $manipulator->getHeight();
        $centreX = round($width / 2);
        $centreY = round($height / 2);
        // our dimensions will be 200x130
        $x1 = $centreX - 100; // 200 / 2
        $y1 = $centreY - 65; // 130 / 2

        $x2 = $centreX + 100; // 200 / 2
        $y2 = $centreY + 65; // 130 / 2

        // center cropping to 200x130
        $newImage = $manipulator->crop($x1, $y1, $x2, $y2);
        // saving file to uploads folder
        $manipulator->save('uploads/' . $newNamePrefix . $_FILES['fileToUpload']['name']);
        echo 'Done ...';
    } else {
        echo 'You must upload an image...';
    }
}



Now you learned how to upload, resize and crop images using pure PHP.

How to Select name from Table in Select Box(dropdown) Through MySQL and PHP !


If you are facing problem in select name from table of  MySQL(in drop down select box only for one select box if you are more after this select box you will have to use ajax)

so...

1 Step)
Create database and table.......

2 Step) 


<div class="setting">
<div class="input text">
<label for="setting0value">select art student</label>
<select name="art" value="">
<option> --select-- </option>
<?php
$sql=mysql_query("select *from students where streem='art'");
while($row = mysql_fetch_array($sql))
{
?>
<option value="<?php echo $row['id'];?>">
<?php echo $row['name'];?>
</option>
<?php
}
?>
</select>
</div>

</div>

How to Send Form Data in Database/How to Add/Edit/Delete/View a form entry dynamically through PHP and MySQL?


Learn here everything very quickly.............


1 Step) Make a Database and Table Like or same Below.....


2 Step) connection.php

<?php
define("HOSTNAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("DATABASE", "school_management");
$conn = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
if(!$conn) {
die("Mysql error");
}
?>



3 Step) add_student.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Add Student</title>
</head>

<body>
<form action="save_student.php" method="post" enctype="multipart/form-data">
<table align="center">
<tr>
<th colspan="2">
Add Student
</th>
</tr>
<tr>
<td>Roll No</td>
<td><input type="text" name="roll_no" value="" maxlength="10" /></td>
</tr>
<tr>
<td>Student Name</td>
<td><input type="text" name="name" value="" maxlength="50"/></td>
</tr>
<tr>
<td>Father's Name</td>
<td><input type="text" name="father" value="" maxlength="50"/></td>
</tr>
<tr>
<td>Mother's Name</td>
<td><input type="text" name="mother" value=""  maxlength="50"/></td>
</tr>
<tr>
<td>Date Of birth</td>
<td><input type="text" name="dob" value="" /><br />(eg : 20/09/2014 => 2014-09-20)</td>
</tr>
<tr>
<td>Streem</td>
<td>
<select name="streem">
<option>Select Streem</option>
<option value="Art">Art</option>
<option value="Science">Science</option>
</select>
</td>
</tr>
<tr>
<td>Student's Photo</td>
<td>
<input type="file" name="photo"  />
  </td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Save" /><input type="reset" name="reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>


4 Step) save_student.php


<?php 
include("connection.php");
$roll_no = $_POST['roll_no'];
$name = $_POST['name'];
$father = $_POST['father'];
$mother = $_POST['mother'];
$dob = $_POST['dob'];
$streem = $_POST['streem'];
// upload photo
$photo = $_FILES['photo'];
$photo_path = "";
//print_r($photo); die;
if($photo['type'] == "image/jpeg" || $photo['type'] == "image/png" || $photo['type'] == "image/gif") {
$photo_name = uniqid().".jpeg";
$photo_path = "./images/student_photo/".$photo_name;
move_uploaded_file($photo['tmp_name'], $photo_path);
//die("hello");
}
$sql = "insert into students (roll_no, name, father, mother, dob, streem, photo) values (".$roll_no.", '".$name."', '".$father."', '".$mother."', '".$dob."', '".$streem."', '".$photo_path."')";
$result = mysqli_query($conn, $sql) or die($conn);
if($result) {
header("location:index.php");
} else {
header("location:add_student.php?msg=some error");
}
?>


5 Step) edit.php

<?php 
include("connection.php"); 
$id = "";
// check status
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
header("location:index.php");
}
// Get student record
$sql = "select * from students where id = ".$id;
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$data = array();
if(mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
} else {
header("location:index.php");
}
//print_r($data); die;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Edit student record</title>
</head>

<body>
<form action="update_student.php" method="post" enctype="multipart/form-data">
<input name="id" type="hidden" value="<?php echo $data['id'];?>"/>
<table align="center">
<tr>
<th colspan="2">
Edit Student
</th>
</tr>
<tr>
<td>Roll No</td>
<td><input type="text" name="roll_no" value="<?php echo $data['roll_no'];?>" maxlength="10" /></td>
</tr>
<tr>
<td>Student Name</td>
<td><input type="text" name="name" value="<?php echo $data['name'];?>" maxlength="50"/></td>
</tr>
<tr>
<td>Father's Name</td>
<td><input type="text" name="father" value="<?php echo $data['father'];?>" maxlength="50"/></td>
</tr>
<tr>
<td>Mother's Name</td>
<td><input type="text" name="mother" value="<?php echo $data['mother'];?>"  maxlength="50"/></td>
</tr>
<tr>
<td>Date Of birth</td>
<td><input type="text" name="dob" value="<?php echo $data['dob'];?>" /><br />(eg : 20/09/2014 => 2014-09-20)</td>
</tr>
<tr>
<td>Streem</td>
<td>
<select name="streem">
<option>Select Streem</option>
<option value="Art" <?php echo ($data['streem'] == "Art" ? "selected" :  "");?> >Art</option>
<option value="Science" <?php echo ($data['streem'] == "Science" ? "selected" :  "");?>>Science</option>
</select>
</td>
</tr>
<tr>
<td>Student's Photo</td>
<td>
<input type="file" name="photo"  />
<img src="<?php echo $data['photo'];?>" width="50px"/>
  </td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Update" /><input type="reset" name="reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>


6 Step) update_student.php


<?php 
include("connection.php");
$id = $_POST['id'];
$roll_no = $_POST['roll_no'];
$name = $_POST['name'];
$father = $_POST['father'];
$mother = $_POST['mother'];
$dob = $_POST['dob'];
$streem = $_POST['streem'];
// upload photo
$photo = $_FILES['photo'];
$photo_path = "";
if(!empty($photo)) {
if($photo['type'] == "image/jpeg" || $photo['type'] == "image/png" || $photo['type'] == "image/gif") {
$photo_name = uniqid().".jpeg";
$photo_path = "./images/student_photo/".$photo_name;
move_uploaded_file($photo['tmp_name'], $photo_path);
//die("hello");
}
}
if($photo_path != "") {
$sql = "update students 
set roll_no = ".$roll_no.", 
name = '".$name."', 
father = '".$father."', 
mother = '".$mother."', 
dob = '".$dob."', 
streem = '".$streem."', 
photo = '".$photo_path."' 
where id = ".$id;
} else {
$sql = "update students 
set roll_no = ".$roll_no.", 
name = '".$name."', 
father = '".$father."', 
mother = '".$mother."', 
dob = '".$dob."', 
streem = '".$streem."' 
where id = ".$id;
}
$result =  mysqli_query($conn, $sql) or die(mysqli_error($conn));
if($result) {
header("location:index.php");
} else  {
header("location:edit_student.php?id=".$id);
}


7 Step) delete_student.php

<?php 
include("connection.php");
$id = "";
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
header ("location:index.php");
}
$sql = "delete from students where id = ".$id;
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
header("location:index.php");
?>


8 Step) index.php


<?php include("connection.php"); ?>
<html>
<head>
<title>My schoole management</title>
</head>
<body>
<table align="center" width="1024px" border="1" cellpadding="10" cellspacing="0">
<tr>
<td colspan="7" align="left">Students list</td>
<td align="right">
<a href="add_student.php">Add</a>
</td>
</tr>
<tr>
<td>Roll No.</td>
<td>Name</td>
<td>Father Name</td>
<td>Mother Name</td>
<td>Streem</td>
<td>Date Of birth</td>
<td>Photo</td>
<td>Created date</td>
<td>Actions</td>
</tr>
<?php 
$sql = "select * from students";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo $row['roll_no'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['father'];?></td>
<td><?php echo $row['mother'];?></td>
<td><?php echo $row['streem'];?></td>
<td><?php echo $row['dob'];?></td>
<td><img src="<?php echo $row['photo'];?>" width="50px"/></td>
<td><?php echo date("d M, Y", strtotime($row['created_date']));?></td>
<td>
<a href="edit_student.php?id=<?php echo $row['id'];?>">Edit</a>
<a href="delete_student.php?id=<?php echo $row['id'];?>">Delete</a>
</td>
</tr>
<?php 
}
  }
?>
</table>
</body>
</html>

How to Get/Send Form/Contact Us form detail in Email ID through PHP?



1 Step) contactform.html

<!DOCTYPE html>

<html>
<head>
<title>Contact form</title>
</head>
<body>
   <form name="contactform" method="post" action="send_form_email.php">
<table width="450px">
<tr>
<td valign="top">
<label for="first_name">First Name</label>
</td>
<td valign="top">
<input type="text" name="first_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="last_name">Last Name</label>
</td>
<td valign="top">
<input type="text" name="last_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="email"> E-mail</label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone"> Telephone No.</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="comments">Comments</label>
</td>
<td valign="top">
<textarea name="comments" maxlength="300" cols="25" rows="6"></textarea>
</td>
</tr>
<tr>
<td style="text-align:center">
<input type="submit" name="submit" value="submit" >
</td style="text-align:center">
<td>
<input type="reset" name="reset" value="reset">
</td>
</tr>
</table>
   </form>


</body>
</html>


2 Step) send_form_email.php

<?php
if(isset($_POST['email'])){
//Edit the 2 lines below as required
$email_to = "test@gmail.com";
$email_subject ="Welcome in Digital World";
function died($error){
//Your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted";
echo "These errors appears below.<br><br>";
echo "Please go back and fix these errors.<br><br>";
die();
}
//Validation expected data exists
if(!isset($_POST['first_name']) || !isset($_POST['last_name'])  || !isset($_POST['email'])  || !isset($_POST['comments'])){
 died('We are sorry, but there appears to be a problem with the form you submitted');
}
$first_name = $_POST['first_name']; //required
$last_name  = $_POST['last_name'];  //required
$email_form = $_POST['email'];     //required
$telephone  = $_POST['telephone']; //not required
$comments   = $_POST['comments'];  //required

$error_message = "";
$email_exp = '/^[A - Za - z0 - 9._ %-] + @[A - Za z0-9.-] + \.[A Za -z]
{2,4} $/';

if(!preg_match($email_exp, $email_form))
{
$error_message .= 'The Email Address you entered does not appear to be valid.<br>';
}
           $string_exp = " /^[A - Za - z. '-] + $/";
 if(!preg_match($string_exp. $first_name)){
$error_message .= 'The First Name you entered does not appear to be valid.<br>';
}
 if($preg_match($string_exp, $last_name)){
$error_message .='The Last Name you entered does not appear to be valid.<br>';
  }
 if(strlen($comment)>2){
$error_message .= 'The Comment you entered do not appear to be valid.<br>';
  }
 if(strlen($error_message)>0){
died($error_message);
  }
 $email_message = 'form details below.\n\n';
function clean_string($string){
$bad = array("content_type", "bcc:", "to:", "cc:", "href");
return str_replace($bad, "", $string);
}
  $email_message .= "First Name:".clean_string($first_name)."\n";
$email_message .= "Last Name:".clean_string($last_name)."\n";
  $email_message .= "Email:".clean_string($email_from)."\n";
  $email_message .= "Telephone:".clean_string($telephone)."\n";
  $email_message .= "Comments:".clean_string($comments). "\n";

$header = 'From:'.$email_form."\r\n".'Reply-to:'.$email_from."\r\n".'X-mailer: PHP/'. phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

<!--include your own success html here-->

Thank you for contacting us. We will be in touch with you very soon!
<?php
}

?>