I'm building a very simple API in PHP to give me data from my DB in application/json format.
Here is my muscular-groups.php file :
<?php
include '../inc/db.php';
if (isset($_GET['id'])) {
$req = $pdo->prepare('SELECT * FROM muscular_groups WHERE id = ?');
$req->execute([$_GET['id']]);
$res = $req->fetchAll();
}
else {
$req = $pdo->prepare('SELECT * FROM muscular_groups');
$req->execute();
$res = $req->fetchAll();
}
header('Content-Type: application/json');
echo json_encode($res);
The problem is that in local all works well as you can see below :
But when I want to access it on my server (at www.example.com/api/muscular-groups), I have a white screen without any error message or error logs.
What is strange : If I replace header('Content-Type: application/json'); and echo json_encode($res); with var_dump($res) in muscular-groups.php, it appears on the screen.
P.S.: very strange, only one of my endpoints works on my server (eg: www.example.com/api/offers) and displays a json output, here's the code :
<?php
include '../inc/db.php';
$req = $pdo->prepare('SELECT * FROM offers');
$req->execute();
$res = $req->fetchAll();
header('Content-Type: application/json');
echo json_encode($res);
I'm lost...
I finally got it : the problem was there was UTF-8 characters, and PDO was not configured to give them as-is. So $pdo->exec("SET NAMES 'utf8'"); saved my life!
Related
I am trying to get users' data (hypothetical) from mySQL database, store them in an array, convert the array to json to be able to use it in AJAX requests in Javascript.
The code works, but when I add:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header('Content-Type: application/json');
at the top of the index.php, the browser gives me the error:
SyntaxError: JSON.parse: unexpected character at line 5 column 1 of the JSON data
I still haven't any .js file btw, I'm just trying to get it ready for ajax,
and I know the first two headers make the json accessible from the client,
and the last header tells it is in json format.
Here is the code; all the files are in one folder;
index.php
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header('Content-Type: application/json');
require 'config.php';
if($_SERVER['REQUEST_METHOD'] == "GET") {
if(isset($_GET['request'])) {
if($_GET['request'] == "user" && isset($_GET['name'])) {
$test = new TestClass($_GET['name']);
$detail = $test->get_detail();
echo json_encode($detail);
}
else if($_GET['request'] == "users") {
$users = TestClass::get_users();
echo json_encode($users);
}
}
} ?>
config.php
<?php
$dbhost="localhost";
$dbname="ajax";
$dbuser="root";
$dbpassword="";
require 'test.class.php'; ?>
test.class.php
<?php
class TestClass {
private $name;
function __construct($name) {
$this->name = $name;
}
public function get_detail() {
try {
$conn = new PDO("mysql:host=".$GLOBALS['dbhost'].";dbname=".$GLOBALS['dbname'], $GLOBALS['dbuser'], $GLOBALS['dbpassword']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM users where username = ?");
$stmt->execute([$this->name]);
$res = $stmt->fetch();
return array(
"ID" => $res['ID'],
"username" => $res['username'],
"email" => $res['email'],
"password" => $res['password'],
);
}catch(PDOException $e) {
echo $e->getMessage();
return array();
}
}
public static function get_users() {
try{
$conn = new PDO("mysql:host=".$GLOBALS['dbhost'].";dbname=".$GLOBALS['dbname'], $GLOBALS['dbuser'], $GLOBALS['dbpassword']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM users");
$stmt->execute([]);
$array = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($array, array(
"ID" => $row['ID'],
"username" => $row['username'],
"email" => $row['email'],
"password" => $row['password'],
));
}
return $array;
} catch(PDOException $e) {
return array();
}
}
}?>
How i said I still don't have any JavaScript file. I am expecting to see the string of the Array in JSON format by going to: localhost/folder/index.php?request=users
From Firefox
info:
-server: XAMPP for Linux 8.1.10 (so, LAMPP);
-os: Ubuntu server 22.04.1 LTS x86_64, Kernel: 5.15.0-52-generic
-browser: Firefox Browser 106.0.1 (via snap)
Thank you, I tried to google this, but nothing was clear to me.
UPDATE
I was following a tutorial, and whith the above code,
but without the three headers,
this was the output:
But from what I understood, I also have to add the three headers to make it accessible from js.
after adding them, here's the output:
I was expecting to see the data like in the first image.
I solved this, for some reason, which I still don't know,
when I changed the index.php to another structure
using the switch statement to manage the requests, the output was fine.
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header('Content-Type: application/json');
require 'config.php';
if(isset($_GET['request'])) {
switch($_GET['request']) {
case "user":
$test = new TestClass($_GET['name']);
$detail = $test->get_detail();
echo json_encode($detail);
break;
case "users":
$users = TestClass::get_users();
echo json_encode($users);
break;
}
}?>
Maybe someone can explain why this happened.
I would like to be able to save a JSON file that is in a database to the user's PC. In summary, I'm storing setup files from a sim racing game, that use a JSON format, in a database, and I'd like the user to be able to upload/download these JSON files (to share with others, etc).
I've got the upload working, using PDO, so there is a column called setup that is a text data type. I'm using a form, with a $FILES() to fetch the uploaded json file, with some checks to ensure it's a valid setup json.
$setup = file_get_contents($_FILES['setupjson']['tmp_name']); //get json from file uploaded
$setupJSON = json_decode($setup); //decode into object
$car = $setupJSON->carName; //carName from object
if ($obj->searchCarName($car) > 0) // if search matches (car exists)
{
if($obj->insertSingleSetup($_POST["name"], $_POST["description"], $_POST["type"], $car, $_POST["track"], $setup) !== false)
{
header('Location: add.php?success');
exit();
}
else
{
header('Location: add.php?error=Error+adding+the+setup');
exit();
}
}
else
{
header('Location: add.php?error=Please+submit+a+valid+setup');
exit();
}
}
The issue i'm having is downloading the file again. I've been able to view the JSON directly
<?php
include('../db.php');
$setup_id = $_POST['setup'];
try {
$connectionString = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
DB::DB_HOST,
DB::DB_NAME);
$pdo = new PDO($connectionString, DB::DB_USER, DB::DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT * FROM setups WHERE setup_id= :setupID';
$query = $pdo->prepare($sql);
$query->bindValue(':setupID', $setup_id);
$result = $query->execute();
$setup = $query->fetch(PDO::FETCH_ASSOC);
processSetup($setup);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
$setupJSON = json_decode($setup);
echo '<pre>';
echo $setup;
echo '</pre>';
}
?>
but I can't work out how to download it. I've researched that it's related to headers, but everytime I try something, it never works. I just want the save file dialog to appear with the json, and preferably, the option to set the filename outputted to a chosen variable.
Just figured it out, on the processSetup function, I changed the code to this
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
header('Content-type: application/json');
header('Content-disposition: attachment; filename=setup.json');
echo $setup;
}
If I add some code to give the JSON it's proper filename, it'll be perfect :D
Long story short, I have a project that requires creating a user's avatar based on their data from the database. The avatar is generated using the imagepng() and imagecopy() functions.
The user's avatar can either be male or female and that preference is saved in an SQL database as column "user_gender" where "0" = female and "1" = male:
Screenshot of table in phpmyadmin
So the idea is that we take the data from the database, assign the value (0 or 1) to a variable, then use that variable to generate the image. See code below:
<?php
//Database connection script not included, but works fine
$id = 1;
$sqlQuery = "SELECT * FROM table WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array(':id' => $id));
while($rs = $statement->fetch())
{
$gender = $rs['user_gender'];
}
if($gender == "0")
{
//Allocation of images, file paths
$bodytype ="images/female/f_body.png";
}
else
{
$bodytype ="images/male/f_body.png";
}
header('Content-Type: image/png');
$destination = imagecreatefrompng($bodytype);
imagealphablending($destination, true);
imagesavealpha($destination, true);
imagepng($destination);
?>
This code however, does not work as it results in a blank black page on the browser.
HOWEVER, this code, without any pulling from the database, works perfectly fine:
<?php
//taking out the sql query and just creating a $gender variable for testing
$gender = "0";
if($gender === 0)
{
$bodytype ="images/female/f_body.png";
}
else
{
$bodytype ="images/female/f_body.png";
}
header('Content-Type: image/png');
$destination = imagecreatefrompng($bodytype);
imagealphablending($destination, true);
imagesavealpha($destination, true);
imagepng($destination);
?>
This is the output with the second code, showing that the image generation is indeed functional and the problem is most likely the passing from sql to php:
Working image generation in browser
I'd be extremely grateful to know what I am doing wrong or being hinted as to why the code stops working if the variable is pulled from the database.
Thank you!
I tried your code and encountered the same problem so I did some digging it and found that nothing was returned from the database so what I did was prefix the database name along with the tablename and it worked. See code below
$gender = '';
$sqlQuery = "SELECT * FROM register.users WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array('id' => 1));
while($rs = $statement->fetch())
{
$gender = $rs['gender'];
}
if($gender == 0)
{
$bodytype ="images/female/f_body.png";
}
else if($gender == 1)
{
$bodytype ="images/male/m_body.png";
}
$destination = imagecreatefrompng($bodytype);
imagealphablending($destination, true);
imagesavealpha($destination, true);
header('Content-Type: image/png');
imagepng($destination);
Try it and let me know how it goes.
I want to convert severals rows after PDO request but I can't display result on my page.
This is for use with a rubimotion app
there is my php code:
<?php
//to see what return request in my php page
header('Content-type: text/html; charset=utf-8');
try {
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=IP;dbname=NAME','USER','PASS');
$reponse = $bdd->prepare("SELECT * FROM table WHERE id = 1");
$reponse->execute(); #this request return severals rows
$nb = $reponse->rowCount();
if($nb > 0){
$json = json_encode( $reponse->fetchAll( PDO::FETCH_ASSOC ) );
echo $json;
}
}
catch (Exception $e) {
echo "Connexion échouée : " . $e->getMessage();
}
?>
But I have a white page and in the console the response is empty.
Whats wrong ?
I tryed many option however I have many errors like
array to string convertion
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
thanks ! And sorry for the mistakes I am french
You must removed header function & use below line. You should add below line above the json_encode function.
header("content-type:application/json");
I am developing an android app that download songs(so type of data is blob) from db.
I have the following download image code example:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select * from images where id = '$id'";
require_once('dbConnect.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
header('content-type: image/jpeg');
echo base64_decode($result['image']);
mysqli_close($con);
}else{
echo "Error";
}
How do I change "header" and "echo"(under header) to download an mp3 audio file ?
You'll want to send the following header for a .mp3 file:
Content-Type: audio/mpeg3
Refer to https://www.sitepoint.com/web-foundations/mime-types-complete-list/ for a good list of MIME types.