Showing posts with label MySql. Show all posts
Showing posts with label MySql. Show all posts

Tuesday, March 17

Simple PHP MYSQL Pagination





1. Database Connection:
    Create connection.php file and put that php code (provided below) in it.

<?php
    $db_username = 'root'; // Your MYSQL Username.
    $db_password = ''; // Your MYSQL Password.
    $db_name = 'database_name_here'; // Your Database name.
    $db_host = 'localhost';
     
    $conDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('Error: Could not connect to database.');
?>


2. Pagination function:
    Let’s create pagination function and store it in your functions.php file.
   
<?php
    function pagination($query,$per_page=10,$page=1,$url='?'){ 
        global $conDB;
        $query = "SELECT COUNT(*) as `num` FROM {$query}";
        $row = mysqli_fetch_array(mysqli_query($conDB,$query));
        $total = $row['num'];
        $adjacents = "2";
         
        $prevlabel = "&lsaquo; Prev";
        $nextlabel = "Next &rsaquo;";
        $lastlabel = "Last &rsaquo;&rsaquo;";
         
        $page = ($page == 0 ? 1 : $page);
        $start = ($page - 1) * $per_page;                             
         
        $prev = $page - 1;                        
        $next = $page + 1;
         
        $lastpage = ceil($total/$per_page);
         
        $lpm1 = $lastpage - 1; // //last page minus 1
         
        $pagination = "";
        if($lastpage > 1){ 
            $pagination .= "<ul class='pagination'>";
            $pagination .= "<li class='page_info'>Page {$page} of {$lastpage}</li>";
                 
                if ($page > 1) $pagination.= "<li><a href='{$url}page={$prev}'>{$prevlabel}</a></li>";
                 
            if ($lastpage < 7 + ($adjacents * 2)){ 
                for ($counter = 1; $counter <= $lastpage; $counter++){
                    if ($counter == $page)
                        $pagination.= "<li><a class='current'>{$counter}</a></li>";
                    else
                        $pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";                  
                }
             
            } elseif($lastpage > 5 + ($adjacents * 2)){
                 
                if($page < 1 + ($adjacents * 2)) {
                     
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++){
                        if ($counter == $page)
                            $pagination.= "<li><a class='current'>{$counter}</a></li>";
                        else
                            $pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";                  
                    }
                    $pagination.= "<li class='dot'>...</li>";
                    $pagination.= "<li><a href='{$url}page={$lpm1}'>{$lpm1}</a></li>";
                    $pagination.= "<li><a href='{$url}page={$lastpage}'>{$lastpage}</a></li>";
                         
                } elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
                     
                    $pagination.= "<li><a href='{$url}page=1'>1</a></li>";
                    $pagination.= "<li><a href='{$url}page=2'>2</a></li>";
                    $pagination.= "<li class='dot'>...</li>";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) {
                        if ($counter == $page)
                            $pagination.= "<li><a class='current'>{$counter}</a></li>";
                        else
                            $pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";                  
                    }
                    $pagination.= "<li class='dot'>..</li>";
                    $pagination.= "<li><a href='{$url}page={$lpm1}'>{$lpm1}</a></li>";
                    $pagination.= "<li><a href='{$url}page={$lastpage}'>{$lastpage}</a></li>";    
                     
                } else {
                     
                    $pagination.= "<li><a href='{$url}page=1'>1</a></li>";
                    $pagination.= "<li><a href='{$url}page=2'>2</a></li>";
                    $pagination.= "<li class='dot'>..</li>";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
                        if ($counter == $page)
                            $pagination.= "<li><a class='current'>{$counter}</a></li>";
                        else
                            $pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";                  
                    }
                }
            }
             
                if ($page < $counter - 1) {
                    $pagination.= "<li><a href='{$url}page={$next}'>{$nextlabel}</a></li>";
                    $pagination.= "<li><a href='{$url}page=$lastpage'>{$lastlabel}</a></li>";
                }
             
            $pagination.= "</ul>";      
        }
         
        return $pagination;
    }
?>  


3. Displaying Database Records with pagination:

