Volley upload image using PHP - php

I am trying to upload image from android app using Google Volley to the server but for some reason the SQL command to insert the URL to database and upload doesn't work. The rest of the commands as well as the code in android seems to be working. But the response is incorrect. Check the else statement below highlighted by comment, that statement is executed for some reason whatever I do.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$name = $_POST['name'];
...
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect to db');
$sql ="SELECT id FROM volleyupload ORDER BY id ASC";
$res = mysqli_query($conn,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.png";
$actualpath = "http://myurl.co/prak/$path";
$sql = "INSERT INTO volleyupload (photo,name) VALUES ('$actualpath','$name')";
if(mysqli_query($conn,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
} else{
echo "ERROR in insertion to DB!"; //THIS ERROR COMES UP
}
mysqli_close($conn);
}else{
echo "Error";
}
?>
The tutorial I am following for volley image upload is here: https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
Please let me know what's the problem and if there is an issue with the question do let me know that as well.

Fact that else branch is always entered means that mysqli_query($conn,$sql) function result is FALSE.
This is most likely caused by problem with your SQL statement. Fortunately there is a way to find out where exactly the problem origins - you can use mysqli_error($conn) to find out where the issue is exactly.
Possibly by adjusting your code to something like this:
if(mysqli_query($conn,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
} else{
echo "ERROR in insertion to DB:" . mysqli_error($conn); //THIS ERROR COMES UP
}

Related

Undefined index image in PHP, I know this is duplication but I have tried many solution but none worked

I want to make an application in android where user uploads photo and that uploads will be inserted in my MySQL database using PHP
but my PHP script generates an error that
Undefined index image in PHP
following is my PHP files-
"Constants.php"
<?php
$db_name="mydb";
$local_username="root";
$local_password="";
$server_name="localhost";
$conn=
mysqli_connect($server_name,$local_username,$local_password,$db_name);
if($conn)
{
echo "Connection successful";
}
else
{
echo "Connectionj failed";
}
?>
"imageUploadScript.php"
<?php
require "Constants.php";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$DefaultId = 0;
$image = $_POST['image'];
$mobile = $_POST['mobile'];
// if(isset($_POST['image']))
//{
$ImagePath = "imageUploads/$mobile.jpg";
$ServerURL = "yourPath/$ImagePath";
$InsertSQL = "INSERT INTO info (img) values('$ServerURL') where
mobile=$mobile";
if(mysqli_query($conn, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($ImageData));
echo "Your Image Has Been Uploaded.";
mysqli_close($conn);
}
else{
echo "Please Try Again";
}
//}
}
?>
any help from your side will be appreciated
For uploading an image, you need to use
$_FILES['image']
instead of
$_POST['image']

Upload image to server from android volley via php

I am trying to upload an image to my server but can't seem to get it to work. I am using android and volley to get the image and then sending it to the php to upload.
I am using wamp as well.
Says "successfully uploaded" but is not in the directory?
PHP CODE:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$username = $_POST['username'];
require_once('dbConnect.php');
$sql ="SELECT profilepictureID FROM tbl_userprofilepictures ORDER BY profilepictureID ASC";
$res = mysqli_query($con,$sql);
$profilepictureID = 0;
while($row = mysqli_fetch_array($res)){
$profilepictureID = $row['profilepictureID'];
}
$path = "000001/$profilepictureID.JPG";
$actualpath = "http://*wamp server ip*/Users/Images/$path";
$sql = "INSERT INTO tbl_userprofilepictures(username,profilepicturepath) VALUES ('$username','$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
} else{
echo "Error";
}
?>

IMG dir can't be stored in db but viewed from the same variables used in query

