I have a list of files in my html where I have removed the directory ImageFiles/ from the filename. So for example the file names look like below:
tulips.png
koala.png
jellyfish.png
Now if the user clicks on one of these file names, then I want to retrieve the file from the database, but in the database all files contain the directory ImageFiles/ at the start of the file name. So in the database the files look like this below:
ImageFiles/tulips.png
ImageFiles/koala.png
ImageFiles/jellyfish.png
My question is simply how do I finish the WHERE clause in order to retrieve the correct file from the database? For example if I am looking for the file tulips.png, how can I get the query to be able to find ImageFiles/tulips.png and only this file from the database?
Below is the mysqli query:
$getimage = $_GET['filename'];
$imagequery = "SELECT ImageFile FROM Image WHERE (ImageFile = ?)";
if (!$imagestmt = $mysqli->prepare($imagequery)) {
// Handle errors with prepare operation here
}
// Bind parameter for statement
$imagestmt->bind_param("s", $getimage);
// Execute the statement
$imagestmt->execute();
Just prepend the directory name to the $getimage variable:
$getimage = 'ImageFiles/' . $_GET['filename'];
Related
I have a php project running in my local machine(angular,php,mysql).Same copy of project running in online.
My Aim is to Sync(copy local db to server db) every one hour by running any PHP Script using angular 'set Interval' function.
What is the IDEA behind this functionality should i use?
or how i will achieve this ?
Any suggestions will be great help for me,
and Thanks in advance.
If your database tables not gonna change what you can do is create a function select all the data from your local database and pass that data to online function to update your online database with new or updated records.
For ex:
If you have a table called users. From AJAX you will select all local data and create JSON Object pass the data to script function.
From that JSON Object you will pass data to online php file and update your online database from it.
Note: You have to careful with giving lot of conditions to check whether data get missing or override.
You'll have to write a service and some code to dump your database (if you want to sync complete database every time) follow this answer
After dumping your sql next you have to upload the file to your server via the service. Upon receiving you can load the data again mysql -u username -p database_name < file.sql
However I won't recommend this, try exploring database approach of Master-Slave Database, where your local server's database will be a Master and your remote server will be slave. Your data will automatically be synchronized.Please see this tutorial
You can implement interface to select tables you want to import in live. Use below code generate CSV files of selected tables and prepare array.
<?php
$file_name_flat = 'TABLE-NAME.csv'; // Replace TABLE-NAME with your selected table name.
$fpointer = fopen(FOLDER-LOCATION.$file_name_flat, 'w+'); // Open CSV file. Replace
FOLDER-LOCATION with your local folder path where you want to save this CSV files.
//Execute query to get all columns data
$query = "select * FROM TABLE-NAME WHERE 1"; // Replace TABLE-NAME with your selected
table name. You can set other conditions based on your requirement.
//Execute query as per your CMS / Framework coding standards and write CSV file.
$result_flat = $DB_Connection->query($query)->fetchAll('assoc');
foreach ($result_flat as $fields) {
fputcsv($fpointer, $fields);
}
//Prepare Array of CSVs to create ZIP file
$files = array($file_name_flat);
fclose($fpointer); // close CSV file after successfully write.
?>
CREATE ZIP of CSVs
//Create ZIP
$zipname = 'tables_'.date('Y-m-d-H-i-s').'.zip';
createZipFile($files,$zipname,FOLDER_LOCATION); //Replace FOLDER-LOCATION with your
local folder path where you saved CSV files.
/* createZipFile Funcation to create zip file Both params are mandatory */
function createZipFile($files_names = array(),$zipfileName, $files_path=""){
$zip = new \ZipArchive;
$zip->open(TMP.$zipfileName, \ZipArchive::CREATE);
foreach ($files_names as $file) {
$zip->addFile($files_path.$file,$file);
}
$zip->close();
foreach ($files_names as $file) {
unlink($files_path.$file);
}
///Then download the zipped file.
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipfileName);
header('Content-Length: ' . filesize(FOLDER_LOCATION.$zipfileName));
readfile(TMP.$zipfileName);
unlink(TMP.$zipfileName);
die;
}
Now Implement a form to upload this zip file on live server. In Post action of this form add code to get zip file.
$filename = $_FILES['filename']['name'];
$source = $_FILES["filename"]["tmp_name"];
//Upload zip file to server location. Replace SERVER_FOLDER_PATH to server's location
where you want to save uploaded zip.
if(move_uploaded_file($source, SERVER_FOLDER_PATH)) {
//Extract ZIP file
$zip = new \ZipArchive();
$x = $zip->open($target_path);
if($x === true) {
$zip->extractTo(PATH_TO_SAVE_EXTRACTED_ZIP); // change this to the correct site path
$zip->close();
$cdir = scandir(PATH_TO_SAVE_EXTRACTED_ZIP); // Read DIR
$fieldSeparator = ",";
$lineSeparator = '\n';
foreach ($cdir as $key => $value)
{
if (!in_array($value,array(".","..")))
{
$fileName = PATH_TO_SAVE_EXTRACTED_ZIP.$value; // replace
PATH_TO_SAVE_EXTRACTED_ZIP with your server path
$tableName = SET_TABLE_NAME; // You have to set the logic to get the table name.
if (is_file($fileName))
{
// User MYSQL "LOAD DATA LOCAL INFILE" to IMPORT CSVs into particular tables. There are option available for this LOAD DATA process. It will import your CSV to particular table. No need to execute loop to insert data one by one.
$q = 'LOAD DATA LOCAL INFILE "'.$fileName.'" REPLACE INTO TABLE '.$tableName.' FIELDS TERMINATED BY "' .$fieldSeparator. '" Enclosed BY '.'\'"\''.' LINES TERMINATED BY "'.$lineSeparator.'"';
$DB_Connection->query($q);
}
}
}
}
You can check LOAD DATA of MySQL from - MYSQL
You can run a cron job on your local computer that exports the MySQL data using mysqldump and then uploads it to the server using rsync and sshpass.
Am saving a file as a long blob in php by first saving it in a folder then to a db, the problem is that the server has write permissions so i would like to save it directly
This is what i have tried (This works perfectly):
if(isset($_POST['image'])){
$id = 0;
$image = $_POST['image'];
$tmp_image = date('YmdHisu').'.jpg';
file_put_contents($tmp_image, base64_decode($image));
$sql = "INSERT INTO fingerprint(template)
VALUES ('".addslashes(file_get_contents($tmp_image))."')";
try
{
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$rowCount=$command->execute(); // execute the non-query SQL
echo "saved successifully";
unlink($tmp_image);
}
catch(Exception $ex)
{
echo 'Query failed' , $ex->getMessage();
unlink($tmp_image);
}
}
How can i save this in a blob field in mysql without first having to save it in a folder then saving to db
Let's assume you've sent the file via Android using POST method to your server running Yii1.
First of all the physical file is contained in the $_FILES variable and in the $_POST variable, as you said, contains a string of the file encoded in base 64 format (i write this for a clear answer).
$_FILE DOCUMENTATION
Now this is how you can try to upload the file with the standard MVC yii way using yii code:
It's true that you're uploading your file from an external device but Yii came in your help with CUploadedFile Class:
Call getInstance to retrieve the instance of an uploaded file, and then use saveAs to save it on the server. You may also query other information about the file, including name, tempName, type, size and error.
In particular you should use the function getInstancesByName that returns an array of instances starting with specified array name.
$temp = CUploadedFile::getInstanceByName("image"); // $_FILES['image']
and with this you can access to the file data:
$temp->name; // Name of the file
$temp->type; // Type of the file
$temp->size; // Size of the file
// etc etc..
$temp->saveAs("/your/path/" . $tmp_image . $temp->type); // Save your file
for final you can check if the file was saved and execute your query:
if($temp->saveAs("/your/path/" . $tmp_image . $temp->type)) {
// File is saved you can execute the query for save the record in your db
} else {
// Something went wrong.
}
You can also transfer this logic in a model.
check this link for more infos
Hope this will help you.
I have a directory full of images (40,000 +) that I need sorted. I have designed a script to sort them into knew proper directories, however, I am having issues with the file name.
The images urls with the id they belong to are stored in a database, and I am using the database in conjunction with the script to sort the images.
My Problem:
The image url's in the database are shortened. An example of such corresponding images are like this:
dsc_0107-367.jpg
dsc_0107-367-5478-2354-0014.jpg
The first part of the filenames are the same, but the actual file contains more info. I'd like a way to move the file from the database with the known part of the file name.
I have a basic code:
<?php
$sfiles = mysqli_query($dbconn, "SELECT * FROM files WHERE gal_id = '$_GET[id']");
while($file = mysqli_fetch_assoc($sfiles)){
$folder = $file['gal_id'];
$fileToMove = $file['filename'];
$origDir = "mypath/to/dir";
$newDir = "mypath/to/new/dir/$file['gal_id']";
mkdir "$newDir";
mv "$fileToMove" "$newDir";
}
Im just confused on how to select the file based on the small part from the database.
NOTE: It's not as simple as changing the number of chars in the db, because the db was given to me from an external site thats been deleted. So this is all the data I have.
PHP can open files using the function glob() . Glob searches your server, or specified directory, for any files containing a "match" to a pattern you specify.
Using glob() like this will pull your images from a partial name.
Run this query separate from the second:
$update = mysqli($dbconn, "UPDATE files
SET filename = REPLACE(filename, '.info', ''));
filename should be the column in your database that contains the list of images. The reason we are removing the .jpg from the db columns is if your names are partial, the .jpg may not match with the given name in your directory. With it removed, we can search solely for the pattern of the name.
Build the query to select and move the folders:
$sfiles = mysqli_query($dbconn, "SELECT * FROM files");
while($file = mysqli_fetch_assoc($sfiles)){
$fileToMove = $file['filename'];
// because glob outputs the result set into an array,
// we will use foreach to run each result from the array individually.
foreach(glob("$fileToMove*") as filename){
echo "$filename <br>";
// I'm echoing this out to see that the results are being run
// one line at a time and to confirm the photo's are
// matching the pattern.
$folder = $file['gal_id'];
// pulling the id from the db of the gallery the photo belongs to.
// This will specify which folder to move the pic to.
// Replace gal_id with the name of your column.
$newDir = $_SERVER['DOCUMENT_ROOT']."/admin/wysiwyg/kcfinder/upload/images/gallery/old/".$folder;
copy($filename,$newDir."/".$filename);
// I would recommend copy rather than move.
// This will leave the original photo in its place.
// This measure is to ensure the photo made it to the new directory so you don't lose it.
// You could go back and delete the photos after if you'd prefer.
}
}
Your MySQL query is ripe for SQL Injection, and your GET statement needs to be sanitized, if I went to your page with something similar to :
pagename.php?id=' DROP TABLE; #--
this is going to end extremely badly for you.
So;
OVerall it's much better to use Prepared Statements. THere's LOTS and LOTS of data about how to use them all over SO and the wider internet. What I show below is only a stopgap measure.
$id = (int)$_GET['id'] //This forces the id value to be numeric.
$sfiles = mysqli_query($dbconn, "SELECT * FROM files WHERE gal_id = ".$id);
Also keep note of closing your ' and " quotes as your original doesn't close the array key wrapper quotes.
I never used mysqli_fetch_assoc and always used mysqli_fetch_array so will use that as it fits the same syntax :
while($file = mysqli_fetch_array($sfiles)){
$folder = $id //same thing.
$fileToMove = $file['filename'];
$origDir = "mypath/to/dir/".$fileToMove;
//This directory shold always start with Server['DOCUMENT_ROOT'].
//Please read the manual for it.
$newDir = $_SERVER['DOCUMENT_ROOT']."/mypath/to/new/dir/".$folder;
if(!is_dir($newDir)){
mkdir $newDir;
}
// Now the magic happens, copies the file to the new directory.
// Then (optionally) delete the original.
copy($origDir,$newDir."/".$fileToMove);
unlink($origDir); //removes original.
// Add a flag to your Database to know that this file has been copied,
// ideally you should resave the filepath to the correct new one.
//MySQL update saving the new filepath.
}
Read up on PHP Copy and PHP unlink.
And; please use Prepared Statements for PHP and Database interactions.!
I have a directory of images which are all named *.jpg, where * is the ID of each record in a MySQL table. e.g. 1394.jpg
What I'd like to be able to do is pull 5 random images from that directory using PHP and for each image, then query the MySQL table for records matching that ID / image filename, so I can then display details of each record.
The part I am looking for some guidance on is how to a) randomly choose 5 images using php, then b) identifying the filenames. Once I have the filename as a variable, I am sure I should be able to write the MySQL query. It's the PHP element I'm struggling with.
Could anyone offer any advice?
If the file info in your db is update-to-date regarding the image files in your file system, you can get the 5 random filename ids along with other info directly from the db:
$sql = 'SELECT * FROM image_files ORDER BY RAND() LIMIT 5';
This will return you file ids along with other info you have there in the table.
EDIT: Apparently all files in db does not exist in file system. So below is updated answer:
// Get files info from db in random order
$sql = 'SELECT * FROM image_files ORDER BY RAND()';
$result = $conn->query($sql);
// Pick first 5 files that does exist in file system
$five_files=Array();
while($row = $result->fetch_assoc()) {
$filepath = '/dir/images/'.$row['id'].'.jpg';
if (is_file($filepath)) {
$five_files[] = $row;
if (count($five_files) == 5) break;
}
}
// This will have info on five randomly picked files from db that does exist
print_r($five_files);
I'll do that, first getting all the images of the folder
$files = glob("$dir/*.{jpg,jpeg}", GLOB_BRACE);
Then, I'll get one (you can make a loop) random pic using array_rand, like this
$file = array_rand($files); // You can check if is repeated or something too
Finally, you can preg_replace the name of the file to get only the name (without extension) and query to your DB with that name... (Maybe there are other ways, but this is simple and fast)
Okay, We will do it in these steps :
Get File Name Lists from the required Directory
Function : scandir() look for more details here
Store in Array
Get Random 5 Data
Function array_rand() look for more details here
For Each File Run Query For Details
Loop - Foreach() - Store MySQL-fetched-data in multi-dimensional Array
Display
How do you display an image from a SQL database in php.
The file name is stored in the database and the images itself is saved in my images file.
The image should change accordingly and correspond to the information I want.
Tried using this codes but failed
echo"<tr><td> <img src='mysql_query('SELECT imagefile FROM recipe WHERE recipeid = $recipeid')'> </td>";
Create a php file called image.php and an extra parameter which corresponds to the path.
Like, for example image.php?v=007
Hence, image.php should be able to look up the database using 007 as a reference and find it's path.
Path can be stored in a column in the database.
EDIT:
Create a php file called image.php
Next create a database with with columns like ID, REFERENCE AND PATH.
Use the following code to get the reference:
$reference = $_GET["v"];
Next look up the database for the path:
$stat = $conn -> prepare ("SELECT PATH FROM TABLE_NAME WHERE REFERENCE = :reference");
$stat -> bindValue(':reference', $reference);
$stat -> execute();
$path = $stat -> fetchColumn();
// Now you can use this code to display the image.
echo '<img src="' . $path . '">';
It will take the user to the image's path.
For this, you need to insert reference and path into the database everytime where a new image is uploaded.