I cannot display an image from my Mysql Database.
I've kept following all the examples and other posts but can't seem to get it right...
<?php
$db = new PDO('mysql:host=localhost;dbname=MyDatabase;charset=utf8mb4', 'tester', '1234567890');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$request = "347";
$mytable = "u55";
$stmt = $db->prepare("SELECT * FROM ".$mytable." WHERE Id = :SearchName ");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $result[0]['TheAvatar'];
header("Content-Type: image/jpg");
echo '<img src="'.$result.'" />';
?>
My error that I have is image cannot be displayed because it contains errors.
The only difference I have from the examples is the data is stored in TEXT not BLOB/VARCHAR..
I've also tried using BinToHex() with the data to see if that made a difference.
The pictures come from a phone and are stored on a server.
The Pic data is in this link below (cant copy paste it so..)
http://spyon.agency/PicData.bmp
EDIT:
This is the code that stores the data into the DB..
It's a code snippet from the main file, the login remains the same as posted above. The Data comes from a JSON string.
$MessageDecoded = base64_decode ($request);
$input = json_decode($MessageDecoded);
Then the function that stores the data is
$mTheAvatar = $input[$i]->TheAvatar;
$mTheDirection= $input[$i]->TheDirection;
$mTheGroup = $input[$i]->TheGroup;
$mTheMedia = $input[$i]->TheMedia;
$mTheMessage = $input[$i]->TheMessage;
$mTheSenderName= $input[$i]->TheSenderName;
$mTheThumbImage = $input[$i]->TheThumbImage;
$mTheTime = $input[$i]->TheTime;
$mTheMediaExtension = $input[$i]->TheMediaExtension;
$statement = $db->prepare('INSERT INTO '.$mDevice.' '.
'(TheAvatar , TheDirection , TheGroup , TheMedia , TheMediaExtension , TheMessage , TheSenderName , TheThumbImage , TheTime) '.
'VALUES (:aTheAvatar, :aTheDirection, :aTheGroup , :aTheMedia, :aTheMediaExtension , :aTheMessage, :aTheSenderName, :aTheThumbImage, :aTheTime)');
try {
$statement->execute(array(
"aTheAvatar" => $mTheAvatar,
"aTheDirection" => $mTheDirection,
"aTheGroup" => $mTheGroup,
"aTheMedia" => $mTheMedia,
"aTheMediaExtension" => $mTheMediaExtension,
"aTheMessage" => $mTheMessage,
"aTheSenderName" => $mTheSenderName,
"aTheThumbImage" => $mTheThumbImage,
"aTheTime" => $mTheTime
));
} catch(PDOException $ex) {
echo "An Error occured!";
echo $ex->getMessage();
die;
}
you can use this code to show your image :
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result ).'"/>';
Related
i am getting issue in PUT method. But everything is fine when i'm doing method post
here is some code :
<?php
header("Content-type: multipart/form-data");
include_once '../Database/database.php';
$status = array();
if(is_uploaded_file($_FILES["ImageKTP"]["tmp_name"]))
{
$tmp_file = $_FILES["ImageKTP"]["tmp_name"];
$ImageKTP = $_FILES["ImageKTP"]["name"];
$upload_dir = "./uploads/" .$ImageKTP;
if (move_uploaded_file($tmp_file, $upload_dir)) {
$status['kode']=1;
$status['deskripsi']='upload success';
$ImageKTP = $upload_dir;
} else {
$status['kode']=0;
$status['deskripsi']='upload failed';
$ImageKTP = null;
}
}
echo json_encode($status);
?>
But when i'm doing method put using application/json, the result is failed
<?php
header("Content-type: application/json");
include_once '../Database/database.php';
include_once '../Controller/users.php';
$data = json_decode(file_get_contents('php://input'), true);
$email=$data['email'];
$idcardnumber=$data['idcardnumber'];
$placeofbirth=$data['placeofbirth'];
$dateofbirth=$data['dateofbirth'];
$Gender=$data['Gender'];
$Religion=$data['Religion'];
$ImageKTP=$data['ImageKTP'];
$ImageSelfie=$data['ImageSelfie'];
$ImageFamilyMemberCard=$data['ImageFamilyMemberCard'];
$database = new Database();
$db = $database->getConnection();
$user = new Users($db);
$stmt = $user->UpdateProfile($email, $idcardnumber, $placeofbirth, $dateofbirth, $Gender, $Religion, $ImageKTP, $ImageSelfie, $ImageFamilyMemberCard);
if($stmt->rowCount() > 0){
// create array
$profile_arr=array(
"success" => 1,
"message" => "Successfully Update Profile!"
);
}
else{
$profile_arr=array(
"success" => 0,
"message" => "Update Profile Failed!",
);
}
print_r(json_encode($profile_arr));
?>
I still didnt find out how to solve this problem cause i want to update profile using method PUT include other value
The $_FILES array only works with POST requests. If you want to use PUT there are some configurations to the web server that need to be made first, you can find a detailed guide here.
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
I have a very simple update page where i post updates with title, content and a timezone. However, i've noticed that since a couple of days the timezone is different from mine.
If my local time is 12.00, it says that it was posted at 10.00. Now i'm not sure why this is happening all of the sudden, so i hope you guys can help me out.
DB structure:
Table: Updates -
Columns: medewerker, titel, tekst, datum(timestamp)
Here is my code:
function PostUpdate() {
try {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(!empty($_POST['titel']) && $_POST['tekst']) {
$mede = ucfirst($_SESSION['username']);
$titel = trim($_POST['titel']);
$titel = strip_tags($titel);
$titel = htmlspecialchars($titel);
$tekst = trim($_POST['tekst']);
$tekst = strip_tags($tekst);
$tekst = htmlspecialchars($tekst);
$datum = date("Y-m-d H:i:s");
require('connection.php');
$insertstmt = $pdo->prepare('INSERT INTO updates (medewerker, titel, tekst, datum) VALUES (:medewerker, :titel, :tekst, :datum)');
$insertstmt->execute(array(':medewerker' => $mede, ':titel' => $titel, ':tekst' => $tekst, ':datum' => $datum));
header('Refresh:0');
exit();
} else {
echo "Titel of tekst is niet ingevuld.";
}
}
}
catch (PDOException $e) {
echo "Something went wrong: " . $e->getMessage() . "";
}
}
It can be happen based on your server(host) (In local also same). I faced this issue early with when using Symfony on AWS server. To fix I used
date_default_timezone_set("America/New_York"); # can change whatever you want
Here is the List of supported time formats
In local(php.ini)
date.timezone="";
Read : Runtime Configuration
i have a file on the disk that i retrieve, and store its contents into an array for display as json.
function getCurrentPic($username, $password){
$con = connectToPDO();
$valid = validateUser($username, $password);
if($valid == 1){
$sth = $con->prepare('
SELECT current_pic
FROM user
WHERE
username = :username');
$sth->execute(array(':username' => $username));
$sth->bindColumn(1, $imagePath, PDO::PARAM_STR);
$sth->fetch(PDO::FETCH_BOUND);
echo spitImageJSON($imagePath);
}
}
function spitImageJSON($imagePath){
if(strlen($imagePath) > 1){
$IDPath = $imagePath.'d';
$id = getContentsAtPath($IDPath);
$image = getContentsAtPath($imagePath);
//echo "$imagePath";
$arrayData = array(array(
'image' => $image,
'id' => $id
));
return json_encode($arrayData);
}
}
that code doesn't work unless i uncomment the echo "$imagePath", at which point it prints the path AND the json.. when i re-comment it, nothing is echoed. I'm losing my mind. please help.
btw the file is just a base64 encoded string.. id is just a numerical string
by placing
header("Content-type: application/json");
before returning the json, it worked like it was supposed to without the echo $imagePath
In case anyone else has this problem, I had to add the following on top over the correct answer:
header("Access-Control-Allow-Origin: *");
I have a simple form that inserts data into my sqlite database. It works just fine on my localhost, however, I am not getting the insert to work on my remote server. How do I get error messages if my execute() never happens or === false?
Here is my code:
if (isset($_POST["submit"])) {
$email = $_POST["Email"];
$name = $_POST["txt_Name"];
$agency = $_POST["sel_Agency"];
$subagency = $_POST["txt_SubAgency"];
$location = $_POST["txt_Location"];
$params = array(
':email' => $email,
':name' => $name,
':agency' => $agency,
':subagency' => $subagency,
':location' => $location
);
$stmt = $db->prepare($sql);
if ($stmt->execute($params) === FALSE) {
//HOW TO SHOW ERROR CODE HERE
}
}
I tried a try-catch, but didn't get anything. However, if I echo "ERROR" for example, I get the echo ERROR on screen.... I know it isn't working also, since the db has no new rows.
Any help would be appreciated. Thanks!
If you are using PDO, to get the last error use $db->errorCode() to get erro code and $db->errorInfo() get error info