Hassan
Hassan

Reputation: 422

How can I send data by json in php

I'am trying to use w3school example in my localhost but when I run it , it gives me this error

Fatal error: Uncaught Error: Call to a member function bind_param() on bool in C:\xampp\htdocs\test\json_demo_db.php:7 Stack trace: #0 {main} thrown in C:\xampp\htdocs\test\json_demo_db.php on line 7

I've just copied code from w3school and replace information about my db

here is my code

<?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);
?>

and it's my html and 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>

and this is the link of w3school's example ( PHP Database)

https://www.w3schools.com/js/js_json_php.asp

Upvotes: 0

Views: 262

Answers (1)

Pupil
Pupil

Reputation: 23948

The prepare() method is returning FALSE because, you are not providing the table name to it.

And you are calling function bind_param() on FALSE.

Provide table name directly by:

$stmt = $conn->prepare("SELECT name FROM `$obj->table` LIMIT ?");

So, your modified code should be:

$stmt = $conn->prepare("SELECT name FROM `$obj->table` LIMIT ?");
$stmt->bind_param("s", $obj->limit);

Upvotes: 1

Related Questions