【发布时间】:2016-06-03 02:22:20
【问题描述】:
我必须做一个网络服务。因此我参考了网上的一些教程并想出了以下代码
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 = $_GET['s'];
$sqlcode = mysql_query("Select * from $something");
$jsonObj= array();
while($result=mysql_fetch_object($sqlcode))
{
$jsonObj[] = $result;
}
$final_res =json_encode($jsonObj) ;
echo $final_res;
?>
connectdb.php
<?php
$hostname="localhost";
$username="root"; //write your username
$password=""; //write your password
$db_name="webservice_trial"; //write your db name
$con=mysql_connect($hostname,$username,$password);
mysql_select_db($db_name,$con) or die ("Cannot connect the Database");
mysql_query("SET NAMES 'utf8'",$con);
?>
上面的代码工作正常。 当我从 form.php 输入一个表的名称时,它将检索该特定表中的所有元组。
现在我想做的是让数据显示在另一个页面上。 即我想将数据从 webservice.php 从 json 格式传输到另一个页面。所以我编辑了我的 webservice.php 如下
webservice.php
<?php
include('connectdb.php');
$something = $_GET['s'];
$sqlcode = mysql_query("Select * from $something");
$jsonObj= array();
while($result=mysql_fetch_object($sqlcode))
{
$jsonObj[] = $result;
}
$final_res =json_encode($jsonObj) ;
echo $final_res;
$jsonArray = (array) json_decode($final_res);
echo $jsonArray[0];
?>
它给出了以下错误
[{"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"}]
可捕获的致命错误:第 18 行的 C:\xampp\htdocs\json_folder\my web service\webservice.php 中的类 stdClass 的对象无法转换为字符串
【问题讨论】:
-
错字
jsonArray,需要$。 -
发布代码的最后一行。 jsonArray 前面需要一个 $。
-
您还需要解决发布的代码中存在的 SQL 注入问题。 :)
-
我编辑了错字,但它仍然给出错误。帮帮我