首先,不要忘记设置实际的<form>。把它们都包起来。
其次,我建议,只需在提交按钮中使用相同的名称属性:
name="table_name"
所以它现在应该是这样的:
echo '<h2> Search Result: </h2>';
$searchSQL = "
SELECT DISTINCT table_name FROM information_schema.columns
WHERE LOWER(column_name) LIKE LOWER('%$search%') AND table_schema = 'university'
";
$result = $conn->query($searchSQL);
echo '<form method="POST" action="show_colums.php">'; // opening form tag
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$table_name = $row['table_name'];
echo "<input type='submit' name='table_name' value='$table_name' /> <br/>";
// ^ don use the $table_name in the name attribute
}
echo '</form>'; // closing form tag
别忘了在表单标签中添加action="" 属性。只需将其指向将执行表单处理的任何 PHP 脚本。对于这个例子,只需使用show_columns.php
现在,只需在将处理所选按钮的 PHP 文件中应用 DESCRIBE:
内部show_columns.php:
if(!empty($_POST['table_name'])) {
$table_name = $_POST['table_name']; // get input
$sql = "DESCRIBE {$table_name}"; // use DESCRIBE
$query = $conn->query($sql); // execute query
while($row = $query->fetch_assoc()) { // fetch rows
// do whatver you need to do, table or whatever you like
echo $row['Field']; // field name
}
}
编辑:或者您可以在第一个表单上使用准备好的语句更安全:
echo '<h2> Search Result: </h2>';
$searchSQL = "
SELECT DISTINCT table_name FROM information_schema.columns
WHERE LOWER(column_name) LIKE LOWER(?) AND table_schema = 'university'
";
$stmt = $conn->prepare($searchSQL);
$search = '%' . $search . '%';
$stmt->bind_param('s', $search);
$stmt->execute();
$stmt->bind_result($table_name);
echo '<form method="POST" action="show_columns.php">';
while($stmt->fetch()) {
echo "<input type='submit' name='table_name' value='$table_name' /><br/>";
}
echo '</form>';