【发布时间】:2024-01-24 12:05:01
【问题描述】:
我必须做一个网络服务。因此我参考了网上的一些教程并想出了以下代码
index.php
<html>
<head>
<title>Form page</title>
</head>
<body>
<form action="http://localhost:81/my%20web%20service/webservice" method="get">
Table name:<br>
<input type="text" name="s" value=""><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
webservice.php
<?php
include('connectdb.php');
$something = $_POST['s'];
$sql = "SELECT * FROM $something";
$result = $conn->query($sql);
$myArray = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
echo "name: " . $row["name"]. " - town: " . $row["town"]. " - telephone: " . $row["telephone"]. "<br>";
}
//$data = json_encode($myArray);
//var_dump($data);
$url = 'http://localhost:81/my%20web%20service/show%details.php';
$ch=curl_init($url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
$string = http_build_query($myArray);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
$applist = curl_exec($ch);
curl_close($ch);
} else {
echo "0 results";
}
//$result->close();
$conn->close();
?>
connectdb.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webservice_trial";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "connection successful.<br>";
}
?>
现在我想做的是让数据显示在另一个页面上。 即我想将数据从 webservice.php 从 json 格式传输到另一个页面(显示 details.php)。
显示详细信息.php
<html>
<head>
<title>Show details page</title>
</head>
<body>
<?php
print_r($_POST['data']);
?>
</body>
</html>
如何将 json 字符串从 web 服务重定向到 show details.php
我得到的是这个
connection successful.
name: hilton - town: colombo - telephone: 774933705
name: galadari - town: colombo - telephone: 112894143
name: mt. lavinia - town: mt. lavinia - telephone: 773580324
string(257) "[{"name":"hilton","town":"colombo","telephone":"774933705","description":"excellent"},{"name":"galadari","town":"colombo","telephone":"112894143","description":"best"},{"name":"mt. lavinia","town":"mt. lavinia","telephone":"773580324","description":"good"}]"
Access forbidden!
You don't have permission to access the requested object. It is either read- protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
Error 403
【问题讨论】:
-
你是在本地主机还是虚拟主机上工作
-
我正在使用 localhost (xampp)
-
检查您的主机文件、Apache2 配置文件和虚拟主机文件
-
@NimmiRashinika,您的查询有问题:` $sql = "SELECT * FROM $something";` ,
$something我猜不是您的表名 -
@Nehal 女士,我已经检查过了
标签: php mysql json web-services curl