Showing posts with label Web Development. Show all posts
Wednesday, January 25, 2017
Ajax jQuery File Upload with Codeigniter using BlueImp with image preview
Hello friends, are you looking for ajax based jquery file upload using codeiginter. Then here is tutorial for you. In this tutorial we will discuss about File Uploading using PHP Codeigniter and Jquery with ajax. Blueimp file upload gives you a best option for file uploading. I found this script very useful for my projects and I would like to share this information with you. Blueimp is a free open source code.Why Blueimp?
Blueimp is a file upload widget which can be used for multiple file uploads with validations and is highly secured. It also supports cross domain, chunked and resumable file uploads. It can be used for image, audio, video etc., It has a progress bar shown for each image and supports drag and drop. It works with any server side platform such as Google App Engine, PHP, Python, Ruby on Rails, Java etc., However in this tutorial we are going to discuss about PHP and Codeigniter.
Demo
Blueimp with codeigniter
As we already discussed that Blueimp supports PHP, so we can use with Codeigniter too. Blueimp wiki says that you can easily integrate this script with Codeigniter but when I tried to work with it I found it very hard to do. I made it simpler and will share it with you.
How to integrate Blueimp with Codeigniter?
Open constants.php file in config folder and add the below given code in it. You can add it at the bottom of the code in constants.php
// Define Ajax Request
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
Now create a new php file using any text editor and add the following code to it.
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url', 'file'));
}}
public function do_upload() {
$upload_path_url = base_url() . 'files/';
//you should create a folder uploads in the root directory of your codeigniter
$config['upload_path'] = FCPATH . 'files/';
//to allow only image files of below type
$config['allowed_types'] = 'jpg|jpeg|png|gif';
//max size to upload else return error message. change it to more if you want to allow large files
$config['max_size'] = '50000';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
//Load the list of existing files in the upload directory
$existingFiles = get_dir_file_info($config['upload_path']);
$foundFiles = array();
$f=0;
foreach ($existingFiles as $fileName => $info) {
if($fileName!='thumbnails'){//Skip over thumbnails directory
//set the data for the json array
$foundFiles[$f]['name'] = $fileName;
$foundFiles[$f]['size'] = $info['size'];
$foundFiles[$f]['url'] = $upload_path_url . $fileName;
$foundFiles[$f]['thumbnailUrl'] = $upload_path_url . 'thumbnails/' . $fileName;
$foundFiles[$f]['deleteUrl'] = base_url() . 'upload/deleteImage/' . $fileName;
$foundFiles[$f]['deleteType'] = 'DELETE';
$foundFiles[$f]['error'] = null;
$f++;
}
}
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('files' => $foundFiles)));
} else {
$data = $this->upload->data();
// to re-size for thumbnail images un-comment and set path here and in json array
$config = array();
$config['image_library'] = 'gd2';
$config['source_image'] = $data['full_path'];
$config['create_thumb'] = TRUE;
$config['new_image'] = $data['file_path'] . 'thumbnails/';
$config['maintain_ratio'] = TRUE;
$config['thumb_marker'] = '';
$config['width'] = 300;
$config['height'] = 100;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
//set the data for the json array
$info = new StdClass;
$info->name = $data['file_name'];
$info->size = $data['file_size'] * 1024;
$info->type = $data['file_type'];
$info->url = $upload_path_url . $data['file_name'];
// I set this to original file since I did not create thumbnails. change to thumbnail directory if you do = $upload_path_url .'/thumbnails' .$data['file_name']
$info->thumbnailUrl = $upload_path_url . 'thumbnails/' . $data['file_name'];
$info->deleteUrl = base_url() . 'upload/deleteImage/' . $data['file_name'];
$info->deleteType = 'DELETE';
$info->error = null;
$files[] = $info;
//this is why we put this in the constants to pass only json data
if (IS_AJAX) {
echo json_encode(array("files" => $files));
//this has to be the only data returned or you will get an error.
//if you don't give this a json array it will give you a Empty file upload result error
//it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
// so that this will still work if javascript is not enabled
} else {
$file_data['upload_data'] = $this->upload->data();
$this->load->view('upload/upload_success', $file_data);
}
}
}
public function deleteImage($file) {//gets the job done but you might want to add error checking and security
$success = unlink(FCPATH . 'files/' . $file);
$success = unlink(FCPATH . 'files/thumbnails/' . $file);
//info to see if it is doing what it is supposed to
$info = new StdClass;
$info->sucess = $success;
$info->path = base_url() . 'files/' . $file;
$info->file = is_file(FCPATH . 'files/' . $file);
if (IS_AJAX) {
//I don't think it matters if this is set but good for error checking in the console/firebug
echo json_encode(array($info));
}
}
Saturday, May 30, 2015
How to determine what technology a website or web application is built?
Hello friends, hope you are doing good. In this tutorial I would like to discuss about the trick that helps you find out what technology a website is built with. Quite often I come across websites with good looking or good functionality, and wonder what technology was used to create such websites. You might have also had the same situation sometimes. Let's see what techniques are available to us to figure out the technologies or frameworks that have been used to build a particular website.
When I researched for the tools that helps to figure out the technologies I found few online tools and browser extensions. I gathered all the tools together to make it easier for developers.
Below are some tools for querying site details:
BuiltWith
BuiltWith is an online application where you can acquire information about the technology used behind a website. You could also check the competitive analysis about a website with BuiltWith. You should enter website URL in the search box. Then the application responds with backend and front end technology details, along with analytics and business intelligence information for a particular website.
DomainTools
DomainTools is an application that offers a basic whois search, whois histories for domain names, cross-IP lookups, a Name Server Spy, a typo-generator, and dozens of other useful domain tools.
The popular domain tools, the site also offers a variety of DNS tools, such as ping and traceroute. They also offer WhoIs Lookup, WhoIs History, reverse Whois, Hosting History, Reverse IP, Reverse Name Server, Reverse MX. Their powerful search features include domain suggestion search.
It also provide many of the tools at free of cost. However some tools have usage restrictions that require a subscription. Their subscription system allows you to get more points for the more money yu pay, and in turn the more tools you can use.
NetCraft
W3Techs
SimilarTech
Thursday, April 23, 2015
How to show password strength using JQuery
Hello friends, I want to discuss about JQuery code to show password strengths when a user types in a password into password field.
Password security is necessary to keep our accounts safe from hackers. Generally we use common passwords to remember them easily. However we should use secured passwords so that it couldn't be guessed by anyone. Recently I had a client who wants to show the password strength when a user types his password. So I tried the Jquery code which is explained in this tutorial to check the password strengths. This code will use JQuery regular expressions to check the strength of a password typed by the user.
I have also provided the CSS in this tutorial to add style to the message which shows the strengths of password entered.
I have also provided the CSS in this tutorial to add style to the message which shows the strengths of password entered.
Please check the below JQuery code:
$('#pwd').keyup(function(e) { var strongPass = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g"); var midPass = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g"); var morePass = new RegExp("(?=.{6,}).*", "g"); if (false == morePass.test($(this).val())) { $('#msg').html('Please enter more characters'); } else if (strongPass.test($(this).val())) { $('#msg').className = 'ok'; $('#msg').html('Great! your password is strong.'); } else if (midPass.test($(this).val())) { $('#msg').className = 'alert'; $('#msg').html('Better, your password strength is medium.'); } else { $('#msg').className = 'error'; $('#msg').html('Sorry, your password is too weak.'); } return true; });
Here I have included the CSS to add styles to the div when the password strength status changes while typing in the password filed.
CSS:
.error{ background:#BE4C39; color:#fff; }.alert{ background:#fd7c2a; color:#fff; }.ok{background:#3cc16e; color:#fff; }
Below is the HTML code for the input field and the div that holds the message which shows the password strength.
<input type="password" name="pwd" id="pwd" /><span id="msg"></span>
I used pwd as name and id in the above input fields and the respective id has been used in the JQuery code and "msg" is the id used for the span which holds the message for the password strength.
I hope this code will help you in your projects. Please don't hesitate to ask your queries in the comment section below. Thank you. Happy coding :) Labels: blogger tips, JQuery, Tips and Tricks, Web Development
Saturday, June 7, 2014
How to send activation link to email on user registration in PHP (Email verification)
During user registration in order to verify the email address of the user, a confirmation email is sent to the provided email address with activation link and when user clicks the link provided in the mail, his account gets activated. If you are looking for such PHP code. Then read this tutorial carefully.This is a basic code to implement email verification using PHP and MySQL. In this code I have shown how to get a link to user email. The link actually contains an id which is stored in the database for each user. Here we use PHP mail() function to send an email to the user after registration.
You may also read:
PHP contact form using mail function using JQuery toggle.
Beautiful contact form in PHP.
Here is the MySQL query to create users table with five columns id, name, email, password and status. We are using the first column "id" in activation link and status contains whether the user has been activated or not.Dump the below sql code into your MySql database.
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(70) NOT NULL,
`status` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
Follow the below given steps.
Step 1. Look How to connect MySql database using PHP and copy the full PHP code from the block and save the file as db.php.
Step 2. Copy the below code and save it as register.php
<form action="" method="post" >
<label>Name</label>
<input type="text" name="name" >
<label>Email</label>
<input type="text" name="email">
<label>Password</label>
<input type="password" name="pwd" id="pwd">
<input type="submit" name="submit" value="Register">
</form>
<?php
require_once("db.php");
if(isset($_POST['submit']))
{
$email = $_POST['remail'];
$check = mysql_query("SELECT email FROM users where email='$email'");
$num_rows = mysql_num_rows($check);
if($num_rows > 0)
{
echo "<script>alert('Email Already in Use. Please Choose another Email')</script>";
}
else
{
$name = $_POST['name'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$insert = mysql_query("INSERT INTO users(name,email,password) VALUES('$name','$email','$pwd')");
$id = mysql_insert_id($conn); //gets the last inserted id
$message = "<html>
<head></head>
<body>
<p>Hello ".$name.",</p>
<p>Your content here</p>
<p><a href=\"http://DOMAIN-NAME/activate.php?actid=".$id."\">http://DOMAIN-NAME/activate.php?actid=".$id."</a></p>
</body>
</html>";
$from = "your-mail-id"; //Ex: name@domain.com
$headers ='Reply-To: '. $from . "\r\n" ;
$headers.='From: '.$from. "\r\n";
$headers .='X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
mail($email, "Activate your account", $message, $headers);
}
}
?>
Step 3. Copy the below code and save it as activate.php
<?phphow to implement email verification system using PHP.
require_once("db.php");
$activationid = $_GET['actid'];
$check = mysql_query("SELECT status FROM users where id='$actid'",$api->db);
$num_rows = mysql_num_rows($check);
if($num_rows > 0)
{
$row = mysql_fetch_array($check);
$status = $row['status'];
$query = mysql_query("UPDATE users SET status = 1 where id = $actid",$api->db) or die(mysql_error());
}
else { echo "<script>alert(Activation link is not valid.')</script>"; }
?>
How to send activation link to email PHP
Email verification using PHP
Email verification script
User registration email check verify validate with PHP Labels: MySQL, PHP, Web Development
Friday, May 2, 2014
Google maps API to show map after button click using text input value javascript with hide and show
Hi friends, in this tutorial I am going to discuss about Google maps API using javascript. I worked with a project in which a user will add his address and that address needs to be shown in a map. This looks like a complex task but is a very simple task. Google Maps provides an API code to display maps and we are going to use that code here.How it works?
Google maps API gives the developers to add maps to their projects using the API code that is provided by Google Maps.In present tutorial I have the code that shows a map after button click. Here we have a input textbox in which we need to give the address of our wish and click the button below the textbox. Then a map of the particular address is displayed at the bottom.
Here the button text changes after the button is clicked. First the button contains "show".
After click the text will be changed as "hide".
That means I have added show/hide to the map area to show/hid the map when the button click event changes.
You can look at the demo below.
Code to show/hide:
var obj = document.getElementById(unique + "map_area");
var subm = document.getElementById("subm");
if (obj.style.display=="none"){
obj.style.display='block';
subm.value = 'Hide';
} else if(obj.style.display=="block"){
obj.style.display='none';
subm.value = 'Show';
}
Google maps API Code:
var map = null;Here is the entire code below. Just copy the below code and save it with any name in .html extension.
var geocoder = null;
function showAddress(address, unique) {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById(unique + "map_area"));
map.setUIToDefault();
geocoder = new GClientGeocoder();
}
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 15);
var marker = new GMarker(point, {draggable: true});
map.addOverlay(marker);
GEvent.addListener(marker, "dragend", function() {
marker.openInfoWindowHtml(marker.getLatLng().toUrlValue(6));
});
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(marker.getLatLng().toUrlValue(6));
});
GEvent.trigger(marker, "click");
}
}
);
}
Full Code for google map with text box and button having show/hide funtionality.
<html>
<head>
<title>Google map TricksTown</title>
<script src="http://maps.google.com/maps?file=api&v=3" type="text/javascript"></script>
<script type="text/javascript">
var map = null;
var geocoder = null;
function showAddress(address, unique) {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById(unique + "map_area"));
map.setUIToDefault();
geocoder = new GClientGeocoder();
}
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 15);
var marker = new GMarker(point, {draggable: true});
map.addOverlay(marker);
GEvent.addListener(marker, "dragend", function() {
marker.openInfoWindowHtml(marker.getLatLng().toUrlValue(6));
});
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(marker.getLatLng().toUrlValue(6));
});
GEvent.trigger(marker, "click");
}
}
);
}
var obj = document.getElementById(unique + "map_area");
var subm = document.getElementById("subm");
if (obj.style.display=="none"){
obj.style.display='block';
subm.value = 'Hide';
} else if(obj.style.display=="block"){
obj.style.display='none';
subm.value = 'Show';
}
}
</script>
</head>
<body>
<form action="" onsubmit="showAddress(this.address.value, this.unique.value); return false">
<input type="hidden" name="unique" value="" />
<input type="text" name="address" value="balajinagar" />
<div class="view-map" title="View map"><input type="submit" id="subm" value="Show" /></div>
</form>
<div id="map_area" style="display:none; width: 615px; height: 200px"></div>
</body>
</html>
Demo:
Saturday, March 29, 2014
How to get website domains at cheaper rates?
Today every business needs a website to grow in this competitive world. So most of the businesses are getting online with websites. Not only for businesses but also to earn money online bloggers are establishing blogs and running them by writing content that is useful for the readers. I have seen most of them are searching for money earning methods online without any investment and mostly students want to start blogging. If you are a student looking to start a blog at less cost then this trick will help you very much.You can read more about online money earning methods and blogging
What is a blog?
How to earn money online?
Can I earn from blog?
How Can Students Earn More Money?
Why every freelance worker wants to be a blogger?
5 Idiotic ways you can promote your blog
8 Tips to reduce load time of Blog/Website
Make your own Blank Template for Blogger
The simple way to get a domain at cheaper rates is just go to google and search for cheap domains. You will see the results something like the below image. Just click on the links which are displayed in the top that have offers as shown in the marked part of the below screenshot.The domain hosting sites like GoDaddy and BigRock ads will be displayed in the results. This can be used to register your domains at cheaper rates. When you go for registering a domain directly from their website then you will not get these offers. Because when you search for domains on google the respective service providers give you the ad links for special offers that contain promo codes. So you can utilize this type of special offers to get domains at cheaper rates.
Thank you. I hope this post might have helped you a lot in choosing a plan to avail domains at cheaper rates. Please share your opinions in the comments below. Labels: Domains, Hosting, internet tips, Tips and Tricks, Web Development
Friday, March 28, 2014
How to display preview of image before upload using JQuery

