-1

In my php script, I am attempting to store a random file name in my MySQL database. However, when I call the variable, nothing is posted to the table. If I change $filetest to a string i.e. 'image12462983764', it will post as expected. Does anyone know why I might have this problem? Please see code below:

<?php
//receive image data, convert from base64 to png, write to server
$rawimagedata = $_POST["varPOST"];
$rawimagedata = str_replace(' ', '+', $rawimagedata);
$decoded = base64_decode($rawimagedata);
$filerand ="image" . rand(0,999) . rand(0,999) . rand(0,999);
$filename =$filerand . ".png";
file_put_contents($filename , $decoded);

//receive device location data
$userlat = $_POST["latitude"];
$userlon = $_POST["longitude"];

echo $userlat;
echo $userlon;
echo $filename;
echo $filerand;

$con=mysqli_connect("localhost","myuser","mypassword","Mydatabase");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  } 

$filetest = mysqli_real_escape_string($filerand);
// Perform queries 
mysqli_query($con,"INSERT INTO photos (username,lat,lon,photourl) 
VALUES ('myusername',$userlat,$userlon,$filetest)");

mysqli_close($con);
?>
  • Possible duplicate of [How can I prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – chris85 Apr 26 '17 at 21:37
  • `mysqli_real_escape_string` requires a connection string. It also doesn't handle encapsulating the value in quotes. Parameterize the query and you'll be good to go. No need to escape. You also should check that the query executed successfully, and if not check for errors. – chris85 Apr 26 '17 at 21:38
  • if its string use qoute around it, i am talking about variable in the instert query and secon, in the values `'myusername'` i am guessing you are missing dollar sign it should be `'$myusername'` – user2860957 Apr 26 '17 at 21:39

1 Answers1

-1

You should use quotes:

mysqli_query($con,"INSERT INTO photos (username,lat,lon,photourl) 
    VALUES ('myusername',$userlat,$userlon,'$filetest')");
                                           ^         ^

By the way, your code is vulnerable to SQL injection. You should use prepared statement.

Felippe Duarte
  • 14,197
  • 2
  • 24
  • 27
  • 1
    Flipping this to use prepared statements is the real fix. This just prolongs the inevitable. – tadman Apr 27 '17 at 01:03