My problem is, when I upload a picture to a database, the upload is successful but the picture isn’t displayed. This is my code:
SQL file:
CREATE TABLE `images` (`id` int(11) NOT NULL auto_increment,`name` varchar(100) default NULL,`size` int(11) default NULL,`type` varchar(20) default NULL,`content` mediumblob,PRIMARY KEY (`id`)) ENGINE=MyISAM;
Index.php
<?php if (!empty($uploadOk)): ?>
<div>
<h3>Image Uploaded:</h3>
</div>
<div>
<img src="image.php?id=<?=$imageId ?>" width="150px">
<strong>Embed</strong>: <input size="25" value='<img src="image.php?id=<?=$imageId ?>">'><br>
</div>
<hr>
<? endif; ?>
<form action="index.php" method="post" enctype="multipart/form-data" >
<div>
<h3>Image Upload:</h3>
</div>
<div>
<label>Image</label>
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<input type="file" name="image" />
<input name="submit" type="submit" value="Upload"><br>
</div>
</form>
</tr>';}mysql_close();?>
image.php
<?php
// verify request id.
if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
echo 'A valid image file id is required to display the image file.';
exit;
}
$imageId = $_GET['id'];
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'username', 'pass', 'db_name')) {
$content = mysqli_real_escape_string($conn, $content);
$sql = "SELECT type, content FROM images where id = {$imageId}";
if ($rs = mysqli_query($conn, $sql)) {
$imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
mysqli_free_result($rs);
} else {
echo "Error: Could not get data from mysql database. Please try again.";
}
//close mysqli connection
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
if (!empty($imageData)) {
// show the image.
header("Content-type: {$imageData['type']}");
echo $imageData['content'];
} ?>
getImage.php
<?php
$id = $_GET['id'];
$link = mysql_connect("localhost", "username", "pass");
mysql_select_db("db_name");
$sql = "SELECT content FROM images WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['content'];
?>
This code worked. I think the SQL database is incorrect or has problems to display images.
In order to display the image, you should use AJAX from JavaScript.
Related
I am trying to make a CRUD application. on the Create page I have to have three fields (title, text, category). the problem is that I have to make a method / function in PHP or JS that chooses a random picture from the "images" file and automatically loads it in the database along with the other 3 fields. then it has to appear on the admin.php page together with the other 3 fields.
Images have almost the same name except the last digit which differs (1-2-3)
I have no idea how to make this method/function.
my create.php page
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$title = $text = $category = "";
$title_err = $text_err = $category_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate title
$input_title = trim($_POST["title"]);
if(empty($input_title)){
$title_err = "Please enter a title.";
} else{
$title = $input_title;
}
// Validate text
$input_text = trim($_POST["text"]);
if(empty($input_text)){
$text_err = "Please enter an text.";
} else{
$text = $input_text;
}
// Validate category
$input_category = trim($_POST["category"]);
if(empty($input_category)){
$category_err = "Please enter the category.";
} else{
$category = $input_category;
}
// Check input errors before inserting in database
if(empty($title_err) && empty($text_err) && empty($category_err)){
// Prepare an insert statement
$sql = "INSERT INTO informatii (title, text, category) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_title, $param_text, $param_category, );
// Set parameters
$param_title = $title;
$param_text = $text;
$param_category = $category;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: admin.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
}
?>
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper {
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Create Record</h2>
<p>Please fill this form and submit to add employee record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>title</label>
<input type="text" name="title"
class="form-control <?php echo (!empty($title_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $title; ?>">
<span class="invalid-feedback"><?php echo $title_err;?></span>
</div>
<div class="form-group">
<label>Text</label>
<textarea name="text"
class="form-control <?php echo (!empty($text_err)) ? 'is-invalid' : ''; ?>"><?php echo $text; ?></textarea>
<span class="invalid-feedback"><?php echo $text_err;?></span>
</div>
<div class="form-group">
<label>Category</label>
<textarea name="category"
class="form-control <?php echo (!empty($category_err)) ? 'is-invalid' : ''; ?>"><?php echo $category; ?></textarea>
<span class="invalid-feedback"><?php echo $category_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
this should get you in the right direction (saving the image src is enough), you of course will have to adapt the path to your image folder, and image name
$nr_images = 3;
$random_nr_index = random_int(1,$nr_images);
$random_image_src = '/images/image-'.$random_nr_index.'.jpg';
To do it you need more than one step creating:
A simple html page to post 3 fields value and the image
A php file that receive the post fields and the image and save into mysql
A simple admin.PHP page that shows 3 fields and image
if you already have the images on the server please specify it in a comment
STEP 1:
<html>
<body>
<form method="POST" action="post.php">
f1:<input type="text" name="field1"><br>
f2:<input type="text" name="field2"><br>
f3:<input type="text" name="field3"><br>
im:<input type="file" name="image"><br>
<input type="submit" value="Save">
</form>
</body>
</html>
STEP 2: post.php
<?php
$f1=$_POST["field1"];
$f2=$_POST["field2"];
$f3=$_POST["field3"];
$im=$_POST["image"];
if ($f1 == "" || $f2 == "" || $f3 == "" ){
die("Errors: fields can't be empty! Go back check the fields and try Again");
}
//Saving image on Server's file system if any image
if(isset($_POST["image"])) {
//Saving image with no checking nothing: filetype, mime , extention (it may be very dangerous in a real server exposed to the public)
$where_save = "images/";
$im_name = basename($_FILES["image"]["name"]);
$tmp_name = $_FILES["image"]["tmp_name"];
move_uploaded_file ( $tmp_name , $where_save.$im_name );
}
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// WARNINGS ------------------------------------------------
// I do not care about security , please pay attention to it .
// use some mysql_escape_string , or real_mysql_escape_string
// could mitigate the violence of some sqlinjection attack
$sql = "INSERT INTO yourtable (field1, field2, field3,im_name)
VALUES ('$f1', '$f2', '$f3',$im_name)";
//executing mysql query to save data into it
if (!mysqli_query($conn, $sql)) {
die("Error: " . $sql . "<br>" . mysqli_error($conn));
}
//closing connection
mysqli_close($conn);
//Now we can redirect the user to admin.php where we show data
header("Location: admin.php");
?>
STEP 3:
<?php
$where_are_images="images/";
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Again creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//now we want to read the data from mysql
$sql = "SELECT * FROM yourtable LIMIT 1"; //just limit to the first record
$result = mysqli_query($conn, $sql);
?>
<html>
<body>
<h2>Admin page</h2>
<em> hey every one can see top secret data here , Needs soma care about security!</em>
<?php while($d = mysqli_fetch_assoc($result)){ // LOOPING ?>
<br>
f1:<?= $d["field1"] ?><br>
f2:<?= $d["field2"] ?><br>
f3:<?= $d["field3"] ?><br>
<img src="<?=$where_are_images.$d['im_name']?>">
<br>
<br>
<?php } ?>
</body>
</html>
<php? // CLOSING AND FREE RESOURCES
mysqli_free_result($result);
mysqli_close($conn); ?>
Now you have all you need . Have fun editing it with random images part ...
I hope there are no error (i have not tested it)
I have created a php script with a form that it should insert some data into database, it actually add the text and the ID but it does not add the file.
the database looks like this:
Database name: highmob_comenzi
table name: players
in table we got 3 rows:
ID (auto_increment)
name (the name that we insert from the form)
schite (where the files should be uploaded) Type: blob Colation: none , all none
this is the script what I have tried so far
<?php
include('connect-db.php');
?>
<?php
function renderForm($name, $schita, $error)
{
?>
<?php
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post" enctype="multipart/form-data" >
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="hidden" name="name" value="<?php echo $name; ?>"/>
<input type="file" id="schita" name="schita" >
<button type="submit" name="submit">Add Data</button>
</form>
<?php
}
include('connect-db.php');
if (isset($_POST['submit']))
{
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$schita = mysql_real_escape_string(htmlspecialchars($_POST['schita']));
if ($name == '')
{
$error = 'Error !!';
renderForm($name, $schita, $error);
}
else
{
mysql_query("INSERT players SET name='$name', schita='$schita'")
or die(mysql_error());
header("Location: mobila.php");
}
}
else
{
renderForm('','','','','');
}
?>
This script creates a page for each ID when we insert data in the form
Like pagename.php?id=4
I want when i fill the form after he create the page when i open the page to see the uploaded file only on that page,
any idea why its not working?
Get the request file using $_FILES, also you need to confirm your mysql field (schita) is a blob type
You need to correct insert query. You are missing 'into' keyword. Change query to:
mysql_query("INSERT into players SET name='$name', schita='$schita'");
You need to convert image to base64 and then save it to Database.
// Select file type
$target_file = basename($_FILES["file"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Convert to base64
$image_base64 = base64_encode(file_get_contents($_FILES['schita']['tmp_name']) );
$image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
// Insert record
$query = "INSERT into players(schita) values('".$image."')";
mysqli_query($con,$query);
I have managed to upload the file using this script
<?php
$dbh = new PDO("mysql:host=localhost;dbname=highmob_comenzi", "highmob", "PW");
if(isset($_POST['btns'])){
$name = $_FILES['myfile']['name'];
$type = $_FILES['myfile']['type'];
$data = file_get_contents($_FILES['myfile']['tmp_name']);
$stmt = $dbh->prepare("UPDATE players SET data='$myfile', name='$name', mime='$type' WHERE id='$id'");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$type);
$stmt->bindParam(3,$data);
$stmt->execute();
}
?>
<!-- form -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile"/>
<button name="btns"> Incarca Schita </button>
</form>
<!-- display data -->
<?php
$stat = $dbh->prepare("select * from players");
$stat->execute();
while($row = $stat->fetch()){
echo "<a target='_blank' href='viewschita.php?id=".$row['id']."'>".$row['name']."</a>";
}
?>
The problem is i got no idea how to make a link to the file, any idea how?
I am trying to execute below code but it gives me an error that 'trying to get property of non-object in c....' .
This code should pull up info about 'images' and 'texts' to be displayed on the index.php page. I have tried in all means but couldn't figure out what is the problem; I am a beginner in PHP by the way :) .I will appreciate if you please help me.
<!DOCTYPE html>
<?php
$alert = "";
//if upload button is pressed
if(isset($_POST['upload'])){
//the path to store the uploaded image
$target = "images/".basename($_FILES['image']['name']);
//connect to the database
$conn = new mysqli('localhost', 'imgcms', '', '');
//Get all the submitted data from thye form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO images (image, text) VALUES ('$image', '$text')";
//Move the uploaded image into the folder: images
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
$alert = "Image uploaded successfully";
}else{
$alert = "There was a problem uploading the image";
}
}
?>
<html>
<head>
<title>ImageBlogger</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content">
<?php
//connect to the database to display image from the database
$conn = new mysqli('localhost', 'imgcms', '', '');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if($result->num_rows > 0){
//output data of each row: image and text
while($row = $result->fetch_assoc()){
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
}else{
echo "0 results";
}
$conn->close();
?>
<form action="index.php" method="post" autocomplete="off" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols"40" rows="4" placeholder="Content..."></textarea>
</div>
<div>
<input type="submit" name="upload" value="Post the content">
</div>
</form>
</div>
</body>
</html>
Copying your code into an editor it looks like line 47 is;
if($result->num_rows > 0)
Before this line add the following and see if you get an error.
if (!$result) {
echo 'Query Error is: ' . $conn->error;}
I have code for image upload and view in php and MySQL. After click on "Submit" button in "imageUpload.php" page image is stored in database. but not displaying in "listImages.php" page. I don't know what's the problem. I see "image not displaying when uploading in php" but its seems different solution for me. here is my code please have a look where i am wrong.
imageUpload.php :
<?php
/* CREATE TABLE IF NOT EXISTS `output_images`
(
`imageId` tinyint(3) NOT NULL AUTO_INCREMENT,
`imageType` varchar(25) NOT NULL DEFAULT '',
`imageData` mediumblob NOT NULL,
PRIMARY KEY (`imageId`)
) */
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysqli_connect("localhost", "root", "");
mysqli_select_db ("test");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO output_images(imageType ,imageData)
VALUES('{$imageProperties['mime']}', '{$imgData}')";
$current_id = mysqli_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image to MySQL BLOB</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</BODY>
</HTML>
listImages.php :
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db("test");
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
$result = mysqli_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" /><br/>
<?php
}
mysqli_close($conn);
?>
</BODY>
</HTML>
imageView.php :
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db("test") or die(mysqli_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysqli_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysqli_error());
$row = mysqli_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
mysqli_close($conn);
?>
this would help you
<a href="imageView.php?image_id=<?php echo $row["imageId"]; ?>">
<img src="<?php echo $row['imagedata']; ?>" alt="my picture" height="128" width="128" />
</a>
it should be
$conn=mysqli_connect("ur_servername_ex_localhost","ur_username","ur_password","ur_db");
mysqli_query($conn, $sql);
I setup a little site for my roomate whose an artist, and I set it up where he could use an admin.php page to upload images to the site, and they are added to a MYSQL Database where the main site pulls them from and displays them.
He wants the option to remove images from the same page he adds images, so I wrote a little code to display them again and add a "remove" link to each one. I can't figure out what a good way would be to actually code the rest of it where it actually removes the image when he clicks it.
Can anyone possibly shed some light, urls, etc. that may help to get this finished? Here is what the admin.php looks like thus far...
<html>
<head><title>SethClem.com Image Management</title></head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
Image File: <input type="file" name="image" /><br />
Description: <input type="text" name ="description" ><br>
<input type="submit" value="upload" />
</form>
<?php
include("../database.php");
// Connects to your Database
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()) ;
mysql_select_db($dbname) or die(mysql_error()) ;
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM images") or die(mysql_error());
?>
<div style="width:100%; height:105px; border:0 ; padding:5px;">
<table><tr>
<?php
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
$image = "../images/".$info['image'];
?>
<td>
<img src="<?php echo $image ?>" style="width:191; height:124; border:0px ; float:left;" />
remove
</td>
<?php
}
?>
</tr>
</table>
</div>
$action = !empty($_GET['action'])?$_GET['action']:false;
$id = !empty($_GET['id'])?$_GET['id']:false;
switch ($action) {
case 'delete':
if ($id !== false)
{
mysql_query("delete from `images` where `id`='$id' limit 1;");
//unlink($path_to_image.'/'.$file_name);
}
break;
default:
echo 'No known action was passed through (Test Message, will be removed)';
}
replace
remove
with remove
now, put this php code imediatly after the db connection:
if( isset( $_GET['action'] ) && ( $_GET['action == 'delete' ) )
{
$id = $_GET['id'];
mysql_query("delete from `images` where `id`='$id' limit 1;");
unlink($path_to_image.'/'.$file_name);
}