For this purpose we can use JQuery code which will show the image before it is uploaded. Today I am going to discuss about the code which helps you preview the image before upload.
Here is the code for showing image before uploading.
JQuery:
$(document).ready(function(){
$("#image").change(function(){
var file = document.getElementById("image").files[0];
var readImg = new FileReader();
readImg.readAsDataURL(file);
readImg.onload = function(e) {
$('.imagepreview').attr('src',e.target.result).fadeIn();
}
})
})
This code uses the advantage of HTML5 attribute. FileReader reads the file, here the file is an image. It fetches the URL of the current image to show up when it is selected through file browser field.
The above code jquery code fetches the image and shows the preview. Below is the HTML code which refers the above jquery code.
HTML:
<input name="image" type="file" class="image" id="image"><br/>
<img class="imagepreview" src="">
Since the above HTML code has no image in the source it displays a broken image, so in order to eliminate the broken image we can use the code for this link to avoid broken images or we can use the following CSS code instead of the code specified in the link. I recommend you to use the CSS code below.
CSS:
.imagepreview{width:500px;
display:none;}
Here are some helpful posts for bloggers and web designers.
Add Google Plus Follower Gadget For Blogger
How to add floating widget to blogger blog
Add awesome sticky footer menu to Blogger with simple HTML
How to trace details of an unknown person with mobile number
Why every freelance worker wants to be a blogger?
Which is the best way to optimize mobile site?
How facebook fan page can make you money?
Separate Contact page in Blogger
How to add Contact Form Widget to blogger Official Plugin
SEO Title Tag Best Practices
How to disable graph search on facebook/trick to remove facebook graph
How to find fake profile pictures on facebook?
Add Facebook Like Button below posts titles (Speed Loading)
How to delete Facebook account permanently?
How to use facebook on slow internet connections
How to delete Google Search History/Cache?
8 Tips to reduce load time of Blog/Website
Xenon Blogger Template Download
3 ways to make money online
5 Idiotic ways you can promote your blog
I have given you three blocks of code for image preview. Look below for the complete code after combining all the above blocks of code.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Preview image before upload by TricksTown.com</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("#image").change(function(){
var file = document.getElementById("image").files[0];
var readImg = new FileReader();
readImg.readAsDataURL(file);
readImg.onload = function(e) {
$('.imagepreview').attr('src',e.target.result).fadeIn();
}
})
})
</script>
<style>
.imagepreview{width:500px;
display:none;}
</style>
</head>
<body>
<input name="image" type="file" class="image" id="image"><br/>
<img class="imagepreview" src="">
</body>
</html>
Copy the above code and paste it in your notepad. Save it with .html extension and check it.
Enjoy... :) Happy coding.
Thank you. If you have any doubts, please comment below. Spam comments will be removed. Labels: HTML5, JQuery, Web Design, Web Development
Thursday, March 27, 2014
How to hide or fix a broken image using jquery
We commonly face a problem with broken images on websites. Our browsers will show a broken image when the link to an image doesn't work or when there is no image. Mostly this problem is faced when you make dynamic websites in which you work on putting a default image for posts. When a user/visitor come across your site having a broken image then he/she may lose interest on your website. So we need to put a small JQuery code so that the broken image disappears. In today's tutorial I want to show you the code for hiding the broken images.You may like these
Get free likes for your facebook account.
Login script in PHP
Delete file using PHP
Delete Facebook account permanently
Disable graph search on Facebook
Pagination with PHP
Awesome stylish sliding professional contact form for your website
Use facebook on slow internet
How to delete google cache from search
How to scare your friends with simple code
Just look at the code below.
<script>
$(document).ready(function(){
$("img").error(function(){
$(this).hide();
});
})
</script>
Copy the above code and paste it above the closing </head> tag. That's it. You are done. is
Explanation:
$(document).ready(function()) says the function to execute when the page loads.$("img") finds the img tag.
error(function()) checks if the img tag has any error and executes the function to hide the broken image using $(this).hide();
Here this refers to the current one i.e., the img tag.
Thanks for reading this article. If you have any doubts please don't hesitate to comment below. Labels: blogger tips, JQuery, Web Design, Web Development
Friday, February 21, 2014
How to delete a file using PHP
When I was working with a project with file uploads, I had a thought of deleting those files with php. unlink is used to delete a file from a folder. It takes the file path along with the file name as parameter. This funtion can be simply written as shown below.
unlink("path_to_img/file_name.extension");For example if you want to delete a text file sample.txt which inside the folder uploads then you need to use like this unlink("uploads/sample.txt);
You can use the same code to delete any file, just by changing the file extension.
Thank you very much. If you have any doubts just comment below. I'm always happy to help you.
Tags:
How to delete a file using PHP? How to delete a file from a folder using PHP? php code to delete a file
php code to unlink a file. from folder remove file using php .
remove files from folder using php
php script to remove files
php script to delet files
how can i remove file using php
how can i delete a file using php
php delete file
php file delete
php files delete using code
php deletion of a file
file deletion using php
delete an image using php
delete a photo using php
delete photo images with php
php code to delete photos
php photo deleting code
php function to delete photo
php function to remove images
php function to remove images photos and files
How to delete a file using php
how to delete an image from folder using php
how can i delete photo usnig php
Labels: PHP, Web Development
Thursday, February 13, 2014
How to fetch youtube video thumbnail title using javascript
Hi friends, we have discussed about pagination tutorial using PHP and MySql in previous post. In this tutorial I came up with a script to fetch youtube videos on the client side using javascript. Sometimes we need to put video thumbnail and it's title to show as gallery. I worried about fetching videos into my website first. I googled for the code and found youtube API code. Using youtube API we can retrieve upto 50 videos. Youtube API code fetches last 50 videos uploaded by the user through feeds.
Now let me explain you about the javascript code to fetch youtube videos. It contains a small code that fetches the video thumbnails directly from youtube into your site. You just need to put video id into the code. Here in this tutorial I have included CSS styles to give a style to the video thumbnails.
Javascript code with HTML:
<div id="vidC">
<div id="vidThumb">
<script type="text/javascript">
//function to call youtube feeds
function youtubeFeedCallback(data) {
var s = '';
s += '<img src="http://i1.ytimg.com/vi/YOUTUBE-VIDEO-ID/mqdefault.jpg"/>'; //fetching the thumbnail image of the video
s += '<p style="color:white; font-size:13px;"> ' + data.entry.title.$t + '</p>'; //here we get the title of the video
document.write(s);//writes the above values in HTML
}
</script>
<!--youtube feeds API-->
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/YOUTUBE-VIDEO-ID?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>
</div>
Copy the above code and replace YOUTUBE-VIDEO-ID with the video ID from youtube.
Ex:
<script type="text/javascript">
//function to call youtube feeds
function youtubeFeedCallback(data) {
var s = '';
s += '<img src="http://i1.ytimg.com/vi/mhzyi9nDHFI/mqdefault.jpg"/>'; //fetching the thumbnail image of the video
s += '<p style="color:white; font-size:13px;"> ' + data.entry.title.$t + '</p>'; //here we get the title of the video
document.write(s);//writes the above values in HTML
}
</script>
<!--youtube feeds API-->
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/mhzyi9nDHFI?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>
If you want to include styles then just copy the below CSS code.
<style>Put these both blocks of code in a file and save it in HTML. Now the code will fetch the youtube thumbnails along with their titles.
#vidC {
width: 282px;
height: 190px;
padding: 5px;
margin-right: 15px;
background-color: #000000;
box-shadow:2px 0px 10px #333333;
margin-bottom: 20px;
float: left;
}
#vidThumb img{
width: 282px;
height: 158px;
padding: 0;
border:none;
}
</style>
Thank you. Please comment below if you need any help regarding this tutorial.
Labels: Javascript, Tips and Tricks, Web Development, Youtube
Wednesday, February 12, 2014
Create simple pagination with PHP and MySQL
Hi friends, todays tutorial is about creating a simple pagination using PHP and MySQL. I am going to explain you about creating a page with PREVIOUS and NEXT links at the bottom of your page with numberings.
Before looking at the code let's discuss about pagination concept. Pagination let's you create links that contains the data which is the continuation of the current item. Whenever there is large amount of data then it looks hard to load the entire data into a single page. Hence, we use the concept of pagination to allow the content to be split into parts and show only some part of the content per each page. This will give your website viewers a great experience and also has an advantage of speed loading of data, inorder to avoid the inconvenience.
You may also like:
Beautiful contact form for websites
Add Google plus follower widget to blogger
Stylish sticky menu bar with social icons for footer
Make money with facebook
Add contact form to your blogger blog free
Get more visitors to your site with SEO
Remove facebook graph search
Trick to find fake accounts on facebook
Get free mobile balance 100% working trick in India only
Speed loading like button for blogger
Delete facebook account permanently 100% working trick
Trick to use facebook on slow internet
How to get more page likes on facebook
How to delete google search history
8 Tricks to reduce load time of your website
3 ways to make money online without investment
5 idiotic ways to promote your blog
I said before that this code is based on PHP and MySQL, hence this code reads the data from the database tables and displays it on our page with pagination links. Since the data is being retrieved from the tables in the database we need to use sql connection mysql_connect() and then we need select database using mysql_select_db(). Let us see briefly how to connect to database using these two functions in PHP.
Code for Database connection:
<?phpThe above code is used for datavase connection. Now let's see the code that is required to generate pagination links.
$dbhostname = "host name here"; //replace with your host name usually localhostname
$dbusername = "database user name"; //replace with your database user name.
$dbpassword = "database password"; //replace with your password
$dbname = "database name"; //replace with your database name
$conn = mysql_connect($dbhostname, $dbusername, $dbpassword) or die ("Database connection failed");
mysql_select_db($dbname) or die ("Database selection failed");
?>
Code to generate pagination:
<?phpThe above part of the code is to generate pagination links. I have clearly explained within the comments. So please look the code carefully and understand it. The above code is not included with database connection. Hence we can combine both the above codes together as shown below.
function create_pagination($current_page, $total_pages)
{
$create_page_links = '';
// generates anchor tag for previous page if this is not first page
if ($current_page > 1)
{
$create_page_links .= '<a href="current-page-name.php?page=' . ($current_page - 1) . '">PREV</a> ';
}
// generates page links with numbers till the loop ends
for ($count = 1; $count <= $total_pages; $count++)
{
if ($current_page == $count)
{
$create_page_links .= ' ' . $count;
}
else
{
$create_page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?page=' . $count . '"> ' . $count . '</a>';
}
}
// generates anchor tag link for next page if this is not last page
if ($current_page < $total_pages) {
$create_page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?page=' . ($current_page + 1) . '">NEXT</a>';
}
return $create_page_links;
}
// Calculate pagination
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page =15; // displays number of results per single page replace 15 with number of pages you may want
$jump = (($current_page - 1) * $results_per_page); //3*2
$query = "select * FROM table_name order by id desc";//query to select from table
$result = mysql_query($query1);
$total = mysql_num_rows($result); //counts number of rows
$total_pages = ceil($total / $results_per_page);
$query = $query . " LIMIT $jump, $results_per_page";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
//your code here to retrieve rows
}
?>
<!--creates links to display at bottom with previous, next and page numbers-->
<div style="float:left; padding:20px">
<?php
if ($total_pages > 1)
{
echo create_pagination($current_page, $total_pages);
}
?>
</div>
Pagination code with database connection:
The above code is the final one.Copy the code and use it wherever you want.<?php$dbhostname = "host name here"; //replace with your host name usually localhostname
$dbusername = "database user name"; //replace with your database user name.
$dbpassword = "database password"; //replace with your password
$dbname = "database name"; //replace with your database name
$conn = mysql_connect($dbhostname, $dbusername, $dbpassword) or die ("Database connection failed");
mysql_select_db($dbname) or die ("Database selection failed");
function create_pagination($current_page, $total_pages)
{
$create_page_links = '';
// generates anchor tag for previous page if this is not first page
if ($current_page > 1)
{
$create_page_links .= '<a href="current-page-name.php?page=' . ($current_page - 1) . '">PREV</a> ';
}
// generates page links with numbers till the loop ends
for ($count = 1; $count <= $total_pages; $count++)
{
if ($current_page == $count)
{
$create_page_links .= ' ' . $count;
}
else
{
$create_page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?page=' . $count . '"> ' . $count . '</a>';
}
}
// generates anchor tag link for next page if this is not last page
if ($current_page < $total_pages) {
$create_page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?page=' . ($current_page + 1) . '">NEXT</a>';
}
return $create_page_links;
}
// Calculate pagination
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page =15; // displays number of results per single page replace 15 with number of pages you may want
$jump = (($current_page - 1) * $results_per_page); //3*2
$query = "select * FROM table_name order by id desc";//query to select from table
$result = mysql_query($query1);
$total = mysql_num_rows($result); //counts number of rows
$total_pages = ceil($total / $results_per_page);
$query = $query . " LIMIT $jump, $results_per_page";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
//your code here to retrieve rows}
?>
<!--creates links to display at bottom with previous, next and page numbers-->
<div style="float:left; padding:20px">
<?php
if ($total_pages > 1)
{
echo create_pagination($current_page, $total_pages);
}
?>
</div>
Note: Now just make these changes before using the code.
host name here //replace with your host name usually localhostname
database user name //replace with your database user name.
database password//replace with your password
database name //replace with your database name
current-page-name.php //Replace with the name of the page where this code is being used.
$results_per_page =15 //change 15 to whatever the number results you may want to display ina single page
//your code here to retrieve rows //Code to fetch the rows from a database table
Thanks for reading this articles.
If you still have any queries then please don't hesitate to comment below. Labels: MySQL, PHP, Web Design, Web Development
Subscribe to:
Posts (Atom)