[英]How can I send data by json in php
我正在尝试在本地主机中使用w3school示例,但是当我运行它时,它给了我这个错误
致命错误:未捕获错误:在C:\\ xampp \\ htdocs \\ test \\ json_demo_db.php:7中的bool上调用成员函数bind_param():7堆栈跟踪:#0 {main}抛出在C:\\ xampp \\ htdocs \\ test \\第7行的json_demo_db.php
我刚刚从w3school复制了代码,并替换了有关我的数据库的信息
这是我的代码
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "root", "", "blog");
$stmt = $conn->prepare("SELECT name FROM ? LIMIT ?");
$stmt->bind_param("ss", $obj->table, $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
这是我的html和js
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p>The JSON received from the PHP file:</p>
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp;
obj = { "table":"users", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</body>
</html>
这是w3school的示例的链接(PHP数据库)
prepare()
方法返回FALSE
因为您没有为其提供表名。
您正在FALSE
上调用函数bind_param()
。
通过以下方式直接提供表名:
$stmt = $conn->prepare("SELECT name FROM `$obj->table` LIMIT ?");
因此,修改后的代码应为:
$stmt = $conn->prepare("SELECT name FROM `$obj->table` LIMIT ?");
$stmt->bind_param("s", $obj->limit);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.