<?php
    include_once('connection.php');
    include_once('functions.php');
    
    $page = (int)(!isset($_GET["page"]) ? 1 : $_GET["page"]);
    if ($page <= 0) $page = 1;
    
    $per_page = 10; // Set how many records do you want to display per page.
    
    $startpoint = ($page * $per_page) - $per_page;
    
    $statement = "`records` ORDER BY `id` ASC"; // Change `records` according to your table name.
     
    $results = mysqli_query($conDB,"SELECT * FROM {$statement} LIMIT {$startpoint} , {$per_page}");
    
    if (mysqli_num_rows($results) != 0) {
        
        // displaying records.
        while ($row = mysqli_fetch_array($results)) {
            echo $row['name'] . '<br>';
        }
     
    } else {
         echo "No records are found.";
    }
    
     // displaying paginaiton.
    echo pagination($statement,$per_page,$page,$url='?');
?>


4. Simple CSS:
   
<style>
    ul.pagination { text-align:center; color:#829994; }
   
    ul.pagination li { display:inline; padding:0 3px; }
   
    ul.pagination a { color:#0d7963; display:inline-block; padding:5px 10px; border:1px solid #cde0dc; text-decoration:none; }
   
    ul.pagination a:hover,
    ul.pagination a.current { background:#0d7963; color:#fff;     }
</style>


Tuesday, January 27

mySql using Prepared Statement with php

test.html

    <form action="test.php" method="POST">
        <input name="test" type="text">
        <input name="submit" type="submit" value="Submit">
    </form>
 
test.php

<?php
    if (isset($_POST['submit'])) {
    
    $mysqli = new mysqli('localhost', 'user', 'password', 'mytestdb');
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    
    $stmt = $mysqli->prepare("INSERT INTO table_name VALUES (?)");
    $stmt->bind_param('s', $test);   // bind $test to the parameter
    
    // escape the POST data for added protection
    $test = isset($_POST['test']) ? $mysqli->real_escape_string($_POST['test']) : '';
    
    /* execute prepared statement */
    $stmt->execute();
    
    printf("%d Row inserted.\n", $stmt->affected_rows);
    
    /* close statement and connection */
    $stmt->close();
    
    /* close connection */
    $mysqli->close();
    }
?>

real_escape_string() is superfluous. The whole point of using prepared statements is to avoid having to escape the values manually.

Prevent SQL-injection in PHP

The SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

1. prepared statements (PDO):

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

2. parameterized queries (MySQLi):

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are thrown as PDOExceptions.

What is mandatory however is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

What happens is that the SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.

Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Oh, and since you asked about how to do it for an insert, here's an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array('column' => $unsafeValue));


Source: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1

MySql Database Connectivity with Reduced Number of Hits

Try to reduce the number of hits to the database. Make queries aggregate so that you call the database less number of times.
For example:

<?php
  $connection=mysqli_connect("localhost","username","password","db_name");
  
  if (mysqli_connect_errno())
  {
    echo "Failed to connect to MySQL" ;
mysqli_connect_error(); 
  }

  function insertValue( $val ){
    mysqli_query($connection,"INSERT INTO table_name (integerValue) VALUES ( $value )");
  }
  
  for( $i =0; $i<99; $i++){
    //  Calling function to execute query one by one 
    insertValue( $i );
  }
  // Closing the connection as best practice
  mysqli_close($connection);

?>

The script above is much slower.
So, script below is the best solution to run fast:

<?php
  $connection=mysqli_connect("localhost","username","password","db_name");
  if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL" ;
  mysqli_connect_error(); 
  }
   
  function insertValues( $val ){
     // Creating query for inserting complete array in single execution.
    $query= " INSERT INTO table_name(integerValue) VALUES .implode(',', $value)";      
    mysqli_query($connection, $query);
  }
  
  $data_array = array();
  for( $i =0; $i<99; $i++){
    // Creating an array of data to be inserted.
    $data_array[ ]  =   '(" ' . $i. '")' ;
  }
  // Inserting the data in a single call
  insertValues( $data_array );
  // Closing the connection as a best practice
  mysqli_close($connection);

?>