我有以下代码,它根据数据库中的内容动态显示一个表:
$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";
};
你们的任何帮助/想法都会很棒。
一般建议:
while
循环和mysqli_fetch_assoc
函数一样)。最好将db获取结果保存到数组中,并在html代码部分中仅使用此数组稍后遍历其项目。mysqli_real_escape_string
提供的转义来避免sql注入,然后是mysqli_query
。我强烈建议你从现在开始忘记这两个功能。让自己习惯使用prepared statements代替。通过准备好的陈述,您将完全避免使用sql injection - 如果正确应用的话。如果您愿意,另请参阅this post。or die(...)
这样的验证。您可以使用a more elegant solution捕获并处理任何类型的错误/异常/警告/通知/等(如数据库连接失败,错误的sql语法,未定义的索引,数据提取失败等)。和here一样,关于MySQLi。回到你的代码:
attending
组合框值的良好解决方案。就个人而言,我使用了一种稍微不同的方法:“ID”列的值的隐藏输入和每个参加组合框的属性name="attending[]"
。这样,在提交时,您将捕获两个数组(请参阅$ids
和$attendings
),其中每个项目对应于发布的用户ID,resp。给用户参加价值。您也可以在提交时在屏幕上看到生成的数组,因为我实现了2-3个测试代码行(在我的代码中搜索@todo
并采取相应的操作)。border='1'
,HTML5不支持)并避免使用内联css样式。在这两种情况下,都将css类分配给html元素,并在css中相应地自定义它们。$connection
而不是$link
。祝好运。
P.S:如果您关心代码优雅和更好的数据访问,那么请不要犹豫使用PDO而不是MySQLi。虽然PDO是完美的选择,但它们在很多方面非常相似。
<?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;
我认为收集与会者的身份也是有用的,而不是获得'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";
};