Learn C programming
This Blog will help you to learn c programming in hindi as well as in hindi all students can find number of examples for c programming and Python Programming
PHP Tutorials for beginners and professionals, WordPress tutorials, Codeigniter tutorials for beginners and professionals, MySQL tutorials for beginners and professionals, SQL tutorials for beginners and professionals, Laravel tutorials for beginners and professionals, PHP object-oriented tutorials for beginners and professionals, Python tutorials for beginners and professionals
users table.CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
application/config/database.php and define Database connection.$db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', // Username 'password' => '', // Password 'database' => 'tutorial', // Database name 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
Default controller
application/config/routes.php and edit default_controller value to User.$route['default_controller'] = 'User';
database library.application/config/autoload.php and add the database in libraries array().$autoload['libraries'] = array("database");
application/models/ directory and create new Main_model.php file.Main_model and extends CI_Model Class. Within this class define a method insertNewuser() which inserts records into the MySQL Database table.username is already in use or not if not then insert record with $this->db->insert('users', $newuser).<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main_model extends CI_Model {
function insertNewuser($postData){
$response = "";
if($postData['txt_name'] !='' || $postData['txt_uname'] !='' || $postData['txt_email'] !='' ){
// Check entry
$this->db->select('count(*) as allcount');
$this->db->where('username', $postData['txt_uname']);
$q = $this->db->get('users');
$result = $q->result_array();
if($result[0]['allcount'] == 0){
// Insert record
$newuser = array(
"name" => trim($postData['txt_name']),
"username" => trim($postData['txt_uname']),
"email" => trim($postData['txt_email'])
);
// $this->db->insert( [table-name], Array )
$this->db->insert('users', $newuser);
$response = "Record insert successfully.";
}else{
$response = "Username already in use";
}
}else{
$response = "Form is empty.";
}
return $response;
}
}
application/controllers/ directory and create a User.php file.User and extends CI_controller Class.index() method from where load model and view. Handle request when the <form> is got submitted.$this->input->post(); and pass it to model insertNewuser() method. According to response pass the data to the view.<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
public function index(){
// load base_url
$this->load->helper('url');
// Check form submit or not
if($this->input->post('submit') != NULL ){
// POST data
$postData = $this->input->post();
//load model
$this->load->model('Main_model');
// get data
$data['response'] = $this->Main_model->insertNewuser($postData);
// load view
$this->load->view('user_view',$data);
}else{
$data['response'] = '';
// load view
$this->load->view('user_view');
}
}
}
application/views/ directory and create a user_view.php file.base_url()<!doctype html>
<html>
<head>
<title>Insert record to Database Table in Codeigniter</title>
</head>
<body>
<b><?php if(isset($response)) echo $response; ?></b>
<form method='post' action='<?php echo base_url(); ?>'>
<table>
<tr>
<td>Name</td>
<td><input type='text' name='txt_name'></td>
</tr>
<tr>
<td>Username</td>
<td><input type='text' name='txt_uname'></td>
</tr>
<tr>
<td>Email</td>
<td><input type='text' name='txt_email'></td>
</tr>
<tr>
<td> </td>
<td><input type='submit' name='submit' value='Submit'></td>
</tr>
</table>
</form>
</body>
</html>
application/config/autoload.php.users table in the example.CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
config.php file.<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
<head> section or end of </body>. <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!-- jQuery UI --> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<table>
<tr>
<td>Single selection</td>
<td><input type='text' id='autocomplete' ></td>
</tr>
<tr>
<td>Selected User id</td>
<td><input type='text' id='selectuser_id' /></td>
</tr>
<tr>
<td>Multiple Selection</td>
<td><input type='text' id='multi_autocomplete' ></td>
</tr>
<tr>
<td>Selected User ids</td>
<td><input type='text' id='selectuser_ids' /></td>
</tr>
</table>
fetchData.php file.users Table. Declare an Array variable $response and initialize it with an associative array where pass the $row['id'] in value key and $row['name'] in label key.<?php
include "config.php";
if(isset($_POST['search'])){
$search = $_POST['search'];
$query = "SELECT * FROM users WHERE name like'%".$search."%'";
$result = mysqli_query($con,$query);
$response = array();
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['id'],"label"=>$row['name']);
}
echo json_encode($response);
}
exit;
NOTE – Removevaluekey from the array if you only want to work it name e.g.$response[] = array("label"=>$row['name']);
<input id='autocomplete'> and <input id='multi_autocomplete'> by calling autocomplete() method.source option to fetch users name when the key is got pressed. Get the typed value with request.term and pass it in AJAX.response() method.extractLast() function and send AJAX request to fetch records.select functionality because when an option is been selected then the value is been shown on the screen instead of the label if the value is been defined.select option and store the selected item value to <input type='text' id='seluserid' > and set label to autocomplete element.ui.item.label and assign in the $('#multi_autocomplete').ui.item.value in $('#selectuser_ids').$( function() {
// Single Select
$( "#autocomplete" ).autocomplete({
source: function( request, response ) {
// Fetch data
$.ajax({
url: "fetchData.php",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
// Set selection
$('#autocomplete').val(ui.item.label); // display the selected text
$('#selectuser_id').val(ui.item.value); // save selected id to input
return false;
}
});
// Multiple select
$( "#multi_autocomplete" ).autocomplete({
source: function( request, response ) {
var searchText = extractLast(request.term);
$.ajax({
url: "fetchData.php",
type: 'post',
dataType: "json",
data: {
search: searchText
},
success: function( data ) {
response( data );
}
});
},
select: function( event, ui ) {
var terms = split( $('#multi_autocomplete').val() );
terms.pop();
terms.push( ui.item.label );
terms.push( "" );
$('#multi_autocomplete').val(terms.join( ", " ));
// Id
terms = split( $('#selectuser_ids').val() );
terms.pop();
terms.push( ui.item.value );
terms.push( "" );
$('#selectuser_ids').val(terms.join( ", " ));
return false;
}
});
});
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
NOTE – Remove
select option if you have not return value key from the AJAX file.value in the element for further processing.posts table.CREATE TABLE `posts` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `title` varchar(100) NOT NULL, `description` text NOT NULL, `link` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
($rowperpage=3).<input id='row'> store current row position.<input id='allcount'> store total number of rows.<div class="container">
<?php
include "config.php";
// Row per page
$rowperpage = 3;
// counting total number of posts
$allcount_query = "SELECT count(*) as allcount FROM posts";
$allcount_result = mysqli_query($con,$allcount_query);
$allcount_fetch = mysqli_fetch_array($allcount_result);
$allcount = $allcount_fetch['allcount'];
// select first 3 posts
$query = "select * from posts order by id asc limit 0,$rowperpage ";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$title = $row['title'];
$content = $row['description'];
$shortcontent = substr($content, 0, 160)."...";
$link = $row['link'];
?>
<div class="post" id="post_<?php echo $id; ?>">
<h1><?php echo $title; ?></h1>
<p>
<?php echo $shortcontent; ?>
</p>
<a href="'.$link.'" target="_blank" class="more">More</a>
</div>
<?php
}
?>
<input type="hidden" id="row" value="0">
<input type="hidden" id="all" value="<?php echo $allcount; ?>">
</div>
fetch_data.php file. Using this file when sending AJAX request from jQuery.posts table according to $_POST['row'] value.<?php
// configuration
include 'config.php';
$row = $_POST['row'];
$rowperpage = 3;
// selecting posts
$query = 'SELECT * FROM posts limit '.$row.','.$rowperpage;
$result = mysqli_query($con,$query);
$html = '';
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$title = $row['title'];
$content = $row['description'];
$shortcontent = substr($content, 0, 160)."...";
$link = $row['link'];
// Creating HTML structure
$html .= '<div id="post_'.$id.'" class="post">';
$html .= '<h1>'.$title.'</h1>';
$html .= '<p>'.$shortcontent.'</p>';
$html .= '<a href="'.$link.'" target="_blank" class="more">More</a>';
$html .= '</div>';
}
echo $html;
.container{
width: 55%;
margin: 0 auto;
border: 0px solid black;
padding: 10px 0px;
}
/* post */
.post{
width: 97%;
min-height: 200px;
padding: 5px;
border: 1px solid gray;
margin-bottom: 15px;
}
.post h1{
letter-spacing: 1px;
font-weight: normal;
font-family: sans-serif;
}
.post p{
letter-spacing: 1px;
text-overflow: ellipsis;
line-height: 25px;
}
/* more link */
.more{
color: blue;
text-decoration: none;
letter-spacing: 1px;
font-size: 16px;
}
scroll event handler on the window to detect page scroll.$(document).height() - $(window).height().var position = $(window).scrollTop(); var bottom = $(document).height() - $(window).height();
position == bottom then finds next row value and if it is not greater than allcount value then send AJAX request where pass row value as data and on successful callback append response.$(document).ready(function(){
$(window).scroll(function(){
var position = $(window).scrollTop();
var bottom = $(document).height() - $(window).height();
if( position == bottom ){
var row = Number($('#row').val());
var allcount = Number($('#all').val());
var rowperpage = 3;
row = row + rowperpage;
if(row <= allcount){
$('#row').val(row);
$.ajax({
url: 'fetch_details.php',
type: 'post',
data: {row:row},
success: function(response){
$(".post:last").after(response).show().fadeIn("slow");
}
});
}
}
});
});
users table in the tutorial example.CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `fname` varchar(80) NOT NULL, `lname` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
config.php file.<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
ng-app='myapp' and ng-controller='userCtrl' on <div>.ng-model directive and a button with ng-click directive.ng-repeat directive on <tr> to show the list of users using AngularJS. Added Delete button following with user record and define ng-click="remove(index,userid.id)".<div ng-app='myapp' ng-controller="userCtrl">
<!-- New entry -->
<table>
<tr>
<td>First Name</td>
<td><input type='text' id='txt_fname' ng-model='fname'></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type='text' id='txt_lname' ng-model='lname'></td>
</tr>
<tr>
<td>Username</td>
<td><input type='text' id='txt_uname' ng-model='uname'></td>
</tr>
<tr>
<td> </td>
<td><input type='button' id='but_save' value='Save' ng-click="add()" ></td>
</tr>
</table>
<!-- User list -->
<table border="1">
<tr>
<th>First name</th>
<th>Last name</th>
<th>Username</th>
<th> </th>
</tr>
<tr ng-repeat="user in users">
<td>{{user.fname}}</td>
<td>{{user.lname}}</td>
<td>{{user.username}}</td>
<td><input type='button' ng-click='remove($index,user.id);' value='Delete'></td>
</tr>
</table>
</div>
addremove.php file.$request_type value –users table if not exists then insert a new record and return a JSON response.users table.<?php
include 'config.php';
$data = json_decode(file_get_contents("php://input"));
$request_type = $data->request_type;
// Get all records
if($request_type == 1){
$stmt = $con->prepare("SELECT * FROM users");
$stmt->execute();
$result = $stmt->get_result();
$data = array();
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$data[] = array("id"=>$row['id'],"fname"=>$row['fname'],"lname"=>$row['lname'],"username"=>$row['username']);
}
}
$stmt->close();
echo json_encode($data);
exit;
}
// Insert record
if($request_type == 2){
$fname = $data->fname;
$lname = $data->lname;
$username = $data->uname;
// Check username already exists
$stmt = $con->prepare("SELECT * FROM users WHERE username=?");
$stmt->bind_param('s',$username);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
$return_arr = array();
if($result->num_rows == 0){
// Insert
$insertSQL = "INSERT INTO users(fname,lname,username ) values(?,?,?)";
$stmt = $con->prepare($insertSQL);
$stmt->bind_param("sss",$fname,$lname,$username);
$stmt->execute();
$lastinsert_id = $stmt->insert_id;
if($lastinsert_id > 0){
$return_arr[] = array("id"=>$lastinsert_id,"fname"=>$fname,"lname"=>$lname,"username"=>$username);
}
$stmt->close();
}
echo json_encode($return_arr);
exit;
}
// Delete record
if($request_type == 3){
$userid = $data->userid;
// Check userid exists
$stmt = $con->prepare("SELECT * FROM users WHERE id=?");
$stmt->bind_param('i',$userid);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
if($result->num_rows > 0){
// Delete
$deleteSQL = "DELETE FROM users WHERE id=?";
$stmt = $con->prepare($deleteSQL);
$stmt->bind_param("i",$userid);
$stmt->execute();
$stmt->close();
echo 1;
}else{
echo 0;
}
exit;
}
$http request from the controller to get all users records where pass request_type: 1 as data. Initialize $scope.users with response data.$http post request and set request_type: 2. Push response.data[0] value in $scope.users if response.data is not empty.userid from $http and set request_type: 3. Remove record from $scope.users using splice() if response.data == 1.<script>
var fetch = angular.module('myapp', []);
fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
// Get all records
$http({
method: 'post',
url: 'addremove.php',
data: {request_type:1},
}).then(function successCallback(response) {
$scope.users = response.data;
});
// Add new record
$scope.add = function(){
$http({
method: 'post',
url: 'addremove.php',
data: {fname:$scope.fname,lname:$scope.lname,uname:$scope.uname,request_type:2},
}).then(function successCallback(response) {
if(response.data.length > 0)
$scope.users.push(response.data[0]);
else
alert('Record not inserted.');
});
}
// Remove record
$scope.remove = function(index,userid){
$http({
method: 'post',
url: 'addremove.php',
data: {userid:userid,request_type:3},
}).then(function successCallback(response) {
if(response.data == 1)
$scope.users.splice(index, 1);
else
alert('Record not deleted.');
});
}
}]);
</script>
$http request for this define multiple if statement which executes according to request type.users table in the tutorial example.CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
config.php file.<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
ng-click='containerClicked()' on <div class='container'> to detect outside click of a search box and suggestion list <ul><li>.<ul> <li>.ng-keyup='fetchUsers()‘ and ng-model directive.Also, add ng-click='searchboxClicked($event)'.<li> using ng-repeat directive. Define ng-click directive which calls setValue($index,$event).<body ng-app='myapp'>
<div class='container' ng-controller="fetchCtrl" ng-click='containerClicked();' >
<input type='text'
ng-keyup='fetchUsers()'
ng-click='searchboxClicked($event);'
ng-model='searchText'
placeholder='Enter text'><br>
<ul id='searchResult' >
<li ng-click='setValue($index,$event)'
ng-repeat="result in searchResult" >
{{ result.name }}
</li>
</ul>
</div>
</body>
.container{
width: 100%;
height: 300px;
}
#searchResult{
list-style: none;
padding: 0px;
width: 250px;
position: absolute;
margin: 0;
}
#searchResult li{
background: lavender;
padding: 4px;
margin-bottom: 1px;
}
#searchResult li:nth-child(even){
background: cadetblue;
color: white;
}
#searchResult li:hover{
cursor: pointer;
}
input[type=text]{
padding: 5px;
width: 250px;
letter-spacing: 1px;
}
getData.php file.users table according to POST value and limit query result to 5. Initialize the array with the users name and return a JSON value.<?php
include 'config.php';
$data = json_decode(file_get_contents("php://input"));
$search = $data->searchText;
// Fetch 5 records
$sel = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$data[] = array("name"=>$row['name']);
}
echo json_encode($data);
keydown event trigger on the input box.$http request where pass input value $scope.searchText as data. Initialize $scope.searchResult with response.data on successfully callback.$scope.searchText with $scope.searchResult[index].name (selected value) and empty $scope.searchResult. Execute $event.stopPropagation() to stop parent click from trigger.$event.stopPropagation() to stop parent click from trigger.<div class='container'> click. Empty the $scope.searchResult.var fetch = angular.module('myapp', []);
fetch.controller('fetchCtrl', ['$scope', '$http', function ($scope, $http) {
// Fetch data
$scope.fetchUsers = function(){
var searchText_len = $scope.searchText.trim().length;
// Check search text length
if(searchText_len > 0){
$http({
method: 'post',
url: 'getData.php',
data: {searchText:$scope.searchText}
}).then(function successCallback(response) {
$scope.searchResult = response.data;
});
}else{
$scope.searchResult = {};
}
}
// Set value to search box
$scope.setValue = function(index,$event){
$scope.searchText = $scope.searchResult[index].name;
$scope.searchResult = {};
$event.stopPropagation();
}
$scope.searchboxClicked = function($event){
$event.stopPropagation();
}
$scope.containerClicked = function(){
$scope.searchResult = {};
}
}]);
ng-click on the parent to detect outside of suggestion list and search box. Stop the parent click from trigger using .stopPropagation() when clicked on the suggestion list or search box.users table in the tutorial example.CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `password` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
config.php file.<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
ng-keyup directive on username input field that calls checkUsername().<div > following with username input field to show the available status and to adjust classes on <div> define ng-class directive.<body ng-app='myapp'>
<div class="container" ng-controller='signup'>
<div id="div_reg">
<h1>Registration</h1>
<div>
<input type="text" class="textbox" id="txt_name" ng-model="name" placeholder="Name"/>
</div>
<!-- Username -->
<div>
<input type="text" class="textbox" id="txt_uname" ng-model="username" ng-keyup='checkUsername()' placeholder="Username" />
<div ng-class="addClass(unamestatus)" >{{ unamestatus }}</div>
</div>
<div>
<input type="password" class="textbox" id="txt_pwd" ng-model="password" placeholder="Password"/>
</div>
<div>
<input type="submit" value="Submit" name="but_submit" id="but_submit" />
</div>
</div>
</div>
</body>
/* Container */
.container{
margin: 0 auto;
width: 70%;
}
/* Registration */
#div_reg{
border: 1px solid gray;
border-radius: 3px;
width: 470px;
height: 370px;
box-shadow: 0px 2px 2px 0px gray;
margin: 0 auto;
}
#div_reg h1{
margin-top:0px;
font-weight: normal;
padding:10px;
background-color:cornflowerblue;
color:white;
font-family:sans-serif;
}
#div_reg div{
clear: both;
margin-top: 10px;
padding: 5px;
}
#div_reg .textbox{
width: 96%;
padding: 7px;
}
#div_reg input[type=submit]{
padding: 7px;
width: 100px;
background-color: lightseagreen;
border: 0px;
color: white;
}
/* Response */
.response{
padding: 6px;
display: block;
}
.hide{
display: none;
}
.exists{
color: green;
}
.not-exists{
color: red;
}
uname_check.php.users table and return a response.<?php
include 'config.php';
$data = json_decode(file_get_contents("php://input"));
// Username
$uname = $data->username;
$resText = '';
if($uname != ''){
// Check username
$sel = mysqli_query($con,"select count(*) as allcount from users where username = '".$uname."' ");
$row = mysqli_fetch_array($sel);
$resText = "Available";
if($row['allcount'] > 0){
$resText = 'Not available';
}
}
echo $resText;
$http request to check the username exists or not and initialize $scope.unamestatus with response.data.unamestatus value.var fetch = angular.module('myapp', []);
fetch.controller('signup', ['$scope', '$http', function ($scope, $http) {
// Check username
$scope.checkUsername = function(){
$http({
method: 'post',
url: 'uname_check.php',
data: {username:$scope.username}
}).then(function successCallback(response) {
$scope.unamestatus = response.data;
});
}
// Set class
$scope.addClass = function(unamestatus){
if(unamestatus == 'Available'){
return 'response exists';
}else if(unamestatus == 'Not available'){
return 'response not-exists';
}else{
return 'hide';
}
}
}]);
users table.CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
config.php file.<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
name column in the users Table and count total records on a character.<li> elements and add <a > where use firstCharacter to create source.$_GET['char'] value to create the SELECT query and list records.<div id="content">
<?php
include("config.php");
?>
<!-- Alphabets Sort -->
<ul class="sort">
<?php
echo '<li ><a href="index.php" ';
if( !isset($_GET['char']) ){
echo ' class="active" ';
}
echo ' >All</a></li>';
// Select Alphabets and total records
$alpha_sql = "select DISTINCT LEFT(name , 1) as firstCharacter,
( select count(*) from users where LEFT(name , 1)= firstCharacter ) AS counter
from users
order by name asc";
$result_alpha = mysqli_query($con,$alpha_sql);
while($row_alpha = mysqli_fetch_array($result_alpha) ){
$firstCharacter = $row_alpha['firstCharacter'];
$counter = $row_alpha['counter'];
echo '<li ><a href="?char='.$firstCharacter.'" ';
if( isset($_GET['char']) && $firstCharacter == $_GET['char'] ){
echo ' class="active" ';
}
echo ' >'.$firstCharacter.' ('.$counter.')</a></li>';
}
?>
</ul><br><br>
<table width="100%" id="userstable" border="1" >
<tr class="tr_header">
<th>S.no</th>
<th>Username</th>
<th>Name</th>
<th>Email</th>
</tr>
<?php
// selecting rows
$sql = "SELECT * FROM users where 1";
if( isset($_GET['char']) ){
$sql .= " and LEFT(name,1)='".$_GET['char']."' ";
}
$sql .=" ORDER BY name ASC";
$result = mysqli_query($con,$sql);
$sno = 1;
while($fetch = mysqli_fetch_array($result)){
$name = $fetch['name'];
$username = $fetch['username'];
$email = $fetch['email'];
?>
<tr>
<td align='center'><?php echo $sno; ?></td>
<td align='center'><?php echo $username; ?></td>
<td align='center'><?php echo $name; ?></td>
<td align='center'><?php echo $email; ?></td>
</tr>
<?php
$sno ++;
}
?>
</table>
</div>
#userstable{
border-collapse: collapse;
max-width: 800px;
}
/* Numeric */
.sort{
list-style: none;
}
.sort li{
float: left;
border: 1px solid #000;
padding: 5px 7px;
margin-right: 10px;
border-radius: 3px;
}
.sort li a{
text-decoration: none;
color:black;
}
.active{
color: red !important;
}
users table.CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `password` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<?php
session_start();
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
<div class="container"> <form method="post" action=""> <div id="div_login"> <h1>Login</h1> <div> <input type="text" class="textbox" name="txt_uname" placeholder="Username" /> </div> <div> <input type="password" class="textbox" name="txt_pwd" placeholder="Password"/> </div> <div> <input type="checkbox" name="rememberme" value="1" /> Remember Me </div> <div> <input type="submit" value="Submit" name="but_submit" /> </div> </div> </form> </div>
$_SESSION['userid'] when the entered username and password matched in MySQL database table and initialize $_COOKIE['rememberme'] when Remember me checkbox is being checked.$_COOKIE I encrypt it for this I created encryptCookie() function and set its expire time to 30 days.$_SESSION and $_COOKIE variable when the user next time come to the login page.$_SESSION variable is set or not if set then redirect the user to home.php.$_SESSION is not set then check $_COOKIE variable.decryptCookie() function and check the return value in MySQL database table. If value found then redirect to home.php.include "config.php";
// Check if $_SESSION or $_COOKIE already set
if( isset($_SESSION['userid']) ){
header('Location: home.php');
exit;
}else if( isset($_COOKIE['rememberme'] )){
// Decrypt cookie variable value
$userid = decryptCookie($_COOKIE['rememberme']);
$sql_query = "select count(*) as cntUser,id from users where id='".$userid."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
$count = $row['cntUser'];
if( $count > 0 ){
$_SESSION['userid'] = $userid;
header('Location: home.php');
exit;
}
}
// Encrypt cookie
function encryptCookie( $value ) {
$key = 'youkey';
$newvalue = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $key ), $value, MCRYPT_MODE_CBC, md5( md5( $key ) ) ) );
return( $newvalue );
}
// Decrypt cookie
function decryptCookie( $value ) {
$key = 'youkey';
$newvalue = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $key ), base64_decode( $value ), MCRYPT_MODE_CBC, md5( md5( $key ) ) ), "\0");
return( $newvalue );
}
// On submit
if(isset($_POST['but_submit'])){
$uname = mysqli_real_escape_string($con,$_POST['txt_uname']);
$password = mysqli_real_escape_string($con,$_POST['txt_pwd']);
if ($uname != "" && $password != ""){
$sql_query = "select count(*) as cntUser,id from users where username='".$uname."' and password='".$password."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
$count = $row['cntUser'];
if($count > 0){
$userid = $row['id'];
if( isset($_POST['rememberme']) ){
// Set cookie variables
$days = 30;
$value = encryptCookie($userid);
setcookie ("rememberme",$value,time()+ ($days * 24 * 60 * 60 * 1000));
}
$_SESSION['userid'] = $userid;
header('Location: home.php');
exit;
}else{
echo "Invalid username and password";
}
}
}
$_SESSION and $_COOKIE variable when it gets button gets clicked.<?php
include "config.php";
// Check user login or not
if(!isset($_SESSION['userid'])){
header('Location: index.php');
}
// logout
if(isset($_POST['but_logout'])){
session_destroy();
// Remove cookie variables
$days = 30;
setcookie ("rememberme","", time() - ($days * 24 * 60 * 60 * 1000));
header('Location: index.php');
}
?>
<h1>Homepage</h1>
<form method='post' action="">
<input type="submit" value="Logout" name="but_logout">
</form>
userid before storing it in a $_COOKIE and you can replace the key with your key which should be long enough so anyone couldn’t guess.images table for storing data.CREATE TABLE `images` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(200) NOT NULL, `image` longtext NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
config.php file.<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
<?php
include("config.php");
if(isset($_POST['but_upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
$query = "insert into images(name) values('".$name."')";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit' value='Save name' name='but_upload'>
</form>
<?php $sql = "select name from images where id=1"; $result = mysqli_query($con,$sql); $row = mysqli_fetch_array($result); $image = $row['name']; $image_src = "upload/".$image; ?> <img src='<?php echo $image_src; ?>'
base64_encode() method is been used for base64 conversion. Before storing it in the database I append data:image/'.$imageFileType.';base64, text with base64 value.Note – In the example, I upload the image to directory. You can remove the upload code if you only want the image will accessible through base64 stored values in the database.Completed Code
<?php
include("config.php");
if(isset($_POST['but_upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Convert to base64
$image_base64 = base64_encode(file_get_contents($_FILES['file']['tmp_name']) );
$image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
// Insert record
$query = "insert into images(image) values('".$image."')";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit' value='Save name' name='but_upload'>
</form>
<?php $sql = "select image from images where id=1"; $result = mysqli_query($con,$sql); $row = mysqli_fetch_array($result); $image_src2 = $row['image']; ?> <img src='<?php echo $image_src; ?>' >
$http service is use to send AJAX request.users table in the tutorial example.CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `fname` varchar(80) NOT NULL, `lname` varchar(80) NOT NULL, `username` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
config.php file.<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
angular.min.js in the page or use CDN.<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js'></script>
<body ng-app='myapp'> and <div ng-controller='userCtrl'> on the page.<table> layout and specify ng-repeat directive on a row. Which loop through all available data in users Array. <!doctype html>
<html>
<head>
<title>How to get data from MySQL with AngularJS - PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
</head>
<body ng-app='myapp'>
<div ng-controller="userCtrl">
<table >
<tr>
<th>First name</th>
<th>Last name</th>
<th>Username</th>
</tr>
<!-- Display records -->
<tr ng-repeat="user in users">
<td>{{user.fname}}</td>
<td>{{user.lname}}</td>
<td>{{user.username}}</td>
</tr>
</table>
</div>
</body>
</html>
getData.php file.include 'config.php';
$sel = mysqli_query($con,"select * from users");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$data[] = array("fname"=>$row['fname'],"lname"=>$row['lname'],"username"=>$row['username']);
}
echo json_encode($data);
getData.php in url and set method to get.then where store reponse.data to $scope.users.ng-repeat directive.<script>
var fetch = angular.module('myapp', []);
fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'get',
url: 'getData.php'
}).then(function successCallback(response) {
// Store response data
$scope.users = response.data;
});
}]);
</script>
$http service which helps to make an AJAX call to the server.$http to fetch data from MySQL database in JSON format.extractTo() method is used to extract the zip file that takes destination absolute path as argument.ZipArchive class and open given zip file using $zip->open() method.TRUE then extract the file to the specified path ($path) with extractTo() method by passing path value as an argument in it.
Here, I am extracting the file in project files directory.
Completed Code// Get Project path
define('_PATH', dirname(__FILE__));
// Zip file name
$filename = 'zipfile.zip';
$zip = new ZipArchive;
$res = $zip->open($filename);
if ($res === TRUE) {
// Unzip path
$path = _PATH."/files/";
// Extract file
$zip->extractTo($path);
$zip->close();
echo 'Unzip!';
} else {
echo 'failed!';
}
$_FILES['file']['tmp_name'] to open() method and extract it to specified path using extractTo() method.<?php
// Get Project path
define('_PATH', dirname(__FILE__));
// Unzip selected zip file
if(isset($_POST['unzip'])){
$filename = $_FILES['file']['name'];
// Get file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$valid_ext = array('zip');
// Check extension
if(in_array(strtolower($ext),$valid_ext)){
$tmp_name = $_FILES['file']['tmp_name'];
$zip = new ZipArchive;
$res = $zip->open($tmp_name);
if ($res === TRUE) {
// Unzip path
$path = _PATH."/files/";
// Extract file
$zip->extractTo($path);
$zip->close();
echo 'Unzip!';
} else {
echo 'failed!';
}
}else{
echo 'Invalid file';
}
}
?>
<form method='post' action='' enctype='multipart/form-data'>
<!-- Unzip selected zip file -->
<input type='file' name='file'><br/>
<input type='submit' name='unzip' value='Unzip' />
</form>
ZipArchive Class.<p> for display response result.ng-click directive which calls upload() function.<body ng-app='myapp'>
<div ng-controller="userCtrl">
<input type='file' name='file' id='file'><br/>
<input type='button' value='Upload' id='upload' ng-click='upload()' >
<p>{{ response.name }}</p>
</div>
</body>
$scope.upload in the controller which triggers the button click.FormData object variable fd.$http service where pass FormData object as data and set Content-Type: undefined using headers property. var upload= angular.module('myapp', []);
upload.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.upload = function(){
var fd = new FormData();
var files = document.getElementById('file').files[0];
fd.append('file',files);
// AJAX request
$http({
method: 'post',
url: 'upload.php',
data: fd,
headers: {'Content-Type': undefined},
}).then(function successCallback(response) {
// Store response data
$scope.response = response.data;
});
}
}]);
ng-file='uploadfiles' on the input element and other codes will be the same as the above example. <body ng-app='myapp'>
<div ng-controller="userCtrl">
<input type='file' name='file' id='file' ng-file='uploadfiles'><br/>
<input type='button' value='Upload' id='upload' ng-click='upload()' >
<p>{{ response.name }}</p>
</div>
</body>
.directive where initializing the scope when the change event trigger and use it to define FormData Object variable fd.var upload = angular.module('myapp', []);
upload.directive('ngFile', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('change', function(){
$parse(attrs.ngFile).assign(scope,element[0].files)
scope.$apply();
});
}
};
}]);
upload.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.upload = function(value){
var fd=new FormData();
angular.forEach($scope.uploadfiles,function(file){
fd.append('file',file);
});
$http({
method: 'post',
url: 'upload.php',
data: fd,
headers: {'Content-Type': undefined},
}).then(function successCallback(response) {
// Store response data
$scope.response = response.data;
});
}
}]);
upload.php file and an upload directory.upload directory and return an Array in JSON format which has a file name.<?php
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = 'upload/';
/* Upload file */
move_uploaded_file($_FILES['file']['tmp_name'],$location.$filename);
$arr = array("name"=>$filename);
echo json_encode($arr);
FormData initializing step is different. You can use any of them to upload file to the server with Angular.