Inserting session array into mysql database

I am still learning bits of PHP and have been stuck on this issue regarding the POST data from radio buttons within a form being inserted into a mysql database from a session array. Currently, I have 2 questions within my survey and they consist of radio button options for a user to select from. The relevant answers can be selected and they are stored in a session array:

I am still learning bits of PHP and have been stuck on this issue regarding the POST data from radio buttons within a form being inserted into a mysql database from a session array. Currently, I have 2 questions within my survey and they consist of radio button options for a user to select from. The relevant answers can be selected and they are stored in a session array:

array(1) { ["choice"]=> array(2) { [0]=> string(11) "56-65 years" [1]=> string(17) "Prefer not to say" } }

However I was not too sure if the array should be as such. The two answers chosen from the radio options in the above example are "56-65 years" and "Prefer not to say".

Following on from the session array, I am trying to insert each of those answers in to a mysql database. I have a column created to insert each answer (i.e. there are two columns (question 1 and question 2) to store the two answers from the example above).

I am aware that my code is open to SQL injection and plan on fixing that after overcoming the inserting of data.

Question.php

     <form method="POST" action="process.php">
      <ul class="choices">
  &lt;?php while($row = $answers-&gt;fetch_assoc()):?&gt;
    &lt;li&gt;&lt;input type="radio" name="choice" value="&lt;?php echo $row['answerText']; ?&gt;"&gt;

    &lt;?php echo $row['answerText'] ?&gt;&lt;/li&gt;
    &lt;?php endWhile; ?&gt;

  &lt;/ul&gt; 
  &lt;input type="submit" name="submit" value="Next Question"&gt;
  &lt;input type="hidden" name="number" value="&lt;?php echo $number; ?&gt;"&gt;

</form>

Process.php

<?php

    if(isset($_POST['submit'])){

$number = $_POST['number'];
$next = $number+1;

$selected_choice = $_POST['choice'];
$_SESSION['choice'][] = $selected_choice;

foreach ($_SESSION['choice'] as $key) {

$user_responses = $key;

}

$insertdata = "INSERT INTO userAnswersTable('question1', 'question2') VALUES ($_SESSION['choice'])";
$resulting = $mysqli->query($insertdata) or die($mysqli->error.LINE);

}
?>

I would expect each of the user responses to be in an array from which each individual selected choice within the session array can be stored in each corresponding column within the mySql table. Any suggestions would be very helpful.

PHP / MySQL - Count how many table in database contain Specific name

I'm building an admin to control an interactive game, and I'm using PHP/MySql to store all the data for all the rounds. Each of the tables that I want to load into the game via PHP are titled "Puzzle*" with the * being an incremental index number. There are a few other tables in my database for global game data and bonus rounds.

I'm building an admin to control an interactive game, and I'm using PHP/MySql to store all the data for all the rounds. Each of the tables that I want to load into the game via PHP are titled "Puzzle*" with the * being an incremental index number. There are a few other tables in my database for global game data and bonus rounds.

What I want to be able to do is count the number of tables in my database that contain the name "Puzzle", and then use that total number as a randomizer to select a puzzle randomly. I plan to have roughly 50 puzzles, so an automated way of selecting a random puzzle, and then if I want to select another puzzle - to remove that previous puzzle from the list so that there is no chance of it being repeated until I start the whole game over again.

MySQL Database

Database Name: puzzleGame
Table 1: puzzle1
Table 2: puzzle2
Table 3: puzzle3
Table 4: puzzle4
Table 5: globals
Table 6: bonus


Flexible PHP 7- MySQLi database class (+ download)

Flexible PHP 7- MySQLi database class (+ download)

We all know it: Write annoying code over and over again! That’s over now. With this PHP MySQLi database class you can easily connect to your MySQL database.

This class is very simple and flexible for any project. It also ensures that no SQL-Injectionattacks can be carried out. You may use the class below freely for your projects (also commercially) and of course extend it as you like. And so you use it:

1. Include class in your project structure

You copy the complete class and create a new file in your project structure, e.g. Database.php and paste the complete code there.

