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
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);
Related
I'm trying to post form data though a POST AJAX call in JavaScript for a chat system I'm creating, how come the following is not working? I tried to get some documentation but I cannot find it.
<div id="view-chat-form">
<input id="message" type="text" name="chat_message" placeholder="write a message..."/>,
<input type="button" value="send" onclick="sendData()"/>
</div>
and using the followin AJAX code to send the request without loading the page with an hashed string to hide the chat id
<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" + cm);
}
</script>
and the followin php code to insert the message into the messages table
<?php
include "session.php";
include "connection.php";
$id = "";
$hashed_id = mysqli_real_escape_string($connection, $_POST["q"]);
$sql = "SELECT * FROM chats WHERE SHA2(id, 512) = ?";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 's', $hashed_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_num_rows($result);
if($count > 0){
$row = mysqli_fetch_assoc($result);
$id = $row["id"];
} else {
mysqli_free_result($result);
mysqli_close($connection);
header("Location: chat_error.php");
}
$msg = mysqli_real_escape_string($connection, $_POST["chat_message"]);
$username = $_SESSION["username"];
$date = date("d/m/Y");
$time = date("H:i:s");
$sql = "INSERT INTO chat_messages(chat_id, username, message, date, time) VALUES(?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'dssss', $id, $username, $msg, $date, $time);
mysqli_stmt_execute($stmt);
?>
Don't understand why you are using php $_POST in javascript, it will not work. Try using document.getElementById() to grab the chat message.
The correct way is shown below.
<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" + cm);
}
</script>
Also in your PHP code, why using json_decode()? The post is not in JSON format. Correct that also.
Change below code
$data = json_decode(file_get_contents("php://input"));
$hashed_id = $data->q;
$msg = $data->chat_message;
to
$hashed_id = $_POST["q"];
$msg = $_POST["chat_message"];
Do something like this
<script type="text/javascript">
function sendData(){
var id = <?php echo $hashed_id; ?>;
var msg = <?php echo $_POST['chat_message']; ?>;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(id,msg);
}
</script>
I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.
I building a website, which must get data both from a MySQL database on the same server, and from an external API.
I have a javascript function which calls 5 other functions, and each of them creates an XMLHttpRequest to get different kinds of data:
function getData(){
getGi(); //Function which calls an external API (Curl request) via a local php file
getPQ(); //Gets data from a MySQL DB, also via a local php file, same as next 3 functions:
getBS();
getCV();
getTP();
}
All 5 functions call a php file via XMLHttpRequest. The first php file's call is a simple curl request to an external API. The other 4 access a DB on the same server. Example (they are all similar):
function getCV(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "../php/getDB.php?t=CV", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
dados = JSON.parse(this.responseText.slice(0, -1));
initCV(dados);
}
}
}
However, upon loading the website, a few Error 500 are thrown:
CV.js:14 GET https://<url>/php/getDB.php?t=CV 500 (Internal Server Error)
The number of errors or which of the requests throw errors seem random. Sometimes I get just one error, sometimes 3 or 4, and they are never the same files. Right now I've "solved" the issue by forcing the request to try again if it fails the first time:
xmlhttp.addEventListener("load", function() {
if (xmlhttp.status == 500) {
getCV();
return
}
});
But obviously this is not a proper solution. Any ideas on how I can debug/fix this? Or is this a server issue and I should contact my webhost?
Edit: here's the php code:
<?php
//Settings
$dbhost ="localhost";
$dbuser = "user";
$dbpass = "hunter2";
$dbname ="database";
//Read parameter
$tipo = $_GET['t'];
if (is_null($tipo)) {
exit("Sem parĂ¢metro.");
}
//connect to database
$conn = #mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
//query options
mysqli_query($conn,"SET character_set_results = 'utf8mb4', character_set_client = 'utf8mb4', character_set_connection = 'utf8mb4', character_set_database = 'utf8mb4', character_set_server = 'utf8mb4'");
switch($tipo) {
case "CV":
$query = "SELECT * FROM table1";
break;
case "PI":
$query = "SELECT * FROM table2";
break;
case "PQ":
$query = "SELECT * FROM table3";
break;
case "TP":
$query = "SELECT * FROM table4";
break;
case "BS":
$query = "SELECT * FROM table5";
break;
default:
exit("Parametro invalido.");
}
//Execute query
$result = mysqli_query($conn, $query);
if (!$result){
echo "Couldn't execute the query";
die();
}
else{
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data[]=$row;
}
}
mysqli_close($conn);
echo json_encode($data, JSON_PRETTY_PRINT);
?>
So basically I want to have a Javascript function that posts data to a table in my database. i know that I need to call a php page to do this. But the code I have written doesn't work. The js fucntion is triggered by a button press in html. I need to do this in js ajax and not jquery ajax
The Javascript
function comment_sub(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
}
};
xhttp.open("POST", "static/setcomments.php", true);
xhttp.send(encodeURIComponent(document.getElementById('comment-textbox').value));
}
The PHP
<?php
echo "Hello";
$mydb = mysqli_connect("localhost", "root","", "website");
if (!$mydb){
die("Connection failed".mysqli_connect_error());
}
$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_GET['comment-textbox']}')";
$query = mysqli_query($mydb, $sql);
if (!$query)
{
die('Error: ' . mysql_error());
}
echo "1 record added"
?>
Checked the network and console log. The JS function is being called fine but the network logs gives me a 404 error for the post request
You are only sending the value itself, not the name comment-textbox.
Try this:
xhttp.send(JSON.stringify({
'comment-textbox': document.getElementById('comment-textbox').value
}));
On the PHP page, you are doing a HTTP POST and not a HTTP GET. So rewrite it as this:
$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_POST['comment-textbox']}')";
ok I have edited this to another couple of questions I've asked on a similar issue, but I really am in a rush so thought I'd start a new one, sorry if it bothers anyone.
first I have a php script on test.php on the apache server
<?php
//create connection
$con = mysqli_connect("localhost", "user", "password", "dbname");
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Then I've got this ajax script set to fire onload of page a webpage written in html. so the load() function is onload of the page in the body tag. This script is in the head.
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
ok so what I want is the $n1 variable in the php script to be used in the javascript ajax code. Where the script is, but I'm not sure where or how to make use of the variable, I've tried a few things. All that happens right now is the innerHTML of itemNameLink1 just disappears.
I'm quite new so any advise would be appreciated, thanks.
The response (this is what you echo in php) returned from request you can get by responseText attribute of XMLHttpRequest object.
So first your JS code should be:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = xmlhttp.responseText;
}
}
}
now in php echo $n1 variable:
....
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
// echo it to be returned to the request
echo $n1;
Update to use JSON for multiple variables
so if we do this:
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$response = array
(
'name' => $name,
'color' => $color,
'price' => $price
);
echo json_encode($response);
Then in javascript we can parse it again to have data object containing 3 variables.
var data = JSON.parse(xmlhttp.responseText);
//for debugging you can log it to console to see the result
console.log(data);
document.getElementById("itemNameLink1").innerHTML = data.name; // or xmlhttp.responseText to see the response as text
Fetching all the rows:
$row = mysqli_fetch_array($grab); // this will fetch the data only once
you need to cycle through the result-set got from database: also better for performance to use assoc instead of array
$names = $color = $price = array();
while($row = mysqli_fetch_assoc($grab))
{
$names[] = $row['name'];
$color[] = $row['color'];
$price[] = $row['price'];
}
$response = array
(
'names' => $names,
'color' => $color,
'price' => $price
);
You can dynamically generate a javascript document with php that contains server side variables declared as javascript variables, and then link this in the head of your document, and then include this into your document head whenever server side variables are needed. This will also allow you to dynamically update the variable values upon page generation, so for example if you had a nonce or something that needs to change on each page load, the correct value can be passed upon each page load. to do this, you need to do a few things. First, create a php script and declare the correct headers for it to be interpreted as a script:
jsVars.php:
<?php
//declare javascript doc type
header("Content-type: text/javascript; charset=utf-8");
//tell the request not to cache this file so updated variables will not be incorrect if they change
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
//create the javascript object
?>
var account = {
email: <?= $n1; ?>,
//if you need other account information, you can also add those into the object here
username: <?= /*some username variable here for example */ ?>
}
You can repeat this for any other information you need to pass to javascript on page load, and then reference your data using the namespaced javascript object (using object namespacing will prevent collisions with other script variables that may not have been anticipated.) wherever it is needed as follows:
<script type="text/javascript>
//put this wherever you need to reference the email in your javascript, or reference it directly with account.email
var email = account.email;
</script>
You can also put a conditional statement into the head of your document so it will only load on pages where it is needed (or if any permission checks or other criteria pass as well). If you load this before your other scripting files, it will be available in all of them, provided you are using it in a higher scope than your request.
<head>
<?php
//set the $require_user_info to true before page render when you require this info in your javascript so it only loads on pages where it is needed.
if($require_user_info == TRUE): ?>
<script type="text/javascript" href="http://example.com/path-to-your-script/jsVars.php" />
<?php endif; ?>
<script type="text/javascript" href="your-other-script-files-that-normally-load" />
</head>
You can also do this for any other scripts that have to load under specific criteria from the server.
You should define the PHP variable. And use that variable in your javascript:
<?php
$n1 = "asd";
?>
<html>
<head></head>
<body>
<div id="itemNameLink1"></div>
<script>
function load()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/test.php', true);
xmlhttp.send(null);
//Note you used `onreadystatecahnge` instead of `onreadystatechange`
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("itemNameLink1").innerHTML = '<?=$n1?>';
}
}
}
load();
</script>
</body>
</html>