Not inserting data into the database - php

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

Related

Volley upload image using 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
}

mysql image upload blob keeps coming up with hard to read error

I am trying to create a image upload part of my website and it keeps giving this error
"Could not enter data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '’8°€OIßûü ÷ÞÝuÀBjöÁ› ' at line 1" I dont understand what it means. My php code is
<?php
require('php/connect.php');
$title = $_POST['title'];
$price = $_POST['price'];
$desc = $_POST['desc'];
$answer = $_POST['radiog_dark'];
$nulll = "null for now";
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
$sql = "INSERT INTO items ".
"(title, price, shipping, description, sellerid, date, imagename, image) ".
"VALUES('$title','$price', '$answer', '$desc', '$nulll', CURDATE(), '$imageName', '$imageData')";
$retval = mysql_query( $sql, $dbhandle );
if (substr($imageType,0,5) == "image") {
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
} else {
echo "Oh No Something Went Wrong! :(";
}
mysql_close($dbhandle);
?>
I think it is a problem with the image stuff because it worked fine before :(
Thank You To All That Could Help!
Because you are entering invalid character like this '’8°€OIßûü ÷ÞÝuÀBjöÁ› first use utf-8 and second put mysql_real_escape, and also try to use this
str_replace("'","''",var); //this code find the single quote and replace 2 quote to save in db
i think that should do

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.

Convert mysql_* to PDO

I have made a program using PHP and trying to store data into Local Server Xampp, but whenever i run my php script using this url:
http://127.0.0.1/test.php
Getting error message: {"StatusID":"0","Error":"Cannot save data!"}
Please someone help me in this how can i make it useful for me, please check below PHP Script:
<?php
$objConnect = mysql_connect("localhost","root","");
mysql_error($ObjConnect);
$objDB = mysql_select_db("registration_login");
mysql_error($ObjDB);
$strUsername = $_POST["sUsername"];
$strPassword = $_POST["sPassword"];
$strName = $_POST["sName"];
$strEmail = $_POST["sEmail"];
$strTel = $_POST["sTel"];
/*** Insert ***/
$strSQL = "INSERT INTO member (Username,Password,Name,Email,Tel)
VALUES (
'".$strUsername."',
'".$strPassword."',
'".$strName."',
'".$strEmail."',
'".$strTel."'
)
";
$objQuery = mysql_query($strSQL);
mysql_error($ObjQuery);
if(!$objQuery)
{
$arr["Status"] = "0";
$arr["Message"] = "Cannot Save Data!";
echo json_encode($arr);
exit();
}
else
{
$arr["Status"] = "1";
$arr["Message"] = "Register Successfully!";
echo json_encode($arr);
exit();
}
mysql_close($objConnect);
?>
Note: I have created registration_login database and member table under this DB..
Why don't you return the error reported by mysql or log it somewhere?
$objConnect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
You forgot to check the return the return value to see if this was successful - if it failed, the reason is in mysql_error()
$objDB = mysql_select_db(DB_DATABASE);
You forgot to check the return the return value to see if this was successful - if it failed, the reason is in mysql_error()
$objQuery = mysql_query($strSQL);
At least this time you check the return value - but you don't check what the error was.
BTW your script is wide open to SQL injection.
Convert mysql_* to PDO
What has that got to do with your post?

Image upload in a database directory

i am little bit problem in Image upload in a database directory.image upload my avatar folder and can't show my page becouse problem is that in database id, username table show my data but imagelocation table can't show my directory.please any one told me that, what is the problem in my code and correct it specify line
upload.php
<?php
include("connecton.php");
$_SESSION['username']="kyle";
$username = $_SESSION['username'];
if($_POST['submit'])
{
//get file attribute
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if($name)
{
//start upload process
$location = "avatars/$name";
move_uploaded_file($tmp_name,$location);
$query = mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");
die("Your avatar has been uploaded! <a href='view.php'>HOme</a>");
}
else
die("Please select a file");
}
echo "Welcome, ".$username."!<p>";
echo "Upload Your Image:
<form action='upload.php' method='POST' enctype='multipart/form-data'>
File: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload!'>
</form>
";
?>
view.php
<?php
include("connecton.php");
$username = $_SESSION['username'];
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($query)==0)
die ("User not found");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
echo "<img src='$location' width='100' height='100'>";
}
?>
a) You do not check if the upload succeeded. At least do something like:
if ($_FILES['myfile']['error'] === UPLOAD_ERR_OK) {
... upload went ok
}
b) You're using the original user's filename to store it on your server, and you do not sanitize the filename. THere is NOTHING to prevent a malicious user from setting a filename such as ../../../../../../../../../some/critical/system/file, which your script will then happily overwrite.
c) You do not check of the move_uploaded_file() succeeded:
if (!move_uploaded_file(...)) {
die("Move failed!")
}
d) You do not check if the database query succeeded:
$stmt = mysql_query(...)
if ($stmt === FALSE) {
die("MySQL query failed: " . mysql_error());
}
e) You've not sanitized the $filename, so again a malicious user can subvert your query and directly attack your database with SQL injection attacks.
f) You're doing a SELECT * FROM... to get the image's location. Are you sure your table contains an 'imagelocation' row? YOU didn't check if the insert query succeeded using the same row, so maybe you've got a typo and it's really "imglocation" instead.
First php statement of both of upload.php and view.php should be this:
session_start();

Categories