<?php
/**
* Simple Database class for PHP7+
* The class contains main functions for your database. For a detailed documentation, see: https://webdeasy.com/
* created 08.11.2017
* 
* @author LH
*/
class Database {
  private $host, $database, $username, $password, $connection;
  private $port = 3306;

/**
*

  • Sets the connection credentials to connection to your database
  • @param string $host - the host of your database
  • @param string $username - the username of your database
  • @param string $password - the password of your database
  • @param string $database - your database name
  • @param integer $port - the port of your database
  • @param boolean $autoconnect - to auto connect to the database after settings connection credentials
    /
    function __construct($host, $username, $password, $database, $port = 3306, $autoconnect = true) {
    $this->host = $host;
    $this->database = $database;
    $this->username = $username;
    $this->password = $password;
    $this->port = $port;
    if($autoconnect) {
    $this->open();
    }
    }
    /
    *
  • Open the connection to your database
    /
    function open() {
    $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database, $this->port);
    }
    /
    *
  • Close the connection to your database
    /
    function close() {
    $this->connection->close();
    }
    /
    *
  • Execute your query
  • @param string $query - your sql query
  • @return the result of the executed query
    /
    function query($query) {
    return $this->connection->query($query);
    }
    /
    *
  • Escape your parameter
  • @param string $string - your parameter to escape
  • @return the escaped string
    */
    function escape($string) {
    return $this->connection->escape_string($query);
    }
    }
    ?>
2. Include database class

Your program code runs in a different PHP file. There you add the following code to include the class:

require_once("path/to/your/file/Database.php");

What’s the different between require and includeThis!

3. Create instance

To connect to the database, we need to create an instance of the class. For this we need the access data to the database. You can find the optional parameters of the construct in the class. A call could look like this:

$database = new Database("localhost", "testuser", "verySafePassword", "ourDatabase");

An attempt is made to establish a connection to the database with the access data transferred. This happens automatically if the $autoconnect parameter is set to true (see line 26).

If you don’t get any errors, the connection to the database is established successfully. Now you can formulate your SQL queries.

4. Escape parameters!

That’s probably the most important step. To prevent SQL injections, every parameter you use in the query must be escaped. This can prevent harmful SQL statements – whether intentional or unintentional – from getting into your query and thus into your server system. The following lines must be inserted before each query:

$parameter = $_POST["id"];
$parameter = $db->escape($parameter);

In this example, the id parameter of the POST request is passed to PHP and escaped by the second line.

5. Your queries

You can pass the queries to the query($query) function. The query is sent to the database and the function returns the result.

Example of an Insert Query

$query = "INSERT INTO users (id, name) VALUES (1, 'Peter Parker');";
$db->query($query);

Example of a select query with output of the result

$query = "SELECT name FROM users WHERE id = 1";
$result = $db->query($query);

while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["name"];
}
</pre>

At the end of your program you should call the close() function to close open database connections.

$db->close();

Ultimately, these are the functions of the database class. I kept them as simple as possible, but still tried to include all important and security relevant functions. And yes: I am aware that PHP and the MySQLi class have much more functions to offer. But this class is just for simple, fast and flexible applications that only require a simple database connection.

Safety instructions or suggestions for improvement are welcome in the comments, so that I can add them! 

Originally published at webdeasy.de on 26. May 2019

====================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter


Learn More

☞ Ultimate PHP Basics for Absolute Beginners - [200+ PHP Code]

☞ PHP in Web Development in 2020

☞ PHP for Beginners - Become a PHP Master - CMS Project

☞ Learn Object Oriented PHP By Building a Complete Website

☞ MEVP Stack Vue JS 2 Course: MySQL + Express.js + Vue.js +PHP

☞ Object Oriented PHP & MVC

☞ PHP OOP: Object Oriented Programming for beginners + Project

☞ Learn PHP Fundamentals From Scratch

☞ The Complete PHP MySQL Professional Course with 5 Projects

☞ The Complete JavaScript Course 2019: Build Real Projects!

How To Implement Pagination in MySQL with PHP on Ubuntu 18.04

How To Implement Pagination in MySQL with PHP on Ubuntu 18.04

