我试图让我的按钮工作。它适用于$_SERVER["REQUEST_METHOD"] == "POST"
,但不适用于isset($_POST['submit'])
。 $_SERVER["REQUEST_METHOD"] == "POST"
的问题在于它为我提供了多个条目。
我的代码:
if(isset($_POST['submit']))
{
$server_address = $_POST['submitServerIp'];
$server_port = $_POST['submitServerPort'];
$Query = new SourceQuery( );
try
{
$Query->Connect( $server_address, $server_port, SQ_TIMEOUT, SQ_ENGINE );
$data = $Query->GetInfo( );
}
catch( Exception $e )
{
echo $e->getMessage( );
$error = true;
}
$Query->Disconnect( );
if($error == false)
{
$errorMessage = "false";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$stmt = $conn->prepare("INSERT INTO Servers (ipaddress, port) VALUES (?, ?)");
$stmt->bind_param("ss", $ipaddress, $port);
$ipaddress = $_POST['submitServerIp'];
$port = $_POST['submitServerPort'];
$stmt->execute();
$stmt->execute();
$stmt->close();
mysqli_close($conn);
}
}
?>
HTML:
<form method="post" action="">
<div class="container-fluid search-top">
<div class="addContainer">
<div class="addContainer col-sm-12">
<p class="searchText"><?php echo htmlspecialchars($errorMessage);?></p>
<div class="container col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 ">
<div class="input-group stylish-input-group">
<input type="text" name="submitServerIp" class="form-control input-lg" placeholder="Hostname/IP" style="border:0;">
<input type="text" name="submitServerPort" class="form-control input-lg" placeholder="Port" style="border:0;">
<span class="input-group-addon">
<button class="btn btn-primary" type="submit" value="submit">
<span class="fas fa-plus" aria-hidden="true"></span>
</button>
</span>
</div>
</div>
</div>
</div>
我可以不按照我使用它的方式使用按钮,还是我做错了什么?
答案 0 :(得分:3)
当您使用$_POST[KEY]
变量时,该键实际上是您提交的表单元素的name
,而不是value
。
要解决您的问题,只需在提交按钮中添加name="submit"
即可。
<button class="btn btn-primary" type="submit" name="submit" value="submit">
<span class="fas fa-plus" aria-hidden="true"></span>
</button>
对于数据库中的2个条目,您将调用额外的execute()
函数。
$stmt = $conn->prepare("INSERT INTO Servers (ipaddress, port) VALUES (?, ?)");
$stmt->bind_param("ss", $ipaddress, $port);
$ipaddress = $_POST['submitServerIp'];
$port = $_POST['submitServerPort'];
$stmt->execute();
$stmt->execute();
$stmt->close();
mysqli_close($conn);
您应该删除上述一行$stmt->execute();
。