I want to use php to create one table in sql which has images set content of the image and then I want fetch this table in html.
someone knows how this work? or someone has see the example on line?
please help. thanks a lot.
Here' is an article that will tell you all you want to know regarding storing images and the likes of in blob columns http://www.phpriot.com/articles/images-in-mysql
Ok, I understand that you want to upload an image file into a table in db, through your web app, using php, and then again you want to display that same image from the table in your web app(html page).
I will show the example for MySQL, using simple PHP 5.3
Create a sample table, say "photo_table" :
CREATE TABLE photo_table (photo_name_col VARCHAR(30),photo_img_col LONGBLOB);
Now for uploading the image file through your php page use the following in your html code:
<form name="photoForm" method="post" ENCTYPE="multipart/form-data" action="../insertImage.php" >
<input type="text" name="uploadFileName">
<!--commenting as I was not able to publish this note<input type="file" name="uploadFile" />-->
<!--Some other input fields if you want-->
<input type="submit" value="Submit"/>
</form>
Now, once the form "photoForm" is submitted, the form values are passed to "insertImage.php", where we will have the following code to upload the photo and its name into a table in our MySQL db:
<?php
$con=mysql_connect("ipAddressOfDB","username","password");
if(!$con){
die('Could not connect:'.mysql_error());
}
mysql_select_db("db_name",$con);
$image = $_FILES['uploadfile']['tmp_name'];
$imageName = $_POST['uploadFileName'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql="insert into photo_table values('$imageName','$content')";
mysql_query($sql,$con);
?>
For displaying the photo from table into your html page, I use the following approach.
Fetch the image from db and copy it to a temporary location in the server.
<?php
$con=mysql_connect("ipAddressOfDB","username","password");
mysql_select_db("db_name",$con);
$sql="select * from photo_table where photo_name_col ='$uploadFileName'";
$result=mysql_query($sql,$con);
if($row=mysql_fetch_array($result)){
$fileName="generated/".$uploadFileName;
file_put_contents($fileName, $row['photo']);
}
echo "<img src='" . $fileName . "' />"; <!--this will display the image-->
?>
Related
This image shows the products table that I am using to upload my image from the back-end side and I wanted to display it on the front-end page.
I realize that the picture that I have uploaded through the back end side only saved as '48 B' but when I was uploading it through MySQL manually it saved as '64 KiB', although both are the same file.
When it comes to displaying the 48 B Image file would not show.
[code1] This is the code that I am using to insert the image from the back-end.
if(isset($_POST['submit'])){
$pid = mysql_real_escape_string($_POST['productID']);
$productName = mysql_real_escape_string($_POST['productName']);
$productImg = mysql_real_escape_string($_POST['productImg']);
$insert = mysql_query("INSERT INTO products (productID, productName, productImg) VALUES ('$pid', '$productName', '$productImg')");
if($insert)
{
echo 'Successfully added new record.';
} else {
echo 'Failed to add new record because '.mysql_error();
}
}
?>
[code2] and this is the code that I am using to display the image from the front-end.
while($row = mysql_fetch_array($query)){
echo '<tr>
<td>'.$row['productID'].'</td>
<td>'.$row['productName'].'</td>
<td>'.
'<img src="data:image/jpg;base64,'.base64_encode($row['productImg']).'" width="auto" height="150" class="img-thumnail"/>'
.'</td>
I think the problem is in the insertion code [code1] even though all the data successfully inserted.
if you are using <input type="file" /> and if you are not aware this that "you cannot send file type like normal string" check that what you are doing before submit.
Refer this link it may help you:
https://www.codexworld.com/store-retrieve-image-from-database-mysql-php/
I've been working on this for four hours and I still have no clue, so I came here to seek help. I'm learning PHP and mySQL and one of the way I learn is to learn from open source projects. Today I'm trying to understand an open source project and I have some problems. Here is the link to the open source project: https://github.com/markpytel/Printstagram Basically, it has something like the following, let's call it profileinfo.php (name of this file is pretty deceiving, it is a page that shows images uploaded by different users)
<?php
$sql="SELECT pid,poster, pdate FROM photo WHERE poster='$myusername' OR pid
in (select pid from tag where taggee='$myusername') OR pid in (select pid
from ingroup natural join shared where username='$myusername' and username
!= ownername) ORDER BY pdate desc";
$result=mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<hr>";
echo "Posted by: " . $row["poster"]. " Time: " . $row["pdate"]."<br>";
// pid is each photo's unique id in the database
$pidrow=($row["pid"]);
?>
</head>
<body>
<form action="listsingleREV.php?pidrow=<?php echo $pidrow; ?>" method="POST">
<input type="submit" id="pidrow" value="View this image" />
</form>
</body>
</html>
If you click on the button that says "view this image", image uploaded by users will appear. The first question I have is: What's the meaning of the question mark in the image src. I understand that there is a PHP tag in the img src, but I don't understand why there is a question mark between listsingleREV.php and pidrow.
listsingleREV.php looks like this:
<?php
session_start();
$pidrow=$_GET['pidrow'];
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("printstagram");
$sql = "SELECT pid FROM photo WHERE pid=$pidrow";
$result = mysql_query($sql);
?>
<?php
while($row = mysql_fetch_array($result)) {
?>
<img src="imageview.php?pid=<?php echo $row["pid"]; ?>" /><br/>
<?php
}
?>
imageview.php looks like this:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("printstagram") or die(mysql_error());
if(isset($_GET['pid'])) {
$sql = "SELECT image FROM photo WHERE pid=" . $_GET['pid'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("content-type: image/jpeg");
echo $row["image"];
}
mysql_close($conn);
?>
Of course, if a user has to click on a button to see each image, it is very inconvenient. So I decide to give myself some practice and modify the code(it is Apache license so I can do it)such that images will be automatically presented on profileinfo.php without the need to click on a button. Since imageview.php and listsingleREV.php show the images, I tried to substitute the form in profileinfo.php with these two files. I worked on it for four hours without achieving my goal. Can someone tell me the correct way to show the images on profileinfo.php without the need to click on the button?
As it appears in imageview.pho the $row[pid] contain the link of your image in photo table so add this line to profileinfo.php under the while loop in the place you want it to display
<img src="<?php echo". $row["pid"]."; ?>">
I am trying to build an upload component that saves the file information to a MySQL DB table. My first issue is that each time a user uploads a file, two entries are added to the database.
My next issue is that I was to grab an uploaded file and display it as a link for the user to click on to view in a new tab. Right now, the upload saves the file's server directory path. When I go to click on the file, I get an error message saying the directory path could not be found.
My biggest issue is the link problem to view the uploads. Then, if someone also has a suggestion for the double entry problem, that would also be appreciated.
My Code:
HTML: File upload feature - Successfully uploads all variables twice...
<form id="sgFileUpload" action='sg_addupload.php' target='hiddenFrame' method="POST" enctype="multipart/form-data">
<fieldset id='uploadBtnField'>
<input type="hidden" name="MAX_FILE_SIZE" value="50000000"/>
<input type='hidden' name='sgRef' id='sgRef' value='<?php echo $sgref ?>'>
<input type='file' name='searchFile' id='searchFile' multiple>
<input type='submit' name='startUpload' id='startUpload' value='Upload'>
</fieldset>
</form> <!-- End Form Input -->
My PHP: File upload to DB
if(isset($_POST['sgRef'])) {
$sgref=$_POST['sgRef'];
}
$fileName = $_FILES['searchFile']['name'];
$fSize = $_FILES['searchFile']['size'];
$fType = $_FILES['searchFile']['type'];
$target = "../bms/uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["searchFile"]["tmp_name"];
//$docType = $_POST['docType'];
$result = move_uploaded_file($tempFileName,$fileTarget);
if ($result) {
//run DB Connection code...
//Writes the information to the database
$sql="INSERT sg_uploads(sgref,file,type,size,content,doctype) VALUES('$sgref','$fileName','$fType','$fSize','$fileTarget','Other')";
$conn->query($sql);
if($conn->query($sql)) {
echo 'Your file <html><b><i>'.$fileName.'</i></b></html> has been successfully uploaded!';
} else {
//Gives an error if its not
echo "Sorry, there was a problem uploading your file.";
}
//Free the result variables.
$sql->free();
$result->free();
//Close the Database connection.
$conn->close();
}//End If Statement.
PHP CODE: To display links from DB (PHP CODE FOR RETRIEVAL IS SUCCESSFUL)
<?php
while ($row = $result->fetch_array()) {
echo "<tbody>";
echo "<tr>";
echo "<td>" . "<a href=".$row['content']."' >".$row['file']."</a>". "</td>";
echo "<br/>";
echo "<br/>";
}//end while.
echo "</tr>";
echo "</tbody>";
$filename = $row[0];
echo "<p></p>";
?>
All help is appreciated! Thank you!
NOTE: the 'file' column in the database is a datatype of 'blob'.
"#Fred, yes it was a directory issue. Upon fixing this issue, I was able to successfully link the the page and view it. If you summarize your two suggestions as an answer, I will mark your response as the correct answer. Thank you!"
As I stated in comments:
The duplicate entries are caused by $conn->query($sql); if($conn->query($sql))
where there were two instances of query() being used.
You can just use the conditional statement and omit $conn->query($sql);.
For the path issue, this was also stated in comments that the folder's path wasn't properly indexed.
Footnotes:
You're presently open to an SQL injection. Best you use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
I am trying to query a mysql database and display data in a table. That part is working. At the moment, it is set up for displaying the
results within the certain date range.
I now want to take the table and make a button that allows you to export it to an Excel file. Before I added the option of choosing a date range, you were able to export to Excel, but now it seems that the second file does not know what table I am talking about. I tried using POST to send the values of the data and re-query on the other page.
When I click the button to export, the excel document that is downloaded is empty, (though it has a size). Any help please?
-----Query mysql---------
<html><head><title>New Production Rejections</title></head></html>
<?php
include("config.php");
//get serial from submitted data
//$serial = $_POST['sNumber'];
//if the submitted data is empty
$serial = $_POST['entryDate'];
$dateEnd = $_POST['entryDate2'];
//parse the serial from the link in tracker
?>
<form method="post" action="<?php echo "queryNewProdRejections.php?"?>">
Search between dates: (Format: YYYY-MM-DD)<input type='text' size='20' maxlength='20' name='entryDate'> - <input type='text' size='20' maxlength='20' name='entryDate2'>
<input type="submit" value="Search Date Range"><br/></form>
<?php
//query based on approved date that is nothing, repaired date that is nothing,
//tech is a real tech, location that is not Revite (RVP), action was to replace,
//and the status is not (declined or skipped).
$query = "SELECT *
FROM `rma`
WHERE `origin` NOT LIKE 'Field_failure'
AND `origin` NOT LIKE 'DOA_at_Customer'
AND `origin` NOT LIKE 'Sweden_Fail_VI'
AND `entry` > '$serial' AND `entry` < '$dateEnd'";
$data = mysql_query($query) or die(mysql_error());
//Create a table with the array of data from repairs, based on the previous query
echo "<table border='1'><tr><th>RMA</th><th>Product</th><th>Serial</th><th>Origin</th><th>Return To</th><th>Credit Num</th><th>Order</th><th>Entry Date</th><th>Tech</th><th>Traking Num</th></tr>";
while($row = mysql_fetch_array($data)){
print "<tr><td>".$row['intrma']."</td><td>".$row['product']."</td><td>".$row['serial']."</td><td>".$row['origin']."</td><td>".$row['retto']."</td><td>".$row['creditnum']."</td><td>".$row['ordernum']."</td><td>".$row['entry']."</td><td>".$row['tech']."</td><td>".$row['tracknum']."</td></tr>";
}
print "</table>";
?>
<html>
<form method="post" action="saveQueryToExcel.php">
<input type='hidden' name='ent_1' value="<?php echo $_POST['entryDate']; ?>">
<input type='hidden' name='ent_2' value="<?php echo $_POST['entryDate2']; ?>">
<input type="submit" value="Save to Excel">
</form>
</html>
---------------Print to Excel File -- (saveQueryToExcel.php)
<html><head><title>New Production Rejections</title></head></html>
<?php
error_reporting(0);
$dateBeg=$_POST['ent_1'];
$dateEnd=$_POST['ent_2'];
//Connect to the database, repairs in maprdweb
include("config.php");
//query based on approved date that is nothing, repaired date that is nothing,
//tech is a real tech, location that is not Revite (RVP), action was to replace,
//and the status is not (declined or skipped).
$query = "SELECT *
FROM `rma`
WHERE `origin` NOT LIKE 'Field_failure'
AND `origin` NOT LIKE 'DOA_at_Customer'
AND `origin` NOT LIKE 'Sweden_Fail_VI'
AND `entry` > '$dateBeg' AND `entry` < '$dateEnd'";
$data = mysql_query($query) or die(mysql_error());
//Create a table with the array of data from repairs, based on the previous query
header('Content-type: application/vnd.ms-excel');
echo "<table border='1'><tr><th>RMA</th><th>Product</th><th>Serial</th><th>Origin</th><th>Return To</th><th>Credit Num</th><th>Order</th><th>Entry Date</th><th>Tech</th><th>Traking Num</th></tr>";
while($row = mysql_fetch_array($data)){
print "<tr><td>".$row['intrma']."</td><td>".$row['product']."</td><td>".$row['serial']."</td><td>".$row['origin']."</td><td>".$row['retto']."</td><td>".$row['creditnum']."</td><td>".$row['ordernum']."</td><td>".$row['entry']."</td><td>".$row['tech']."</td><td>".$row['tracknum']."</td></tr>";
}
print "</table>";
?>
PHPexcel works great for exporting data to an actual Excel document.
It appears you are just generating an HTML table with your result.. which isn't exactly Excel format.
You should take the same code, and instead of printing <tr> lines with it, send it to fputcsv. Use the standard output as the file handle. You need to set proper html headers for the output to be sent as a csv, along the lines of this post: force file download.
Take a look a this class. It is able to solve the problem.
https://github.com/GSTVAC/HtmlExcel
$xls = new HtmlExcel();
$xls->addSheet("Names", $names);
$xls->headers();
echo $xls->buildFile();
I am building an image uploading website. Images are uploaded to a directory on the server and data such as the filename is stored in a MySql table. I have created a 'gallery' page which displays all the uploaded images as thumbnails. When a user clicks on one of the images, it takes them to 'image.php' page, which will display the image full size and echo information such as the username of the person who uploaded the image etc.
I am unsure as to what would be the correct way of displaying the image. The images in my MySql table have unique ID's which I'm guessing will have to be manipulated in some way, but how do I would I get the ID of the photo that has been clicked on into the 'image.php' MySql query?
Hope this has been explained well enough. Thanks in advance.
gallery.php page... (exclusing database connections etc.)
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM photos");
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
?>
<section class="thumbnails group">
<?php Echo "<img src=http://.../thumbs/tn_".$info['filename'] .">"; }?>
</section>
image.php page...
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM photos WHERE 'id' = ??");
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
?>
<section class="main-image group">
<?php echo "<img src=http://.../images/".$info['filename'] .">"; }?>
</section>
You can simply pass the ID of the image through in the querystring
<img src="/path/to/thumbnail">
In your image.php page, you can retrieve the ID like this (assuming it's an integer):
$imageID = intval( $_GET["image"]);
You should then be able to retrieve the path to the image and display it.
# liquorvicar answer is correct one, there's no ambiguity in his answer! well,
try this;
<?php Echo "<img src=http://...thumbs/tn_".$info['filename'] .">"; }?>
on image.php page
$id=intval($_REQUEST['id'])
now you have id for that specific image show its related info.