PHP - getting image from database - php

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;

Related

How to get information from database file, and retrieve that information in the website file?

I'm in the process of doing a "mock" website for a class and I'm having issues getting the information from my database file, to the actual page in my site. I should mention that I'm a total php newb. Also there isn't any security yet.
I'm calling the connection from another file, so I didn't include that.
database function:
function GetProductsByCategory($categoryID) {
global $conn, $productsResult;
echo $categoryID;
$sql = "SELECT * FROM products WHERE prodCategory = '$categoryID'";
$productsResult = $conn->query($sql);
}
Website File:
//In the head of website file
<?php
$categoryID = "87";
if (isset($_GET['category'])) {
GetProductsByCategory($categoryID);
} else {
// Fallback behaviour goes here
}
?>
//In the body
<?php while ($row = $productsResult->fetch_assoc()) {
//Just trying to get information from the database file
echo '<div>'.$row["prodName"].'</div>';
}
?>
I should mention that nothing throws an error, It echos out the category ID at the top, but inside the <div> it just doesn't show anything.
Call the function and save the result in a variable:
$result = GetProductsByCategory($categoryID);
then inside the function:
$productsResult = $conn->query($sql);
return $productsResult;
then your while loop should use this returned result (i.e., $result):
while ($row = $result->fetch_assoc()) { ... }

How to add image php file from MAMP server

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

get json data in function php

I am new in this json chapter.I have a file named mysql_conn.php .This file have a php function to call data from mysql database.So can anyone help me to create one json file to get data from mysql_conn.php.Below is my code
mysql_conn.php
function getWrkNoTest($wrkno){
$conf = new BBAgentConf();
$log = new KLogger($conf->get_BBLogPath().$conf->get_BBDateLogFormat(), $conf->get_BBLogPriority() );
$connection = MySQLConnection();
$getWrkNoTest ="";
$lArrayIndex = 0;
$query = mysql_query("
SELECT
a.jobinfoid,
a.WRKNo,
a.cate,
a.det,
a.compclosed,
a.feedback,
a.infoID,
b.callerid,
b.customername
FROM bb_jmsjobinfo a
LEFT JOIN bb_customer b
ON a.customerid = b.customerid
WHERE a.WRKNo = '$wrkno';"
);
$result = mysql_query($query);
$log->LogDebug("Query[".$query."]");
while ($row = mysql_fetch_array($result)){
$getWrkNoTest = array("jobinfoid"=>$row['jobinfoid'],
"WRKNo"=>$row['WRKNo'],
"cate"=>$row['cate'],
"det"=>$row['det'],
"compclosed"=>$row['compclosed'],
"feedback"=>$row['feedback'],
"infoID"=>$row['customerid'],
"customerid"=>$row['infoID'],
"callerid"=>$row['callerid'],
"customername"=>$row['customername']);
$iList[$lArrayIndex] = $getWrkNoTest;
$lArrayIndex = $lArrayIndex + 1;
}
$QueryResult = print_r($getWrkNoTest,true);
$log->LogDebug("QueryResult[".$QueryResult."]");
closeDB($connection);
return $iList;
}
json.php
if ($_GET['action']=="getJsonjms"){
$wrkno = $_GET["wrkno"];
if($wrkno != ""){
$jms = getWrkNoTest($wrkno);
if(!empty($jms)){
echo json_encode($jms);
}else{
echo "No data.";
}
}else{
echo "Please insert wrkno";
}
}
I dont know how to solve this.Maybe use foreach or something else.Sorry for my bad english or bad explanation.I'm really new in this json things. Any help will appreciate.Thanks
If I understand your question right, you want to convert the results you receive from your MySQL query into JSON and then store that data into a file?
If this is correct, you can build off of what you currently have in json.php. In this block here, you use json_encode():
if(!empty($jms)){
echo json_encode($jms);
}
We can take this data and pass it to file_put_contents() to put it into a file:
if (!empty($jms)) {
$json = json_encode($jms);
// write the file
file_put_contents('results.json', $json);
}
If this is a script/page that's visited frequently, you'll want to make the filename (above as results.json) into something more dynamic, maybe based on the $wrkno or some other schema.

Viewing Image from database

I have a file in which a user can view its stored files. I want that only the logged in user and it can only be viewed by that member who has stored that file. It works fine when I view other files like .html, .txt etc. But when I view any image, it doesn't work.
This is my script :
require ('config.php');
$id = intval($_GET['id']);
$dn2 = mysql_query('select authorid from files where uploadid="'.$id.'"');
while($dnn2 = mysql_fetch_array($dn2))
{
if(isset($_SESSION['username']) and ($_SESSION['userid']==$dnn2['authorid'] or $_SESSION['username']==$admin)){
$query = "SELECT data, filetype FROM files where uploadid=$id"; //Find the file, pull the filecontents and the filetype
$result = MYSQL_QUERY($query); // run the query
if($row=mysql_fetch_row($result)) // pull the first row of the result into an array(there will only be one)
{
$data = $row[0]; // First bit is the data
$type = $row[1]; // second is the filename
Header( "Content-type: $type"); // Send the header of the approptiate file type, if it's' a image you want it to show as one :)
print $data; // Send the data.
}
else // the id was invalid
{
echo "invalid id";
}
}
}
How can I view the image?

Multiple save on upload plus save on database errors

I have set of questions have you ever encounter some issues when multiple save on database?my problem is this, i have a database called "album" where fields are 'album_id,album_title,album_user'.
The html output would be there is a login section where there is a input type file where you want to add more and once you have uploaded it. and array of set of names will be stored and that array will be our que to save the file on the multiple format the problem is that. it says and error on the database whichs is sql specified twice.Do you have an idea on how to save in multiple using php?
code will be like this.
<?php
class Album extends olib{
function __construct(){
parent::olib();
}
function upload_submit() {
$allow = array("jpg","png","gif");
$directory = "upload";
$pictures = array();
$counter = 0;
$error = '';
if($this->jpost('upload')) {
for($getupload = 0;$getupload<count($_FILES['uploadpictures']['name']);$getupload++){
$extension = end(explode(".",$_FILES['uploadpictures']['name'][$getupload]));
if(in_array(strtolower($extension),$allow)){
if(move_uploaded_file($_FILES['uploadpictures']['tmp_name'][$getupload],$directory."/".$_FILES['uploadpictures']['name'][$getupload])){
$pictures[$getupload] = $_FILES['uploadpictures']['name'][$getupload];
$counter++;
// $this->save_user_album($_FILES['uploadpictures']['name'][$getupload],$this->setSession('user_id'));
}else{
$error[$getupload] = "Sorry seems some of the data invalid";
}
}else{
$error = '1';
}
}
print_r($pictures);
print_r($error);
foreach($pictures as $urpics){
$this->save_user_album($urpics,$this->setSession('user_id'));
}
}
}
function save_user_album($albumtitle,$session){
$_firewall = ($this->setSession('user_id') !=="") ? $this->setSession('user_id') : "";
$this->jfields('album_pics_title',$albumtitle);
// $this->jfields('album_pics_user',$session);
return $this->jSave('album_pics');
}
}
any response will greatly appreciated!!
Hi I'm sorry seems i have a solution for this i have unset after it has been save..
unset($this->jfields); problem has been solved

Categories