In this tutorial, you’ll build a PHP script to connect to your database and implement pagination to your script using the MySQL LIMIT clause.

Introduction

Pagination is the concept of constraining the number of returned rows in a recordset into separate, orderly pages to allow easy navigation between them, so when there is a large dataset you can configure your pagination to only return a specific number of rows on each page. For example, pagination can help to avoid overwhelming users when a web store contains thousands of products by reducing the number of items listed on a page, as it’s often unlikely a user will need to view every product. Another example is an application that shows records on a mobile device; enabling pagination in such a case would split records into multiple pages that can fit better on a screen.

Besides the visual benefits for end-users, pagination makes applications faster because it reduces the number of records that are returned at a time. This limits the data that needs to be transmitted between the client and the server, which helps preserve server resources such as RAM.

In this tutorial, you’ll build a PHP script to connect to your database and implement pagination to your script using the MySQL LIMIT clause.

Step 1 — Creating a Database User and a Test Database

In this tutorial you’ll create a PHP script that will connect to a MySQL database, fetch records, and display them in an HTML page within a table. You’ll test the PHP script in two different ways from your web browser. First, creating a script without any pagination code to see how the records are displayed. Second, adding page navigation code in the PHP file to understand how pagination works practically.

The PHP code requires a MySQL user for authentication purposes and a sample database to connect to. In this step you’ll create a non-root user for your MySQL database, a sample database, and a table to test the PHP script.

To begin log in to your server. Then log in to your MySQL server with the following command:

sudo mysql -u root -p

Enter the root password of your MySQL server and hit ENTER to continue. Then, you’ll see the MySQL prompt. To create a sample database, which we will call test_db in this tutorial, run the following command:

Create database test_db;

You will see the following output:

OutputQuery OK, 1 row affected (0.00 sec)

Then, create a test_user and grant the user all privileges to the test_db. Replace PASSWORD with a strong value:

GRANT ALL PRIVILEGES ON test_db.* TO 'test_user'@'localhost' IDENTIFIED BY 'PASSWORD';

OutputQuery OK, 1 row affected (0.00 sec)

Reload the MySQL privileges with:

FLUSH PRIVILEGES;

OutputQuery OK, 1 row affected (0.00 sec)

Next, switch to the test_db database to start working directly on the test_db database:

Use test_db;

OutputDatabase changed

Now create a products table. The table will hold your sample products—for this tutorial you’ll require only two columns for the data. The product_id column will serve as the primary key to uniquely identify each record. You’ll use the product_name field to differentiate each item by name:

Create table products (product_id BIGINT PRIMARY KEY, product_name VARCHAR(50) NOT NULL ) Engine = InnoDB;

OutputQuery OK, 0 rows affected (0.02 sec)

To add ten test products to the products table run the following SQL statements:

Insert into products(product_id, product_name) values ('1', 'WIRELESS MOUSE');
Insert into products(product_id, product_name) values ('2', 'BLUETOOTH SPEAKER');
Insert into products(product_id, product_name) values ('3', 'GAMING KEYBOARD');
Insert into products(product_id, product_name) values ('4', '320GB FAST SSD');
Insert into products(product_id, product_name) values ('5', '17 INCHES TFT');
Insert into products(product_id, product_name) values ('6', 'SPECIAL HEADPHONES');
Insert into products(product_id, product_name) values ('7', 'HD GRAPHIC CARD');
Insert into products(product_id, product_name) values ('8', '80MM THERMAL PRINTER');
Insert into products(product_id, product_name) values ('9', 'HDMI TO VGA CONVERTER');
Insert into products(product_id, product_name) values ('10', 'FINGERPRINT SCANNER');

You’ll see this output:

OutputQuery OK, 1 row affected (0.02 sec)

Verify that the products were inserted to the table by running:

select * from products;

You’ll see the products in your output within the two columns:

Output+------------+-----------------------+
| product_id | product_name          |
+------------+-----------------------+
|          1 | WIRELESS MOUSE        |
|          2 | BLUETOOTH SPEAKER     |
|          3 | GAMING KEYBOARD       |
|          4 | 320GB FAST SSD        |
|          5 | 17 INCHES TFT         |
|          6 | SPECIAL HEADPHONES    |
|          7 | HD GRAPHIC CARD       |
|          8 | 80MM THERMAL PRINTER  |
|          9 | HDMI TO VGA CONVERTER |
|         10 | FINGERPRINT SCANNER   |
+------------+-----------------------+
10 rows in set (0.00 sec)

Exit MySQL:

quit;

With the sample database, table, and test data in place, you can now create a PHP script to display data on a web page.

Step 2 — Displaying MySQL Records Without Pagination

Now you’ll create a PHP script that connects to the MySQL database that you created in the previous step and list the products in a web browser. In this step, your PHP code will run without any form of pagination to demonstrate how non-split records show on a single page. Although you only have ten records for testing purposes in this tutorial, seeing the records without pagination will demonstrate why segmenting data will ultimately create a better user experience and put less burden on the server.

Create the PHP script file in the document root of your website with the following command:

sudo nano /var/www/html/pagination_test.php

Then add the following content to the file. Remember to replace PASSWORD with the correct value of the password that you assigned to the test_user in the previous step:

<?php

try {

    $pdo = new PDO("mysql:host=localhost;dbname=test_db", "test_user", "PASSWORD");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);

    $sql="select * from products";

    $stmt = $pdo->prepare($sql);

    $stmt->execute();

    echo "<table border='1' align='center'>";

    while ( ($row = $stmt->fetch(PDO::FETCH_ASSOC) ) !== false) {
        echo "<tr>";

        echo "<td>".$row['product_id']."</td>";

        echo "<td>".$row['product_name']."</td>";

        echo "</tr>";

    }

    echo "</table>";

}

  catch(PDOException $e)

{
    echo  $e->getMessage();
}

?>

Save the file by pressing CTRL+X, Y, and ENTER.

In this script you’re connecting to the MySQL database using the PDO (PHP Data Object) library with the database credentials that you created in Step 1.

PDO is a light-weight interface for connecting to databases. The data access layer is more portable and can work on different databases with just minor code rewrites. PDO has greater security since it supports prepared statements—a feature for making queries run faster in a secure way.

Then, you instruct the PDO API to execute the select * from products statement and list products in an HTML table without pagination. The line $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); ensures that the data types are returned as they appear in the database. This means that PDO will return the product_id as an integer and the product_name as a string. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); instructs PDO to throw an exception if an error is encountered. For easier debugging you’re catching the error inside the PHP try{}...catch{} block.

To execute the /var/www/html/pagination_test.php PHP script file that you’ve created, visit the following URL replacing your-server-IP with the public IP address of your server:

http://your-server-IP/pagination_test.php

You’ll see a page with a table of your products.

Your PHP script is working as expected; listing all products on one page. If you had thousands of products, this would result in a long loop as the products are fetched from the database and rendered on the PHP page.

To overcome this limitation, you will modify the PHP script and include the MySQL LIMIT clause and some navigation links at the bottom of the table to add pagination functionality.

Step 3 — Implementing Pagination with PHP

In this step your goal is to split the test data into multiple and manageable pages. This will not only enhance readability but also use the resources of the server more efficiently. You will modify the PHP script that you created in the previous step to accommodate pagination.

To do this, you’ll be implementing the MySQL LIMIT clause. Before adding this to the script, let’s see an example of the MySQL LIMIT syntax:

Select [column1, column2, column n...] from [table name] LIMIT offset, records;

The LIMIT clause takes two arguments as shown toward the end of this statement. The offset value is the number of records to skip before the first row. records sets the maximum number of records to display per page.

To test pagination, you’ll display three records per page. To get the total number of pages, you must divide the total records from your table with the rows that you want to display per page. You then round the resulting value to the nearest integer using PHP Ceil function as shown in the following PHP code snippet example:

$total_pages=ceil($total_records/$per_page);

Following is the modified version of the PHP script with the full pagination code. To include the pagination and navigation codes, open the /var/www/html/pagination_test.php file:

sudo nano /var/www/html/pagination_test.php

