如何动态回显php $ _GET变量的多个结果

问题描述 投票:-2回答:2

我有以下代码,它根据数据库中的内容动态显示一个表:

$sql = "SELECT * from users WHERE pin = '" . mysqli_real_escape_string($link, $_SESSION['pin']) . "' ";
$result = mysqli_query($link,$sql) or die("bad query: $sql");

echo"<form method='GET' name='confirm-attending-form'><table border='1'>";
echo"<tr><th>id</th><th>Firstname</th><th>Surname</th><th>Invite Type</th><th>Attending?</th></tr>";

while($row = mysqli_fetch_assoc($result)) {
    echo"
    <tr>
        <td>{$row['id']}</td>
        <td>{$row['forename']}</td>
        <td>{$row['surname']}</td>
        <td>{$row['invite_type']}</td>
        <td><select name='attending'>
                <option value='0'>No</option>
                <option  value='1'>Yes</option>
            </select>   
        </td>
    </tr>";
}
echo"</table><input type='submit' name='submit' value='Get Selected Values'/></form>";

我想从表的不同行回显$ _GET ['atte'']变量的值。我下面的代码只打印出最后一行。

if(isset($_GET['submit'])){
       $attending_val = $_GET['attending'];  // Storing Selected Value In Variable
        echo "You have selected :" .$attending_val;  // Displaying attending Value  

} else {

    echo "Error";

}; 

你们的任何帮助/想法都会很棒。

php dynamic get
2个回答
1
投票

一般建议:

  • 尽可能避免从php创建HTML代码。
  • 不要将db访问语句与html创建代码混淆(就像使用while循环和mysqli_fetch_assoc函数一样)。最好将db获取结果保存到数组中,并在html代码部分中仅使用此数组稍后遍历其项目。
  • 你试图通过应用mysqli_real_escape_string提供的转义来避免sql注入,然后是mysqli_query。我强烈建议你从现在开始忘记这两个功能。让自己习惯使用prepared statements代替。通过准备好的陈述,您将完全避免使用sql injection - 如果正确应用的话。如果您愿意,另请参阅this post
  • 尝试使用面向对象的MySQLi库而不是程序库(参见我的代码)。在MySQLi的php.net文档中,每个程序功能对应一个面向对象的样式方法。
  • 你应该避免像or die(...)这样的验证。您可以使用a more elegant solution捕获并处理任何类型的错误/异常/警告/通知/等(如数据库连接失败,错误的sql语法,未定义的索引,数据提取失败等)。和here一样,关于MySQLi。

回到你的代码:

  • 我编写了下面的解决方案,希望它能帮助您获得有关整个代码结构和涉及“操作”的另一个视角。它确实有很多评论,但我认为你会发现它们很有用。
  • HTTP GET方法在您的任务环境中不是可行的解决方案(甚至不用于测试目的)。你应该坚持使用POST方法从开始到结束,并找到一些其他的测试方法。
  • 通常,如果表格中需要“ID”列,则不要将其显示给您网站的用户。把它藏起来。即便如此,您仍然可以访问每条记录的id值。
  • @Mahesh和@Tenflex已经为您提供了有关attending组合框值的良好解决方案。就个人而言,我使用了一种稍微不同的方法:“ID”列的值的隐藏输入和每个参加组合框的属性name="attending[]"。这样,在提交时,您将捕获两个数组(请参阅$ids$attendings),其中每个项目对应于发布的用户ID,resp。给用户参加价值。您也可以在提交时在屏幕上看到生成的数组,因为我实现了2-3个测试代码行(在我的代码中搜索@todo并采取相应的操作)。
  • 避免在html代码中使用已弃用或不再使用的属性(如border='1',HTML5不支持)并避免使用内联css样式。在这两种情况下,都将css类分配给html元素,并在css中相应地自定义它们。
  • 您可以按原样复制/粘贴/运行我的代码。只需创建两个页面并运行它以查看它是如何工作的。不要忘记更改db连接参数的值。
  • 我使用$connection而不是$link
  • 再次:阅读有关错误/异常报告和准备好的陈述的文章。

祝好运。

P.S:如果您关心代码优雅和更好的数据访问,那么请不要犹豫使用PDO而不是MySQLi。虽然PDO是完美的选择,但它们在很多方面非常相似。


connection.php

<?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'yourdb');
define('USERNAME', 'youruser');
define('PASSWORD', 'yourpass');

/*
 * Enable internal report functions. This enables the exception handling, 
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions 
 * (mysqli_sql_exception).
 * 
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings. 
 * 
 * @link http://php.net/manual/en/class.mysqli-driver.php
 * @link http://php.net/manual/en/mysqli-driver.report-mode.php
 * @link http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/*
 * Create a new db connection.
 * 
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

users.php

<?php
require 'connection.php';

/*
 * Perform operations upon form submission.
 */
if (isset($_POST['submit'])) {
    $ids = $_POST['ids'];
    $attendings = $_POST['attending'];

    /*
     * Just for testing the results.
     * @todo Delete the two lines below.
     */
    echo '<pre>User ids: ' . print_r($ids, TRUE) . '</pre>';
    echo '<pre>Attendings: ' . print_r($attendings, TRUE) . '</pre>';

    $messages[] = 'The third user has the user id ' . $ids[2] . ' and the attending ' . $attendings[2] . '.';
}

/*
 * Just for testing.
 * @todo Delete the line below.
 */
$_SESSION['pin'] = 12;

// Get the pin.
$pin = $_SESSION['pin'];

/*
 * The SQL statement to be prepared. Notice the so-called markers, 
 * e.g. the "?" signs. They will be replaced later with the 
 * corresponding values when using mysqli_stmt::bind_param.
 * 
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$sql = 'SELECT *
        FROM users 
        WHERE pin = ?';

/*
 * Prepare the SQL statement for execution.
 * 
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$statement = $connection->prepare($sql);

/*
 * Bind variables for the parameter markers (?) in the 
 * SQL statement that was passed to prepare(). The first 
 * argument of bind_param() is a string that contains one 
 * or more characters which specify the types for the 
 * corresponding bind variables.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
$statement->bind_param('i', $pin);

/*
 * Execute the prepared SQL statement.
 * When executed any parameter markers in the sql statement will 
 * automatically be replaced with the appropriate data.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.execute.php
 */
$statement->execute();

/*
 * Get the result set from the prepared statement.
 * 
 * NOTA BENE:
 * Available only with mysqlnd ("MySQL Native Driver")! If this 
 * is not installed, then uncomment "extension=php_mysqli_mysqlnd.dll" in 
 * PHP config file (php.ini) and restart web server (I assume Apache) and 
 * mysql service. Or use the following functions instead:
 * mysqli_stmt::store_result + mysqli_stmt::bind_result + mysqli_stmt::fetch.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.get-result.php
 * @link https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
 */
$result = $statement->get_result();

/*
 * Fetch the data and save it into an array.
 * 
 * @link http://php.net/manual/en/mysqli-result.fetch-all.php
 */
$users = $result->fetch_all(MYSQLI_ASSOC);

/*
 * Free the memory associated with the result. You should 
 * always free your result when it is not needed anymore.
 * 
 * @link http://php.net/manual/en/mysqli-result.free.php
 */
$result->close();

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them 
 * so that the next query can be executed.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.close.php
 */
$statement->close();

/*
 * Close the previously opened database connection.
 * Not really needed, because php automatically closes all connections
 * when the script processing finishes.
 * 
 * @link http://php.net/manual/en/mysqli.close.php
 */
$connection->close();
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <style type="text/css">
            body { padding: 30px; }
            button { margin-top: 20px; padding: 7px 12px; background-color: #8daf15; color: #fff; border: none; }
            .messages { margin-bottom: 20px; }
            .users { border-collapse: separate; border: 1px solid #ccc; }
            .users thead th { padding: 10px; background-color: #f3f3f3; }
            .users tbody td { padding: 5px; }
            .idColumn { display: none; }
        </style>
    </head>
    <body>

        <h4>Users list</h4>

        <div class="messages">
            <?php
            if (isset($messages)) {
                echo implode('<br/>', $messages);
            }
            ?>
        </div>

        <form name="confirm-attending-form" action="" method="post">
            <table class="users">
                <thead>
                    <tr>
                        <th class="idColumn">ID</th>
                        <th>First Name</th>
                        <th>Surname</th>
                        <th>Invite Type</th>
                        <th>Attend?</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ($users) {
                        foreach ($users as $user) {
                            $id = $user['id'];
                            $firstName = $user['forename'];
                            $surname = $user['surname'];
                            $inviteType = $user['invite_type'];
                            ?>
                            <tr class="user">
                                <td class="idColumn">
                                    <input type="hidden" id="userId<?php echo $id; ?>" name="ids[]" value="<?php echo $id; ?>" />
                                </td>
                                <td>
                                    <a href="javascript:alert('Do something with this row. User id: <?php echo $id; ?>');">
                                        <?php echo $firstName; ?>
                                    </a>
                                </td>
                                <td>
                                    <?php echo $surname; ?>
                                </td>
                                <td>
                                    <?php echo $inviteType; ?>
                                </td>
                                <td>
                                    <select name="attending[]">
                                        <option value="0">No</option>
                                        <option value="1">Yes</option>
                                    </select>   
                                </td>
                            </tr>
                            <?php
                        }
                    } else {
                        ?>
                        <tr>
                            <td colspan="5">
                                <?php echo 'No users found'; ?>
                            </td>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
            </table>

            <button type="submit" id="submit" name="submit" value="submit">
                Submit
            </button>
        </form>

    </body>
</html>

Used table structure:

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `pin` int(11) DEFAULT NULL,
  `forename` varchar(100) DEFAULT NULL,
  `surname` varchar(100) DEFAULT NULL,
  `invite_type` int(11) DEFAULT NULL,
  `attending` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

0
投票

我认为收集与会者的身份也是有用的,而不是获得'1'的列表。使用POST而不是GET。通过将参加[]作为选择标记的名称作为数组发布。

<td>
<select name='attending[]'>
                <option value='0'>No</option>
                <option  value='{$row["id"]}'>Yes</option> 
            </select>   
        </td>

然后在PHP运行

if(isset($_POST['attending'])){
       $attending_val = $_POST['attending'];  // Storing Selected Values In Variable
        echo "You have selected :" .implode ( ", " , $attending_val );  // Displaying list of attending ID's

} else {
    echo "Error";
}; 
© www.soinside.com 2019 - 2024. All rights reserved.