I'm trying to upload an image to my server using the following form by Sanwebe.
Can be found here.
However when I'm pressing upload, the new thumb loads perfectly fine. However, my image can't be uploaded to the database using the exact same variables from which the image is being viewed. How come?
I tried putting the db information just infront of the query. Like this:
echo '<div align="center">';
echo '<img src="images/profile-pictures/'.$thumb_prefix . $new_file_name.'" alt="Thumbnail">';
echo '</div>';
$profile_pic_temp = "../images/profile-pictures/" . $thumb_prefix . $new_file_name;
$profile_pic_full_temp = "../images/profile-pictures/" . $new_file_name;
$session_user = $_SESSION['user_confirm'];
require 'database.php';
$profile_pic_db_upload = $db->prepare("UPDATE login SET profile_picture_temp = :profile_pic_temp, profile_picture_full_temp = :profile_pic_full_temp WHERE user_session = :session_user");
$profile_pic_db_upload->bindParam(':session_user', $session_user, PDO::PARAM_STR);
$profile_pic_db_upload->bindParam(':profile_pic_temp', $profile_picture_temp, PDO::PARAM_STR);
$profile_pic_db_upload->bindParam(':profile_pic_full_temp', $profile_picture_full_temp, PDO::PARAM_STR);
$profile_pic_db_upload->execute();
$confirm_upload_db = $profile_pic_db_upload->rowCount();
if($confirm_upload_db != 0){
$popup_message = "Profile picture has been uploaded.";
echo $popup_message;
}
else{
$popup_message = "Profile picture could not be uploaded.";
echo $popup_message;
}
EDIT TWO:
The query now runs, however, I get the feedback "Profile picture could not be uploaded.". How come the query does not run properly?
EDIT FOUR:
I have tried changing the user_session = :session_user to id = 1 instead. I then get upload successfull, however, the value is only inserted into profile_picture_temp and is set to 0. Somehow the bindParam changes the value. Why?
EDIT THREE:
I have now tried using mysqli aswell. Same results here. Returning could not be uploaded. However, does not change value in DB.
$sql = "UPDATE login SET profile_picture_temp = ? AND profile_picture_full_temp = ? WHERE user_session = ?";
$stmt = $mysqli->prepare($sql) or die ("Database error<br>" . $sql . "<br><b>Error message:</b> " . $mysqli->error);
$stmt->bind_param("sss", $profile_picture_temp, $profile_picture_full_temp, $session_user);
$stmt->execute() or die("Something went wrong");
if($stmt->fetch()){
$popup_message = "Profile picture has been uploaded.";
echo $popup_message;
}
else{
$popup_message = "Profile picture could not be uploaded.";
echo $popup_message;
}
$stmt->free_result();
$stmt->close();
Are you sure this line isn't throwing a PHP error...
$confirm_upload_db = $$profile_pic_db_upload->rowCount();
^^
The $$ (two dollar signs) are how we reference a variable variable; but $profile_pic_db_upload doesn't contain the name of another variable, it's a reference to a PDO statement object.
Another note. The rowCount() function returns the number of rows affected by the UPDATE statement; if the UPDATE statement succeeds, but no actual changes are made to the row (because the values assigned to the columns are the same as what's already stored in the columns), then rowCount() will return 0.
(To change that behavior, to have it return the number of matched rows, you can use PDO::MYSQL_ATTR_FOUND_ROWS).
The problem was fixed using the following query:
$profile_picture_temp = "../images/profile-pictures/" . $thumb_prefix . $new_file_name;
$profile_picture_full_temp = "../images/profile-pictures/" . $new_file_name;
$session_user = $_SESSION['user_confirm'];
$sql = "UPDATE login l SET l.profile_picture_temp = ?, l.profile_picture_full_temp = ? WHERE l.user_session = ?";
$stmt = $mysqli->prepare($sql) or die ("Database error<br>" . $sql . "<br><b>Error message:</b> " . $mysqli->error);
$stmt->bind_param("sss", $profile_picture_temp, $profile_picture_full_temp, $session_user);
$stmt->execute() or die("Something went wrong");
$result = $stmt->affected_rows;
if($result == 1){
$popup_message = "Profile picture has been uploaded.";
echo $popup_message;
}
else{
$popup_message = "Profile picture could not be uploaded.";
echo $popup_message;
}
$stmt->free_result();
$stmt->close();
I can't identify the problem itself, however, I managed to fix it by adding UPDATE login l. Using alias fixed it somehow.

Not inserting data into the database

I am trying to create a form that require to retrieve the information about an employee then the employee enter their expenses claim. The process of retrieving data is work correctly, but it is not saving the entered data of expenses claim into the database.
I would be most grateful if anybody could help me.
This is my code.
<?php
session_start();
if($_SESSION['emp_no']){
echo "Welcome, ".$_SESSION['emp_no']."!";
}
else
die("You must enter your employee no. ");
$connect = mysql_connect("localhost","root","Omaima2010") or die ("Could not connect");
mysql_select_db("expenses") or die ("Could not find the data base");
$emp_no= $_SESSION['emp_no'];
$query = mysql_query("select e.emp_no, e.manager_no, e.emp_name, m.manager_no, m.manager_name, m.dept_name
from employee e , manager m
where emp_no = '$emp_no' and e.manager_no = m.manager_no");
while($query1 = mysql_fetch_array($query)){
$emp_no = $query1['emp_no'];
$emp_name = $query1 ['emp_name'];
$manager_name = $query1 ['manager_name'];
$manager_no = $query1 ['manager_no'];
$dept_name = $query1 ['dept_name'];
}
if(isset($_POST['exp_desc'])){
//This is the directory where vouchers will be saved
$target = "vouchers/";
$target = $target .basename( $_FILES['datafile']['name']);
$exp_desc = $_POST['exp_desc'];
$date = (date ("d/m/Y"));
$receipt = $_FILES['datafile']['name'];
$amount = $_POST['amount'];
$exch_rate= ($_POST['exch_rate']);
$bd = ($_POST['BD']);
mysql_query("INSERT INTO expenses_claim(emp_no,manager_no,exp_desc,claimant_date,amount,exch_rate,BD,receipt) VALUES ('$emp_no','$manager_no','$exp_desc','$date','$amount','$exch_rate','$bd','$receipt',now())");
//Writes the file to the server
if(move_uploaded_file($_FILES['datafile']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file " . basename( $_FILES['datafile']['name']). " has been uploaded";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
You have 8 columns and 9 values in your query,just delete ,now()
Use prepared statements. Also mysql_query is depreciated as of PHP 5.5, so you should switch to mysqli or PDO.
Validate your input. I'd wager that your problem is the result of bad input causing the query to fail.
If you're sending a query that could fail, make sure to catch your error. For example:
if(!mysql_query($query))
echo "Your query failed. It consisted of: $query and the error was " . mysql_error();

How can I have a upload auto linked in a mysql table

I have a form that uploads a file with other information to a database and displays it in a chart. Right now the chart only displays the file name and doesen't link it. If the file was called test1.pdf, how would I make it so on the chart it still says chart1.pdf but links it to the directory that the file is on?
if ('POST' === $_SERVER['REQUEST_METHOD'])
{
$con = mysql_connect("localhost","xxxx","xxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jjlliinn_test", $con);
$target = "clientdoc/";
$target = $target . basename( $_FILES['file']['name']);
$date = $_POST['date'];
$propertydescription = $_POST['propertydescription'];
$transactiontype = $_POST['transactiontype'];
$applicabledocument = ($_FILES['file']['name']);
$received = $_POST['received'];
$paid = $_POST['paid'];
//Writes the to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
//Tells you if its all ok
echo "";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
$sql = mysql_query("INSERT INTO `transactions` (`date`, `agentclient`, `propertydescription`, `transactiontype`, `applicabledocument`, `received`, `paid`)
VALUES
('$date', '$agentclient', '$propertydescription', '$transactiontype', '$applicabledocument', '$received', '$paid')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"48\">";
mysql_close($con);
}
}
?>
Assuming all your uploads are stored in the client doc folder and you have run the query to get the recordset from the transactions table...
link text
Another point, looking at the code, sending raw $_POST values direct to the db is asking for sql injection trouble. Have a look at either htmlentities with ENT_QUOTES set or the input filters available with php.

Categories