Then, add the following highlighted code to your file:

<?php

try {

    $pdo = new PDO("mysql:host=localhost;dbname=test_db", "test_user", "PASSWORD");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);

    /* Begin Paging Info */

    $page=1;

    if (isset($_GET['page'])) {
        $page=filter_var($_GET['page'], FILTER_SANITIZE_NUMBER_INT);
    }

    $per_page=3;

    $sqlcount="select count(*) as total_records from products";
    $stmt = $pdo->prepare($sqlcount);
    $stmt->execute();
    $row = $stmt->fetch();
    $total_records= $row['total_records'];

    $total_pages=ceil($total_records/$per_page);

    $offset=($page-1)*$per_page;

    /* End Paging Info */

    $sql="select * from products limit $offset,$per_page";

    $stmt = $pdo->prepare($sql);

    $stmt->execute();

    echo "<table border='1' align='center'>";

    while ( ($row = $stmt->fetch(PDO::FETCH_ASSOC) ) !== false) {
        echo "<tr>";

        echo "<td>".$row['product_id']."</td>";

        echo "<td>".$row['product_name']."</td>";

        echo "</tr>";

    }

    echo "</table>";

    /* Begin Navigation */

    echo "<table border='1' align='center'>";

    echo "<tr>";

    if( $page-1>=1) {
        echo "<td><a href=".$_SERVER['PHP_SELF']."?page=".($page-1).">Previous</a></td>";
    }

    if( $page+1<=$total_pages) {
        echo "<td><a href=".$_SERVER['PHP_SELF']."?page=".($page+1).">Next</a></td>";
    }

    echo "</tr>";

    echo "</table>";

    /* End Navigation */

}

catch(PDOException $e) {
        echo  $e->getMessage();
}

?>

In your file you’ve used additional parameters to execute paging:

  • $page : This variable holds the current page in your script. When moving between the pages, your script retrieves a URL parameter named page using the $_GET['page'] variable.
  • $per_page: This variable holds the maximum records that you want to be displayed per page. In your case, you want to list three products on each page.
  • $total_records: Before you list the products, you’re executing a SQL statement to get a total count of records in your target table and assigning it to the $total_records variable.
  • $offset: This variable represents the total records to skip before the first row. This value is calculated dynamically by your PHP script using the formula $offset=($page-1)*$per_page. You may adapt this formula to your PHP pagination projects. Remember you can change the $per_page variable to suit your needs. For instance, you might change it to a value of 50 to display fifty items per page if you’re running a website or another amount for a mobile device.

Again, visit your IP address in a browser and replace your_server_ip with the public IP address of your server:

http://your_server_ip/pagination_test.php

You’ll now see some navigation buttons at the bottom of the page. On the first page, you will not get a Previous button. The same case happens on the last page where you will not get the Next page button. Also, note how the page URL parameter changes as you visit each page.

The navigation links at the bottom of the page are achieved using the following PHP code snippet from your file:

. . .
    if( $page-1>=1) {
        echo "<td><a href=".$_SERVER['PHP_SELF']."?page=".($page-1).">Previous</a></td>";
    }

    if( $page+1<=$total_pages) {
        echo "<td><a href=".$_SERVER['PHP_SELF']."?page=".($page+1).">Next</a></td>";
    }
. . .

Here, the $page variable represents the current page number. Then, to get the previous page, the code will minus 1 from the variable. So, if you’re on page 2, the formula (2-1) will give you a result of 1 and this will be the previous page to appear in the link. However, keep in mind that it will only show the previous page if there is a result greater or equal to 1.

Similarly, to get to the next page, you add one to the $page variable and you must also make sure that the $page result that we append to the page URL parameter is not greater than the total pages that you’ve calculated in your PHP code.

At this point, your PHP script is working with pagination and you are able to implement the MySQL LIMIT clause for better record navigation.

Conclusion

In this tutorial, you implemented paging in MySQL with PHP on an Ubuntu 18.04 server. You can use these steps with a larger recordset using the PHP script to include pagination. By using pagination on your website or application you can create better user navigation and optimum resource utilization on your server.