如何动态地回显php$\u GET变量的多个结果
我有以下代码,它根据数据库中的内容动态显示一个表:如何动态地回显php$\u GET变量的多个结果,php,dynamic,get,Php,Dynamic,Get,我有以下代码,它根据数据库中的内容动态显示一个表: $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'&
$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>";
你们的任何帮助/想法都会很好。我认为收集与会者的id也会很有用,而不是获取“1”的列表。 使用POST而不是GET。 通过将Attenting[]指定为select标记的名称来发布为数组
<td>
<select name='attending[]'>
<option value='0'>No</option>
<option value='{$row["id"]}'>Yes</option>
</select>
</td>
一般建议:
- 尽可能避免从php创建html代码
- 不要将db access语句与html创建代码混淆(就像使用
循环和while
函数一样)。最好将db获取结果保存到一个数组中,并在以后的html代码部分中仅使用该数组来迭代其项mysqli\u fetch\u assoc
- 您试图通过应用由
提供的转义,然后是mysqli\u real\u escape\u string
来避免sql注入。我强烈建议你从现在开始忘记这两个功能。让自己养成一种习惯,不要使用它。通过准备好的语句,如果正确应用,您将完全避免。如果你愿意,也可以看看mysqli\u query
- 尝试使用面向对象的MySQLi库而不是过程库(参见我的代码)。在MySQLi的php.net文档中,每个过程函数对应一个面向对象的样式化方法
- 您应该避免像
这样的验证。您可以通过使用捕获和处理任何类型的错误/异常/警告/通知/等(如数据库连接失败、错误的sql语法、未定义的索引、失败的数据获取等)。关于MySQLi或die(…)
- 我在下面编写了解决方案,希望它能帮助您从另一个角度了解整个代码结构和涉及的“操作”。它确实有很多评论,但我认为你会发现它们很有用
- HTTP GET方法在您的任务上下文中不是一个可行的解决方案(甚至不用于测试目的)。您应该从头到尾坚持POST方法,并找到其他一些测试方法
- 一般来说,如果您需要表格中的“ID”列,则不要向您网站的用户显示它。把它藏起来。即使这样,您仍然可以访问每条记录的id值
- @Mahesh和@Tenflex已经为您提供了关于
组合框值的良好解决方案。就我个人而言,我使用了一种稍有不同的方法:为“ID”列的值隐藏输入,为每个主治组合框使用属性参与
。这样,在提交时,您将捕获两个数组(请参见name=“attenting[]”
和$id
),其中每个项目分别对应于发布的用户id。对用户参与值。您也可以在提交时在屏幕上看到生成的数组,因为我实现了2-3个测试代码行(在我的代码中搜索$attentings
,并采取相应的操作)@todo
- 避免在html代码中使用已弃用或不再受支持的属性(如HTML5不支持的
),并避免使用内联css样式。在这两种情况下,将css类指定给html元素,并在css中相应地自定义它们border='1'
- 您可以按原样复制/粘贴/运行我的代码。只需创建这两个页面并运行它,看看它是如何工作的。不要忘记更改db连接参数的值
- 我使用了
而不是$connection
$link
- 再次:阅读有关错误/异常报告和准备好的声明的文章
connection.php
为什么要从php创建这么多html代码?为什么不使用POST而不是GET?因为我不确定从select语句返回的行数。所以这看起来更具活力和灵活性。我是php新手,所以如果有更好的方法,请告诉我,我很高兴被纠正。我之所以使用get,是因为我想看看url中实际提交的内容,这样我就可以与被回送的内容进行比较。好的。所以,您提供的所有代码都在一页中,对吗?因为表单的“action”属性不存在?是的,正确,所有内容都在一页中,所以您将在最终代码中实际使用POST,对吗?是否应该在每次加载页面时执行SELECT查询,或者在某个按钮单击事件上执行SELECT查询?非常感谢!远远超出我的预期!并且完成了任务。为了回答您上面的问题,是的,最终我将把这些数据写回数据库,我目前还在测试。
<td>
<select name='attending[]'>
<option value='0'>No</option>
<option value='{$row["id"]}'>Yes</option>
</select>
</td>
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";
};
<?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);
<?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>
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;