I am trying to store image file names to a SQL database. The file name looks something like "_p4_analyzed__07001447_20121003-4000096925_Class2_reg_EPI.png" and I was hoping that it would be just "Class2_reg_EPI.png".
I was hoping that this line will do the trick: $fileName = str_ireplace($casePath."/","", $file) but unfortunately when I run it it is still giving me the long name with the path (the '_' underscore acts as the '/'?)
See code below for more information:
$casePath=$path."/".$caseID."/Summary/slicesdir";
global $status;
// print("processImages case path:".$casePath."</br>");
$files = glob($casePath."/*.png");
$connection = getMySqlConnection();
$imageCount= 0;
for($i = 0; $i < count($files); $i++) {
$file = $files[$i];
$fileName = str_ireplace($casePath."/","", $file);
if(strripos($fileName, "grot") === false)
{
$imageCount ++;
//if exists
if(!doesImageExist($fileName, $patientID, $caseID)) {
$id = uniqid("", true);
$sql = "Insert Into images(id,patientid,caseid, image_name,comments,status) VALUES('".mysql_real_escape_string($id)
."','".mysql_real_escape_string($patientID)."','".mysql_real_escape_string($caseID)."', '".mysql_real_escape_string($fileName)."',NULL,".$status[0][0].")";
// print($sql."</br>");
mysql_query("START TRANSACTION", $connection);
$result = mysql_query($sql, $connection);
if($result) {
mysql_query("COMMIT", $connection);
// print("Image data inserted </br>");
} else {
mysql_query("ROLLBACK", $connection);
print("Image Data failed </br>");
}
}
}
}
Any help is appreciated! Thanks in advance!
If the original filename contains path information (e.g. /path/to/the/file.png), and you only want the filename (file.png), you can remove the path using basename()
$filename = basename('/path/to/file.png');
echo $filename; // outputs 'file.png'
Related
I'm working on getting images from the database, which I've been saving as an url from the server it's been getting saved on.
There's this upload image section on the form, which is saving the images on a server and its url is getting saved in the database.
Here's the code:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= $target_file_cv;
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>
Here, I want to edit the file Name before it goes to the database. Like now it is saving as "/home/web/newsletter/uploads/pic.jpg" but I want it to be saved as "newsletter/uploads/pic.jpg".
I referred to a few questions here and got everything else working but just got stuck at hard coding the file's name here. Any help would be appreciated. TIA
$fileName = implode(array_slice(explode("/",$target_file_cv),3),"/");
Okay I got it:
Changed the code to:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= "newsletter/uploads/" . $_FILES['fileToUpload']['name'];
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>
I have this PHP code in which I try to edit a row in the database
$sql="SELECT * FROM `event` where `EId`='".$_GET['EId']."'";
$res=$conn->query($sql);
$numrows=mysqli_num_rows($res);
if ($numrows>0)
{
$obj = mysqli_fetch_object($res);
}
if ($_REQUEST["mode"]=="save")
{
if ($_FILES['image']['name']!="")
{
del_img("event/",$obj->Picture);
$Picture=post_img($_FILES['image']['name'], $_FILES['image']['tmp_name'],"event");
}
else
$Picture = $obj->Picture;
$sqlu="update event set Picture='".$Picture."' where EId='".$_POST['EId']."'";
$conn->query($sqlu);
header("refresh:1; url=event_view.php");
die();
}
function post_img($fileName,$tempFile,$targetFolder)
{
if ($fileName!="")
{
if(!(is_dir($targetFolder)))
mkdir($targetFolder);
$counter=0;
$NewFileName=$fileName;
if(file_exists($targetFolder."/".$NewFileName))
{
do
{
$counter=$counter+1;
$NewFileName=$counter."".$fileName;
}
while(file_exists($targetFolder."/".$NewFileName));
}
$NewFileName=str_replace(",","-",$NewFileName);
$NewFileName=str_replace(" ","_",$NewFileName);
copy($tempFile, $targetFolder."/".$NewFileName);
return $NewFileName;
}
}
function del_img($targetfolder,$filname)
{
if (file_exists($targetfolder.$filname))
{
unlink($targetfolder.$filname);
}
}
When this is executed without uploading a new image it removes the present image and saves the row without any image. When uploading a new image it does not delete the current image.
I checked with isset and it tells me that the variable $obj->Picture is not set. I used this code in an older version of PHP and it still works but I can't seem to get it to work in the current one.
I am quite sure that the problem lies with $obj but I can't seem figure out what it is.
The HTML is just a form with file upload input and I have already set up a connection to the database with $conn being a new mysqli. The reason I am taking the entire row is because I am editing other stuff too
It feels like I am committing a fundamental mistake? What am I missing?
I'd bet there is some Problem with the num_rows_function.
Try to structure the code differently or at least make sure you have obj defined and initialised when the part of your code where the object is required is reached.
Do something like this for xample:
if ($_REQUEST["mode"]=="save" && isset($obj))
{
if (($_FILES['image']['name']!=""))
{
del_img("event/",$obj->Picture);
$Picture=post_img($_FILES['image']['name'], $_FILES['image']['tmp_name'],"event");
}
else
$Picture = $obj->Picture;
$sqlu="update event set Picture='".$Picture."' where EId='".$_POST['EId']."'";
(...)
Well, here's how I would fix this up. Your whole logic was messed up; now we have only the two conditions we need: is a valid EId sent, and is a file attached?
Database API is updated to something a tiny bit more modern, queries are prepared and parameterized for security, and we are properly sanitizing user input before using it to name files.
<?php
$conn = new PDO("mysql:host=localhost;dbname=database", "user", "password");
$stmt = $conn->prepare("SELECT Picture FROM event WHERE EId = ?");
$result = $stmt->execute([$_POST["EId"]]);
if ($obj = $stmt->fetch(\PDO::FETCH_OBJ)) {
if (!empty($_FILES["image"])) {
del_img("event/", $obj->Picture);
$Picture = post_img($_FILES['image'], "event");
$stmt = $conn->prepare("UPDATE event SET Picture = ? WHERE EId = ?");
$result = $stmt->execute([$Picture, $_POST["EId"]]);
}
header("Location: event_view.php");
die();
}
function post_img($file, $targetFolder)
{
if (!(is_dir($targetFolder))) {
mkdir($targetFolder);
}
$fileName = $file["name"];
$tempFile = $file["tmp_name"];
$NewFileName = str_replace([",", " "], ["-", "_"], basename($fileName));
$counter = 0;
while(file_exists($targetFolder . "/" . $NewFileName)) {
$counter += 1;
$NewFileName = $counter . $fileName;
}
move_uploaded_file($tempFile, $targetFolder . "/" . $NewFileName);
return $NewFileName;
}
function del_img($targetfolder,$filname)
{
if (file_exists($targetfolder . $filname)) {
unlink($targetfolder.$filname);
}
}
I'm getting the error message when uploading a form in php.
"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"
I've followed instructions from other posts as follows, to no avail:
1-Wrapped the column heading names in backticks.
2-Made sure all strings were passed as strings, and ints as ints.
3-Cleaned up any strings before sending out.
4-Made sure the connection to the database works and we can query from it.
5-Checked and re-checked my html code.
Here's my php code:
<?php
include('../config/config.php');
// Redirect browser if the upload form WAS NOT submited.
if (!isset($_POST['submit_upload']))
{
header("location: upload.html");
}
// Continue if the upload form WAS SUBMITED
else
{
// Set the upload directory path
$target_path = realpath( dirname( __FILE__ ) ) . "/uploads/audio/";
// Array to store validation errors
$error_msg = array();
// Validation error flag, if this becomes true we won't upload
$error_flag = false;
// We get the data from the upload form
$filename = $_FILES['file']['name'];
$temp_filename = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
$mimetype = $_FILES['file']['type'];
// Convert all applicable characters to HTML entities
$filename = htmlentities($filename);
$mimetype = htmlentities($mimetype);
// Check for empty file
if ($filename == "")
{
$error_msg[] = 'No file selected!';
$error_flag = true;
}
// Check the mimetype of the file
if ($mimetype != "audio/x-mp3" && $mimetype != "audio/mp3")
{
$error_msg[] = 'The file you are trying to upload does not contain expected data.
Are you sure that the file is an MP3 one?';
$error_flag = true;
}
// Get the file extension, an honest file should have one
$ext = substr(strrchr($filename, '.') , 1);
if ($ext != 'mp3')
{
$error_msg[] = 'The file type or extention you are trying to upload is not allowed!
You can only upload MP3 files to the server!';
$error_flag = true;
}
// Check that the file really is an MP3 file by reading the first few characters of the file
$open = #fopen($_FILES['file']['tmp_name'], 'r');
$read = #fread($open, 3);
#fclose($open);
if ($read != "ID3")
{
$error_msg[] = "The file you are trying to upload does not seem to be an MP3 file.";
$error_flag = true;
}
// Now we check the filesize.
// The file size shouldn't include any other type of character than numbers
if (!is_numeric($filesize))
{
$error_msg[] = 'Bad filesize!';
$error_flag = true;
}
// If it is too big or too small then we reject it
// MP3 files should be at least 1MB and no more than 10 MB
// Check if the file is too large
if ($filesize > 10485760)
{
$error_msg[] = 'The file you are trying to upload is too large!
Please upload a smaller MP3 file';
$error_flag = true;
}
// Check if the file is too small
if ($filesize < 1048600)
{
$error_msg[] = 'The file you are trying to upload is too small!
It is too small to be a valid MP3 file.';
$error_flag = true;
}
// Function to sanitize values received from the form. Prevents SQL injection
function clean($conn, $str)
{
$str = #trim($str);
if (get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysqli_real_escape_string($conn, $str);
}
// Sanitize the POST values
$title = clean($conn, $_POST['title']);
$context = clean($conn, $_POST['context']);
$source = clean($conn, $_POST['source']);
$interviewer = clean($conn, $_POST['interviewer']);
$interviewee = clean($conn, $_POST['interviewee']);
$intervieweeAge = (int)$_POST['intervieweeAge'];
$geoRegion = clean($conn, $_POST['geoRegion']);
$language = clean($conn, $_POST['language']);
$recDate = clean($conn,$_POST['recDate']);
$keywords = $_POST['keywords'];
if ($title == '')
{
$error_msg[] = 'Title is missing';
$error_flag = true;
}
if ($interviewee == '')
{
$error_msg[] = 'Interviewee name/anonymous is missing';
$error_flag = true;
}
// If there are input validations, show errors
if ($error_flag == true)
{
foreach($error_msg as $c => $p) echo "Error " . $c . ": " . $p . "<br />";
}
// Else, all checks are done, move the file.
else
{
if (is_uploaded_file($temp_filename))
{
// Generate an uniqid
$uniqfilename = $interviewee . '_' . str_replace("_", "", $recDate) . '.mp3';
$filePath = '/uploads/audio/' . $uniqfilename;
// If the file was moved, change the filename
if (move_uploaded_file($temp_filename, $target_path . $uniqfilename))
{
// Again check that the file exists in the target path
if (#file_exists($target_path . $uniqfilename))
{
// Assign upload date to a variable
$upload_date = date("Y-m-d");
// Create INSERT query
$qry = "INSERT INTO FDM177_AUDIO_CLIPS (title,context,source,interviewer,interviewee,intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES('$title','$context','$source','$interviewer',$interviewee',$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
if ($result)
{
$id = mysqli_insert_id($conn);
echo "File uploaded. Now it is called :" . $uniqfilename . "<br />" . $date . "<br />";
}
else
{
echo "There was an error uploading the file, please try again!";
}
if(1) {
//if (is_array($keywords) || is_object($keywords)) {
foreach($keywords as $k) {
// $idQuery = "SELECT keyword_ID from KEYWORDS WHERE keywordName=" . $k";
$idQuery = mysqli_query($conn, "SELECT * FROM FDM177_KEYWORDS WHERE (`keywordName` LIKE '%".$k."%')") or die(mysql_error());
$matchingKArray = mysqli_fetch_array($idQuery);
$keyword_FK = $matchingKArray[keyword_ID];
// echo $kQuery;
echo $keyword_FK;
$qry = "INSERT INTO FDM177_JNCT_KWDS_CLIPS (keyword_FK, clip_FK)
VALUES ('$keyword_FK', '$id')";
$result = mysqli_query($conn, $qry);
if ($result)
{
echo 'inserted with keyword.' . $k . ' <br />';
}
}
}
else {
echo "keywords are missing";
}
}
}
else {
echo "There was an error uploading the file, please try again!";
}
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
The problem occurs at the first MYSQL query that starts as MYSQL query INSERT INTO FDM177_AUDIO_CLIPS...
What am I missing?
Thank you!
quotes breaking in one query '$interviewer',$interviewee',
$qry = "INSERT INTO FDM177_AUDIO_CLIPS
(title, context, source,interviewer, interviewee,
intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES
('$title', '$context', '$source', '$interviewer', '$interviewee',
$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
As you can see in the below PHP code, I am going to get the value for a combobox from a database table. It shows all the columns of the table without any problem, but when I want to pass the value of combobox back to a table, it always passes the value 1. Why?
<?php
$leccom = mysql_query("select Lec_ID, Lec_Name from lecturer") or die(mysql_error());
while ($result = mysql_fetch_array($leccom)) {
$name = $result[Lec_Name];
$id_leccom = $result[Lec_ID];
echo "<option value='$id_leccom'> $name</option>";
}
?>
Next file:
<?php
mysql_select_db('lms', mysql_connect('localhost', 'root', '')) or die(mysql_error());
// Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if (get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
// Sanitize the POST values
$filedesc = clean($_POST['pdesc']);
$fname = clean($_POST['Pre_Name']);
$com = clean($_post[$id_Leccom]);
echo $_post['comselection'];
// $subject= clean($_POST['upname']);
// upload random name/number
$rd2 = mt_rand(1000, 9999) . "_File";
// Check that we have a file
if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
{
// Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload"))
{
// Determine the path to which we want to save this file
// $newname = dirname(__FILE__).'/upload/'.$filename;
$newname = "uploads/" . $rd2 . "-" . $filename;
// Check if the file with the same name is already exists on the server
// Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newname)))
{
// successful upload
// echo "It's done! The file has been saved as: ".$newname;
// echo "$filedesc,$newname,$fname,$comlec";
mysql_query("INSERT INTO `lms`.`presentation` (`Pre_Name` ,`Path` ,`PLec_ID` ,`pdatein` ,`pdesc`) values ('$fname','$newname','1',NOW(),'$filedesc')") or die("failed");
// mysql_query("INSERT INTO presentation (pdesc,path,pdatein,Pre_Name,plec_id) VALUES ('$filedesc','$newname',NOW(),'$fname','$comlec')") or die("query failed");
// mysql_query("INSERT INTO presentation ('pdesc','path','Pre_Name','PLec_ID') values ('$filedesc','$newname','$fname','$comlec')") ;
header("location: fileupload.php");
}
}
}
?>
$name = $result['Lec_Name'];
$id_leccom = $result['Lec_ID'];
and
echo "<option value='".$id_leccom."'>$name</option>";
I have a a multifile upload script that converts uploaded files to zip. It works flawlessly.Only problem that I have is uploading data to the database. I tried everything and the databse still doesn't get any of the data. Two things: 1: I want to send the file path within a html link tag to be displayed as a link on the page I will be loading to and 2: the rest of the data as is submitted on the form. Any help would be great. Here is the code:
<?php
set_time_limit(0); // Make sure php doesnt end script after 30 seconds
ini_set('memory_limit','128M');
ini_set( 'upload_max_filesize', '100M' );
ini_set( 'post_max_size', '100M' );
$project = $_POST['project'];
$assignto = $_POST['assignto'];
$asdate = $_POST['asdate'];
$chdate = $_POST['chdate'];
$ddate = $_POST['ddate'];
$timestamp = time();
if (isset ($_POST['submit']))
{
$filesArray= $_FILES["files"];
for ($num=0; $num<count($filesArray["name"]);$num++)
{
$fileName = $filesArray["name"][$num];
$tempName= $filesArray["tmp_name"][$num];
move_uploaded_file($tempName,"tmp/".$fileName);
}
$archiveName= $timestamp.".zip";
$filesArrayNames= $_FILES["files"]["name"];
$zipsDir= scandir ("uploads/");
$error = false;
foreach($zipsDir as $zipDirfile)
{
if($zipDirfile == $archiveName)
{
$error= true ;
break;
}
}
if ($error== false)
{
$tmpDir = scandir ("tmp/");
$zip = new ZipArchive;
$zip->open("uploads/".$archiveName, ZipArchive::CREATE);
for ($num =0; $num<count($filesArray["name"]);$num++)
{
$fileName = $filesArray["name"][$num];
foreach($tmpDir as $tmpDirfile)
{
if($tmpDirfile == $fileName)
{
$zip->addFile("tmp/".$fileName);
echo " Adding: ".$fileName."<br/>";
}
}
}
$zip->close();
for ($num=0; $num<count($filesArray["name"]);$num++)
{
$fileName = $filesArray["name"][$num];
foreach($tmpDir as $tmpDirFile)
{
if($tmpDirfile == $fileName)
{
unlink("tmp/".$fileName);
}
}
}
}
else
{
echo "Name already exists";
}
}
$filepath= "<a href='"'http://www.amadastage.com/uploads/ '"'.$archiveName.'"'>Files</a>';
mysql_connect("webcontrolcenter.com","dude","usa") or die ('Error:' .mysql_error());
//database connection
mysql_select_db("mediamanagement");
mysqli_query("INSERT INTO demo (name, id_continent, lastvisit,cdate,ddate,email)
VALUES ('project', 'assignto','asdate','chdate','ddate')");
Like nvanesch said use mysqli for creating connection.
Also you have to put the variable values into quotes:
Try like this:
$sql = "INSERT INTO demo (`name`, `id_continent`, `lastvisit`, `cdate`, `ddate`, `email`)
VALUES ('".$project."', '".$assignto."','".$asdate."','".$chdate."','".$ddate."')";
mysqli_query($sql);
You are connecting with mysql_ and next querying with mysqli_
You should either have all with mysql_ (not recommended as mysql_ is deprecated) or use mysqli_ everywhere.