简体   繁体   中英

Using checkboxes to display sql table data with php

I have five checkboxes that pertain to a column name in my table. Currently the checkboxes each have thier own "name". what im trying to do is allow for multiple boxes to be checked, and then depending on which ones are checked a table will be shown with the selected boxes.

currently what happens is if I select all the boxes the table is shown correctly, If i only select a few i get undefined variable errors because of the way my code is wrriten. How can i write my code so that depending on with check boxes are checked, that table datta will show?

note: using PDO method

html

        <form name='checkboxform' method='post' action='phpfiles/checkBox.php'>
            <input type='checkbox' name='teamname' value='teamname'>teamname<br>
            <input type='checkbox' name='city' value='city'>city<br>
            <input type='checkbox' name='bestplayer' value='bestplayer'>bestplayer<br>
            <input type='checkbox' name='yearformed' value='yearformed'>yearformed<br>
            <input type='checkbox' name='website' value='website'>website<br>
            <br>
            <input type='submit' value='Submit Data'>
        </form>

php

<?php


    if ($_SERVER["REQUEST_METHOD"] == "POST"){
        // server and database information
        $servername = "localhost";
        $username = "";
        $password = "";
        $dbname = "";

        if (isset($_POST['teamname'])) {
            $teamname = $_POST['teamname'];
        } 
        if (isset($_POST['city'])) {
            $city = $_POST['city'];
        }
        if (isset($_POST['bestplayer'])) {
            $best = $_POST['bestplayer'];
        } 
        if (isset($_POST['yearformed'])) {
            $year = $_POST['yearformed'];
        }
        if (isset($_POST['website'])) {
            $website = $_POST['website'];
        }


        echo "<table style='border: solid 1px black;'>";
        echo "<tr><th>$teamname</th><th>$city</th><th>$best</th><th>$year</th><th>$website</th></tr>";

        class TableRows extends RecursiveIteratorIterator { 
            function __construct($it) { 
                parent::__construct($it, self::LEAVES_ONLY); 
            }

            function current() {
                return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
            }

            function beginChildren() { 
                echo "<tr>"; 
            } 

            function endChildren() { 
                echo "</tr>" . "\n";
            } 
        } 

            try {
                $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $stmt = $conn->prepare("SELECT $teamname, $city, $best, $year, $website FROM teams"); 
                $stmt->execute();

                // set the resulting array to associative
                $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
                foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
                    echo $v;
                }
            }
            catch(PDOException $e) {
                echo "Error: " . $e->getMessage();
            }
            $conn = null;
            echo "</table>";
    }    
?>

I know the way my code is, if all the boxes are not check i get errors but im not sure how to accomplish this task. Im quite lost on this.

Instead of just accepting input directly into your SQL statement, and also to avoid all of those unnecessary isset() statements, give your name parameter an array structure to easily loop over them.

Alter your HTML markup like so:

name=team[teamname]
name=team[city]

...so on and so forth.

Now, we'll just loop over the variables. However, before doing so, let's create a whitelisted array of column names so we don't get completed destroyed by SQL injection.

$allowed_columns = array(
    'teamname',
    'city',
    'bestplayer',
    'yearformed',
    'website'
);

Next, lets loop over and check for our field in the whitelist, we'll then use it if it exists, otherwise we'll just move on.

$user_selected_fields = array();
if(isset($_POST['team'])){
    foreach($_POST['team'] as $column =>  $checkbox_value){
        if(in_array($column, $allowed_columns){
            $user_selected_fields[] = $column;
        }
    }
}

Now our data is safe, we're only allowing columns that we have predetermined should be available, so there is no chance of SQL injection. Now we can implode the array on ", " and we'll have a proper list of column names the user wants to see.

$this->conn->prepare("select " . implode(', ', $user_selected_fields) ." from teams");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM