How to add image php file from MAMP server - php

I am trying to add image in MAMP server table & fetch it in PHP, and create json. But I am not getting how to add image in table and again it in file. I am new in PHP scripting. Please someone provide me right direction. I have added my PHP code & also MAMP table screenshot.
PHP Code file
<?php
$conn = mysql_connect("localhost:8888","asmita","asmita123") or die(mysql_error());
if($conn)
{
mysql_select_db("EmployeeInfo");
//echo "connected";
//echo $_SERVER['DOCUMENT_ROOT'];
}
else
{
echo "not connected";
mysql_error();
}
$selectQuery="select * from Emp";
$row=mysql_query($selectQuery);
while($result=mysql_fetch_array($row))
{
//echo $_SERVER['http://localhost:8888/images/index.jpg'];
//output need in JSON format for webservice ...
$empname= $result['Name'];
$empadd= $result['Address'];
$emppho= $result['Phone'];
$emppost= $result['Post'];
$empphoto=$result['Photo'];
$jsonArray[]=array("name"=>"$empname","address"=>"$empadd","phone"=>"$emppho","post"=>"$emppost","photo"=>"$empphoto");
}
echo json_encode($jsonArray);
?>
MAMP table data
Here I added image path. Is this correct? Thanks.

HTML Code
<input type="file" name="img_file" id="imageUpload">
PHP Code
$filename = $_FILES['img_file']['name'];
$src = $_FILES['img_file']['tmp_name'];
$folder = "/images/" ;
$move= move_uploaded_file($src,"$folder/".$image);
if($move!=false)
{
$pic = "http://localhost:8888/directoryName/images" .$filename; //This variable insert into Photo column
$query="Insert or Update Query for your table";
$rslt = mysql_query($query);
}
$data=array();
$selectQuery="select * from Emp";
$row=mysql_query($selectQuery);
while($result=mysql_fetch_array($row))
{
$data[] = $result;
}
echo json_encode($data);

Related

HTML function to download JSON stored in MySQL database

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

PHP's include not working properly

So recently I started a project where I need to load some files. In these files I have colors that come via SQL;
The Problem is, I can only include one color in a file where they'll be used. The first file to be included will work properly, but the second one will not.
The weirdest thing is that if I try to add some echo, all included files will echo it, but only the first one in the order of the import will actually work. It's kind of complicate to explain, but some code can help:
Portifolio.php (where I will use the colors)
<?php
error_reporting(E_ALL);
include_once ('php/db.php');
include_once ('php/colors/accent.php');
include_once ('php/colors/primary.php');
$page =
<<<HTML
// Long HTML code here
<nav class="$primarycolor">
// More code
<a class ="$accentcolor">
accent.php:
<?php
include ('../db.php');
$sql = "SELECT id, color FROM Colors WHERE id = 2";
$getcolor = mysqli_query($conn, $sql);
echo "Accent.php included";
if ($getcolor->num_rows > 0) {
while($row = $getcolor->fetch_assoc()) {
$accentcolor = $row['color'];
}
}
mysqli_close($conn);
?>
primary.php
<?php
include ('../db.php');
$sql = "SELECT id, color FROM Colors WHERE id = 1";
$getcolor = mysqli_query($conn, $sql);
echo "Primary.php has been included";
if ($getcolor->num_rows > 0) {
while($row = $getcolor->fetch_assoc()) {
$primarycolor = $row['color'];
}
}
mysqli_close($conn);
?>
db.php
<?php
$conn = mysqli_connect("localhost","mucap","pswd","webdata");
echo "DB included.";
if (mysqli_connect_errno())
{
echo "Error: " . mysqli_connect_error();
}
?>
In this case:
No errors are gonna be displayed.
$accentcolor will work
$primarycolor will simply pretend it does not exists
All files will echo what they were told to.
I did a lot of research and figured out it could be something with file paths, but I dont think so: Here goes (part of) my file structure:
I cant do [$DOCUMENT_ROOT] as this is not supposed to have a fixed path, long explanation.
What should I do?
Try replacing your statement with this:
if ($getcolor) {
while($row = $getcolor->fetch_assoc()) {
$primarycolor = $row['color'];
}
} else{
echo"no results in row";
}
The simple if check is possible because the results of a search return "FALSE" if there's no data in the results.
The else statement is required just for verification purposes.
If you only expect 1 result, you can do "LIMIT 1" as well as eliminate the while statement.
If you don't want the script to run at all, you should use require_once, not include_once

PHP - getting image from database

