So I'm using http://www.verot.net/php_class_upload_docs.htm?lang=en-GB to upload files to a mysql database. I'm a little new at mysql so please forgive my ignorance.
the below code snippet uploads the image, renames it properly, but stores the old file name in the database table.
include('class.upload.php');
$t = time();
$foo = new Upload($_FILES['receipt_u']);
if ($foo->uploaded) {
$foo->file_new_name_body = "img_$t";
$foo->file_max_size = '4194304'; //4MB
$foo->Process('pics');
}
$receipt_img =($_FILES['receipt_u']['name']);
$sql = "INSERT INTO product (receipt_u) VALUES (:rcpt)";
$q = $conn->prepare($sql);
$q->execute(array(':rcpt'=>$receipt_img));
header("location: ../index.php");
There's actually a lot of data be passed into the database but I removed it for this purpose as this is the only thing giving me trouble.
Why is it posting the original file name into the database and not the new one?
Simple:
echo $foo->file_dst_name;
your new code looks like:
$t = time();
$foo = new Upload($_FILES['receipt_u']);
if ($foo->uploaded) {
$foo->file_new_name_body = "img_$t";
$foo->file_max_size = '4194304'; //4MB
$foo->Process('pics');
}
//here its recipt image new
$receipt_img = $foo->file_dst_name;
$sql = "INSERT INTO product (receipt_u) VALUES (:rcpt)";
$q = $conn->prepare($sql);
$q->execute(array(':rcpt'=>$receipt_img));
header("location: ../index.php");
Related
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 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;
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.
look at this code
<?
require_once("conn.php");
require_once("includes.php");
require_once("access.php");
if(isset($_POST[s1]))
{
//manage files
if(!empty($_FILES[images]))
{
while(list($key,$value) = each($_FILES[images][name]))
{
if(!empty($value))
{
$NewImageName = $t."_".$value;
copy($_FILES[images][tmp_name][$key], "images/".$NewImageName);
$MyImages[] = $NewImageName;
}
}
if(!empty($MyImages))
{
$ImageStr = implode("|", $MyImages);
}
}
$q1 = "insert into class_catalog set
MemberID = '$_SESSION[MemberID]',
CategoryID = '$_POST[CategoryID]',
Description = '$_POST[Description]',
images = '$ImageStr',
DatePosted = '$t',
DateExp = '$_SESSION[AccountExpDate]',
FeaturedStatus = '$_POST[sp]' ";
//echo $q1;
mysql_query($q1) or die(mysql_error());
}
//get the posted offers
$q1 = "select count(*) from class_catalog where MemberID = '$_SESSION[MemberID]' ";
$r1 = mysql_query($q1) or die(mysql_error());
$a1 = mysql_fetch_array($r1);
header("location:AddAsset.php");
exit();
?>
The mySql insert function isn't adding anything also it return success to me , I've tried using INSERT ... Values but what it done was overwtiting existing value ( i.e make 1 entry and overwties it everytime).
I am using PHP 4.4.9 and MySql 4
I tried to add from Phpmyadmin and it is working also it was working after installation but after i quit the browser and made a new account to test it it is not working but the old ones is working ! you can see it here http://bemidjiclassifieds.com/
try to login with usr:openbook pass:mohamed24 and you can see it will be working but any new account won't work!
Maybe $_POST[s1] is not set or you are inserting into a different database than you are watching.
if(isset($_POST[s1]))
should probably be
if(isset($_POST['s1']))
(note the quotes). Also, it's best to NOT depend on a field being present in the submitted data to check if you're doing a POSt. the 100% reliable method is
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
As well, you're not checking if the file uploads succeeded. Each file should be checked like this:
foreach($_FILES['images']['name'] as $key => $name) {
if ($_FILES['images']['error'][$key] !== UPLOAD_ERR_OK) {
echo "File #$key failed to upload, error code {$_FILES['images']['error'][$key]}";
}
...
}
Don't use copy() to move uploaded files. There's a move_uploaded_files() function for that, which does some extra sanity checking to make sure nothing's tampered with the file between the time the upload finished and your script tries to move it.
This is an extension of a question I asked a wee while ago which #eHussain was nice enough to help out with.
I have form which inserts various details into a MySQL table and uploads a file (the name of which is also registered in the database). This works fine. The issue comes when I update, say, the name and not the image. In this case the image name is over written as 'blank', and rightly so as that's the value in the file field.
The update code:
<?php
error_reporting(E_ALL^E_NOTICE);
define('INCLUDE_CHECK',true);
include "connect.php";
$target = "../uploads/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$url=$_POST['url'];
$description=$_POST['description'];
$pic=($_FILES['photo']['name']);
$author=$_POST['author'];
$company=$_POST['company'];
$published=$_POST['published'];
$dashboardID=$_POST['dashboardID'];
//Writes the information to the database
mysql_query("UPDATE dashboard SET name='$name', url='$url', description='$description', documentName='$pic', author='$author', company='$company', publish='$published' WHERE dashboardID='$dashboardID'");
//Writes the photo to the server
if(isset($_FILES['photo']['tmp_name'])) // check if any file is uploaded
{
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
header("Location: ../dashboard.php?success=2"); } else {
header("Location: ../dashboard.php?success=0"); }
}
?>
I understand the 'isset' to avoid a the error generated if no file is selected, but I don't understand how I can extent this to avoid updating a field which has a blank value.
Do a check on the $_FILES array before running the query.
From there, you can either dynamically build the query (including or excluding the documentName field) or alternatively, fetch the current value and assign it to $pic.
For example (untested)
$values = array(
'name' => $name,
'url' => $url,
// etc
);
if (isset($_FILES['photo']['name'])) {
$values['documentName'] = $_FILES['photo']['name']
}
// mysql functions are naff, use PDO
$query = 'UPDATE dashboard SET %s WHERE dashboardID = :dashboardID';
$set = array();
foreach (array_keys($values) as $col) {
$set[] = sprintf('`%s` = :%s', $col, $col);
}
$stmt = $pdo->prepare(sprintf($query, implode(', ', $set)));
$values['dashboardID'] = $dashboardID;
$stmt->execute($values);
#rrfive , please try below method, hope it will work,
//first put all post variable in an array
$post_data = compact($_POST);
$pic=($_FILES['photo']['name']);
//now push pic name in `$post_data`
if (!empty($pic) ) { array_push( $post_data,$pic ) }
//now use UPDATE query using `vsprintf` . but first check the order of `$post_data` #Thanks Phill
$stmt = "UPDATE dashboard SET
name='%s',
url='%s',
description='%s',
author='%s',
company='%s',
publish='%s'";
$stmt .=(!empty($pic)) ? documentName='%s', : "";
$stmt .= "WHERE dashboardID=%d";
// To check the complete query before execute. uncomment below 2 lines
//print vsprintf($stmt,$post_data);
//die;
mysql_query( vsprintf($stmt,$post_data) );
Reference
- compact
- vsprintf
The following code should do the trick.
if(isset($_FILES)){
...stuff...
}