Category: PHP

Create simple pagination using PHP and MySQLi

In your website page when we want to show data list then maximum time we need pagination for better understand. We can do that using php and mysqli. For this case just follow this instruction. First we need to create a table so first create database name “pagination” then run this sql in your phpmyadmin.


CREATE TABLE `user` (
  `userid` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `username` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `user` (`userid`, `firstname`, `lastname`, `username`) VALUES
(1, 'First1', 'Last1', 'test1'),
(2, 'First2', 'Last2', 'test2'),
(3, 'First3', 'Last3', 'test3'),
(4, 'First4', 'Last4', 'test4'),
(5, 'First5', 'Last5', 'test5'),
(6, 'First6', 'Last6', 'test6'),
(7, 'First7', 'Last7', 'test7'),
(8, 'First8', 'Last8', 'test8'),
(9, 'First9', 'Last9', 'test9'),
(10, 'First10', 'Last10', 'test10'),
(11, 'First11', 'Last11', 'test11'),
(12, 'First12', 'Last12', 'test12'),
(13, 'First13', 'Last13', 'test13'),
(14, 'First14', 'Last14', 'test14');


ALTER TABLE `user`
  ADD PRIMARY KEY (`userid`);


ALTER TABLE `user`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;


I just add some demo data for list . Then create a database connection file name “db.php“. Add this code in db.php

<?php

$conn = mysqli_connect("localhost","root","","pagination");
if (!$conn) {
 die("Connection failed: " . mysqli_connect_error());
}
 
?>

then create main page index.php which page show content

<?php include('pagination.php'); ?>
<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" href="http://techparkbd.com/subdomain/source_file/bootstrap.min.css" />
	<script src="http://techparkbd.com/subdomain/source_file/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
	<div style="height: 20px;"></div>
	<div class="row">
	<div class="col-lg-2">
	</div>
	<div class="col-lg-8">
	<table width="80%" class="table table-striped table-bordered table-hover">
		<thead>
			<th>UserID</th>
			<th>Firstname</th>
			<th>Lastname</th>
			<th>Username</th>
		</thead>
		<tbody>
		<?php
			while($crow = mysqli_fetch_array($nquery)){
			?>
				<tr>
					<td><?php echo $crow['userid']; ?></td>
					<td><?php echo $crow['firstname']; ?></td>
					<td><?php echo $crow['lastname']; ?></td>
					<td><?php echo $crow['username']; ?></td>
				</tr>
			<?php
			}		
		?>
		</tbody>
	</table>
	<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
	</div>
	<div class="col-lg-2">
	</div>
	</div>
</div>
</body>
</html>

then this is pagination page which manage pagination list .

<?php

	include("db.php");
	
	$query=mysqli_query($conn,"select count(userid) from `user`");
	$row = mysqli_fetch_row($query);

	$rows = $row[0];
	
	$page_rows = 5; // change how many row show every page

	$last = ceil($rows/$page_rows);

	if($last < 1){
		$last = 1;
	}

	$pagenum = 1;

	if(isset($_GET['pn'])){
		$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
	}

	if ($pagenum < 1) { 
		$pagenum = 1; 
	} 
	else if ($pagenum > $last) { 
		$pagenum = $last; 
	}

	$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
	
	$nquery=mysqli_query($conn,"select * from `user` $limit");

	$paginationCtrls = '';

	if($last != 1){
		
	if ($pagenum > 1) {
        $previous = $pagenum - 1;
		$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$previous.'" class="btn btn-default">Pre</a> &nbsp; &nbsp; ';
		
		for($i = $pagenum-4; $i < $pagenum; $i++){
			if($i > 0){
		        $paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'" class="btn btn-default">'.$i.'</a> &nbsp; ';
			}
	    }
    }
	
	$paginationCtrls .= ''.$pagenum.' &nbsp; ';
	
	for($i = $pagenum+1; $i <= $last; $i++){
		$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'" class="btn btn-default">'.$i.'</a> &nbsp; ';
		if($i >= $pagenum+4){
			break;
		}
	}

    if ($pagenum != $last) {
        $next = $pagenum + 1;
        $paginationCtrls .= ' &nbsp; &nbsp; <a href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'" class="btn btn-default">Next</a> ';
    }
	}

?>

then browse your index.php page then you will show list using pagination. This is simple demo content

If you face any problem then please inform me. I will try to help you.

Credit : https://www.sourcecodester.com/

Comment

How to update session variable from dropdown change?

If you want to update your value like when drop down change then this value will set in php session in this case you can use ajax which help you lot. This is simple code which update session value when change drop down change .

This is total html and php code which need to update and browse data

<?php
session_start(); // for show your session value 
print_r($_SESSION); // remove this after check
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form name="myForm" action="/thanks" method="POST">

    <table>
        <tr>
            <td style="width:272px;">
                <select name="select_amount" id="select_amount" onchange="update_session_value(this.value)">
                    <option value="0">select a listing type</option>
                    <option value="10">Premium Listings</option>
                    <option value="20">Premium Blogs</option>
                    <option value="30">1 week sticky</option>
                </select></td>

            <td style="text-align:left;color:gray;">
                <span style="color:crimson;">*
            </span>Select a listing type
            </td>
        </tr>
    </table>
    <input type="submit" name="submit" class="button_add" onsubmit="return validateForm()">

</form>

<script>
    function update_session_value(value) {
        $.ajax({
            type: "POST",
            url: 'http://localhost/session.php', // change url as your 
            data: 'select_amount=' + value,
            dataType: 'json',
            success: function (data) {

            }
        });
    }

</script>

Then create php file which update session value

<?php
session_start();
if( isset($_POST['select_amount']) ) {
    // save values from other page to session
    $_SESSION['amount'] = $_POST['select_amount'];

}
?>

For test you can refresh the page and check output or ajax function update this code

<script>
    function update_session_value(value) {
        $.ajax({
            type: "POST",
            url: 'http://localhost/session.php', // change url as your 
            data: 'select_amount=' + value,
            dataType: 'json',
            success: function (data) {
 window.location.reload;
            }
        });
    }

</script>

if you face any problem then please inform me, I will try to help you

Comment

How to read child elements of XML using php?

If you want to get child elements from xml using php then you can use this code which help you to get child elements and some other options. This is simple demo code which help you. In this code first get child elements data then also child of child data. Just parse data using php simplexml_load_string function.

<?php
$string = <<<XML
<ORDERSTATUS>
    <DATE>23/01/18</DATE>
    <INVOICE>Test Data</INVOICE>
    <INVTOTAL Tax="25.00" Freight="28" SubTotal="80.00">100.0</INVTOTAL>
</ORDERSTATUS>
XML;

$xml = simplexml_load_string($string);

echo "DATE:".$xml->DATE."<br>";
echo "INVOICE:".$xml->INVOICE ."<br>";
echo "INVTOTAL:".$xml->INVTOTAL ."<br>";
echo  "Tax:".$xml->INVTOTAL->attributes()->Tax."<br>";
echo  "Freight:".$xml->INVTOTAL->attributes()->Freight."<br>";
echo  "SubTotal:".$xml->INVTOTAL->attributes()->SubTotal."<br>";

this code give you first child elements then also child of child elements . This is output this code

DATE:23/01/18
INVOICE:Test Data
INVTOTAL:100.0
Tax:25.00
Freight:28
SubTotal:80.00

If you face any problem then please inform me. I will try to help you.

Comment

How to rotate image and save new image using PHP ?

If you want to rotate image then save rotate image then you can use this simple php code.

<?php
$image = 'test.jpg';
 
// The file you are rotating
 
//How many degrees you wish to rotate
$degrees = 180;
 
// This sets the image type to .jpg but can be changed to png or gif
header('Content-type: image/jpeg') ;
 
// Create the canvas
$src = $image;
$system = explode(".", $src);
 
if (preg_match("/jpg|jpeg/", $system[1]))
{
$src_img=imagecreatefromjpeg($src);
}
if (preg_match("/png/", $system[1]))
{
$src_img = imagecreatefrompng($src);
}
if (preg_match("/gif/", $system[1]))
{
$src_img = imagecreatefromgif($src);
}
 
// Rotates the image
$rotate = imagerotate($src_img, $degrees, 0) ;
 
// Outputs a jpg image, you could change this to gif or png if needed
if (preg_match("/png/", $system[1]))
{
imagepng($rotate,$image);
}
else if (preg_match("/gif/", $system[1]))
{
imagegif($rotate, $image);
}
else
{
imagejpeg($rotate, $image);
}
 
imagedestroy($rotate);
imagedestroy($src_img);
 
?>

If you face any problem then please inform me. I will try to help you.

Comment

How to get content which div first class name using php preg_match function?

Suppose you want to get content using preg_match function for specific div class name or id. This is HTML

<div class="calss1 class2 class3">
    Content 1
</div>
<div class="class1 class2 class3">
    Content 2
</div>
<div class="class1 class2 class3">
    Content 3
</div>
<div class="class1 class2 class3">
    Content 4
</div>
<div class="class1 class2 class3">
    Content 5
</div>

then you want to get content using specific class name , not all class name like class name class1

then you can use this code which get all content which class name first class1

 if (preg_match('/<div class="class1(\s.*?)?">(.*?)<\/div>/is', $my_content, $result)) {
            print_r($result);
        }

This will get all result which you want, if you face any problem then please inform me.

View 2 Comments

how to convert multidimensional array to single array using php?

For convert multidimensional array to single array then this is php code which help you lot . just follow this code

<?php
$your_array = array(0 => array('payment_id' => 3160), 1 => array('action' => 'update'), 2 => array('date' => '2017-05-17 09:59:40'), 3 => array('payment_date' => '23.05.201'));
echo "<pre>";
print_r($your_array);
$convert_array = array_reduce($your_array, 'array_merge', array());
echo "<pre>";
print_r($convert_array);

if you run this code then you will see this output like this :

Input array :

Array
(
    [0] => Array
        (
            [payment_id] => 3160
        )
 
    [1] => Array
        (
            [action] => update
        )
 
    [2] => Array
        (
            [date] => 2017-05-17 09:59:40
        )
 
    [3] => Array
        (
            [payment_date] => 23.05.201
        )
 
)

then output is :

Array
(
    [payment_id] => 3160
    [action] => update
    [date] => 2017-05-17 09:59:40
    [payment_date] => 23.05.201
)

if you face any problem then inform me, i will try to help you.

Comment

get ip from domain name using php

If you need to know ip address from domain name then you can use php which is very simple. You can use gethostbyname. gethostbyname — Get the IPv4 address corresponding to a given Internet host name . This is simple code


<?php
$ip = gethostbyname('https://techparkbd.com/');

echo $ip;
?>

Then Output is :

184.107.37.81 

If you find any problem then please inform me. I will try to help you.

Comment

Get information from the web server automatically

Server-sent events is a technology for where a browser gets automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5[1] by the W3C.

Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established. They are commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream. First create a simple html page which call php file and get result from this file

<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>

<script>
    if(typeof(EventSource)!=="undefined")
    {
        var source=new EventSource("http://localhost/result.php");
        source.onmessage=function(event)
        {
            document.getElementById("result").innerHTML+=event.data + "<br>";
        };
    }
    else
    {
        document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
    }
</script>

</body>
</html>

then create result.php

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

Then you can see the result, without page refresh time will update

This is simple demo result

If you face any problem then please inform me. I will try to help you.

Comment

How to checked checkbox is checked or not using PHP?

If you want to check that which checkbox checked and which not checked using php . Then you can check this simple code which give you this option.

<?php
if(isset($_POST['submit']))
{
  if(isset($_POST['submit']))
    {
       // $x = cout($_POST['checkbox']);
        for($x = 0;$x <= 4;$x++)
        {
            if(strlen($_POST['checkbox'][$x])>1)
            {
                echo "Checkbox is cheked<br>";
            }
            else{
                echo "Checkbox not checked<br>";
            }
        }
    }
 
 
}
 
 
?>

This is html code

<html>
<head>
 
</head>
<body>
<form enctype="multipart/form-data" action="" method="POST">
    <div id="text">
        <input type="checkbox" name="checkbox[0]"  />Checkbox1<br>
        <input type="checkbox" name="checkbox[1]"  />Checkbox2<br>
        <input type="checkbox" name="checkbox[2]"  />Checkbox3<br>
        <input type="checkbox" name="checkbox[3]"  />Checkbox4<br>
        <input type="checkbox" name="checkbox[4]"  />Checkbox5<br>
 
    </div>
    <input type="submit" value="Submit" name="submit" id="submit" />
</form>
</body>
</html>

Hope it will help you. If you find any problem then please inform me. i will try to help you

Comment

Sending data using Ajax to PHP

When you need to send data to server side then you can use Ajax to send data. This is simple code which help you.


<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>PHP, jQuery search demo</title>
    <link rel="stylesheet" type="text/css" href="my.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("input").keyup(function () {
                $('#results').html('');
                var searchString = $("#search_box").val();
                var data = 'search_text=' + searchString;
                if (searchString) {
                    $.ajax({
                        type: "POST",
                        url: 'http://localhost/search.php',
                        data: data,
                        dataType: 'text',
                        async: false,
                        cache: false,
                        success: function (result) {
                            $('#results').html(result);
                            //window.location.reload();

                        }
                    });
                }
            });
        });
    </script>

</head>
<body>
<div id="container">
    <div style="margin:20px auto; text-align: center;">
        <form method="post" action="do_search.php">
            <input type="text" name="search" id="search_box" class='search_box'/>
            <input type="submit" value="Search" class="search_button"/><br/>
        </form>
    </div>
    <div>

        <div id="searchresults">Search results :</div>
        <ul id="results" class="update">
        </ul>

    </div>
</div>

</body>
</html>

then create a search.php file which process ajax request value. you can also select data from database using this ajax data, also set this data to session etc.

This is search.php file

<?php 

$searchquery = $_POST['search_text']; 
echo $searchquery;
?>

if you face any problem then please inform me.

Comment