是否可以用PHP测试邮差中的单选按钮?



我有一段api的代码,允许用户输入各种东西的文本输入,但我也想包括一个单选按钮,让用户在3种类型的东西之间做出选择。我怎么能包括在我的API,我怎么能通过邮差测试它?

<?php


$DBhost = "localhost";
$DBuser = "root";
$DBpassword = "";
$DBname = "mytest";
$conn = mysqli_connect($DBhost, $DBuser, $DBpassword, $DBname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$data = json_decode(file_get_contents("php://input"), true);
$n1 = $data["num1"];
$n2 = $data["num2"];
$n3 = $data["num3"];
num_input(num_1,num_2,num_3)VALUES ('".$n1."','".$n2."','".$n3."')";
if(mysqli_query($conn, $query) or die("Insert Query Failed"))
{
echo json_encode(array("message" => "Product Inserted Successfully", "status" => true));
}
else
{
echo json_encode(array("message" => "Failed Product Not Inserted ", "status" => false));
}
?>

不幸的是,在您的情况下,不清楚是谁以及如何发送请求,以及您的表单看起来是什么样子。我将从你的例子开始。从这行代码判断:

$data = json_decode(file_get_contents("php://input"), true);

你正在使用ajax请求,发送json。


我还想包括一个单选按钮,这将让用户做一个

添加到您的表单单选按钮如下:

<input type="radio" id="some1" name="something" value="var1">
<label for="some1">Some 1</label><br>
<input type="radio" id="some2" name="something" value="var2">
<label for="some2">Some 2</label><br>
<input type="radio" id="some3" name="something" value="var3">
<label for="some3">Some 3</label>

我如何在我的api中包含这个

将得到与text

相同的变量
$data = json_decode(file_get_contents("php://input"), true);
$n1 = $data["num1"];
$n2 = $data["num2"];
$n3 = $data["num3"];
$something = $data["something"];

顺便说一下,你可以检查你得到的结果,像这样:

$data = json_decode(file_get_contents("php://input"), true);
var_dump($data);
die();

如何通过邮差进行测试

我不确定,但是你可以这样写:

使用request with 发送jsonmethod = POST

add header: Content-Type = application/json

添加json格式的正文= {"num1"="1","num2"="2","num3"="3";


警告:

当你处理用户数据时,你不应该信任他的输入数据。你需要检查它们。您可以使用php pdo和bind参数来防止SQL注入。

https://www.php.net/manual/en/pdo.prepared-statements.phphttps://www.w3schools.com/sql/sql_injection.asp


if(mysqli_query($conn, $query) or die("Insert Query Failed"))
{
echo json_encode(array("message" => "Product Inserted Successfully", "status" => true));
}
else
{
echo json_encode(array("message" => "Failed Product Not Inserted ", "status" => false));
}

这里的Else代码将永远不会到达,因为如果mysqli_query发生错误死亡。要么删除,要么死掉(…)片段


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

尝试使用相同的响应

if (!$conn) {
echo json_encode(array("message" => "Connection failed: " . mysqli_connect_error(), "status" => false));
}

开始使用psr:

https://www.php-fig.org/psr/psr-1/
  • https://www.php-fig.org/psr/psr-12/
  • https://www.php-fig.org/psr/

最新更新