I want to save user's image to a database.
p9_member (member_no ,member_name , .... , member_photo)
Now, I am using a BLOB to save the image for "member_photo" column
What I want to do now is that:
1. I have an application that need to connect the database and get the image from the database.
2. I have also a website doing the same things.
I am implementing the application now. As I need to send the image with some information of the member like name or id. So I create an object to save all the things. This is my PHP code:
<?PHP
Class Friends{
var $no;
var $name;
var $photo;
var $status;
var $admin;
public function __construct($no,$name,$photo,$admin,$status){
$this->name = $name;
$this->photo = $photo;
$this->no = $no;
$this->status=$status;
$this->admin=$admin;
}
};
include ("../../server_config.php");
$friends = array();
$SQL = "SELECT p9_member.member_no,p9_member.photo AS PHOTO,p9_member.name,p9_member.photo FROM p9_member, p9_friends WHERE p9_member.member_no = p9_friends.member_no2 AND p9_friends.member_no1 =".$_POST['memberno'];
$result = mysqli_query($con,$SQL);
if (mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)){
$friends[] = new Friends($row['member_no'],$row['name'],$row['photo'],null,null);
}
}else
$friends[] = 0;
echo json_encode($friends);
?>
The SQL CODE:
SELECT p9_member.member_no,p9_member.photo AS PHOTO
FROM p9_member, p9_friends
WHERE p9_member.member_no = p9_friends.member_no2
AND p9_friends.member_no1 =".$_POST['memberno']
I cannot get the data back from the application after json decode.
What is the best solution for me?
TRY the below code it will work..
$image_qry=mysql_query("SELECT * FROM tabel_name WHERE your condition");
$image=mysql_fetch_assoc($image_qry);
$get_image=$image['image_column']; //BLOB DATA TYPE
header("Content-type: image/jpeg"); // need to add the header content type in your code
echo $get_image;

File Downloading error from database php

I have read every tutorial I can find on this topic, but none of them helped fix my issue. I don't know why, but my code is just giving me an html file whenever I click on the download button, instead of downloading an image file.
HTML:
Download Now
PHP:
<?php
$id= $_GET['id'];
$con= mysqli_connect("localhost","root","","dbname");
if (mysqli_connect_errno($con))
{
echo "<script type=\"text/javascript\">alert('Failed To connect to MySQL: "+"mysqli_connect_error();"+"');</script>";
}
else
{
$sql = "SELECT * FROM users_files WHERE file_id = ".$id;
$result = mysql_query($sql);
$row_cnt = mysqli_num_rows($result);
echo "<script type=\"text/javascript\">alert('".$row_cnt."');</script>";
if(!$result || !mysql_num_rows($result)){
echo "<script type=\"text/javascript\">alert('Invalid file chosen.');</script>";
//echo '<script language="javascript" type="text/javascript" >';
//echo ' window.location.assign("ViewMyFiles.php");';
//echo '</script>';
mysqli_close($con);
}
$curr_file = mysql_fetch_assoc($result);
$size = $curr_file['file_size'];
$type = $curr_file['file_type'];
$name = $curr_file['file_name'];
$content = $curr_file['file_content'];
header("Content-length: ".$size."");
header("Content-type: ".$type."");
header('Content-Disposition: attachment; filename="'.$name.'"');
readfile($content);
$_SESSION['email']=$nemail;
mysqli_close($con);
}
?>
I named the above PHP file getfile.php and I'm getting on download result as getfile.htm.
Debug!
Comment out the headers and see, what really gets to the client. Then comment them in and check in browser dev console (header + response).
You're also vulnerable to SQL injections.

blob in data module

I am using the data module in drupal 7 and i created a view which shows my table.
But I have a blob in my table and this is filling my page with content.Is there any way that I can get the blob to display as a link and the file must be downloaded when clicked.
Also is it possible for the data module to access tables in a different database than the default drupal database mentioned in settings.php.I added another database in the settings.php which has the required table but I am not able to adopt tables from there.(They do not show up in the orphaned tables list).Is there a place where I can change so that the data module only sees the new database and not the default database
Fixed the first problem by doing this in the theme.inc
if($vars['fields'][$field] == 'content')
{
$field_output = "<form action=\"download.php\"
method=\"POST\">
<input type=\"submit\" name=\"download\" value=\"Download\">
<input type=\"hidden\" name=\"did\" value=\"$num+1\">
</form>";
}
and download.php needs to have something like this
<?php
if(isset($_POST['id']))
{
$table = 'tablename';
$download_id = $_POST['id'];
$q="SELECT * FROM {$table} where id = $download_id";
$link = mysqli_connect(...);
$res = mysqli_query($link,$q);
if($res)
{
$row = mysqli_fetch_assoc($res);
$id = $row['id'];
$name = $row['name'];
$status = $row['status'];
$content = $row['content'];
header("Content-type: required type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
else{
echo "Cannot download";}
}
?>
I am still unable to fix the second problem.

Categories