Can anyone help me with this, i have checked the SQL table names multiple times but every time i attempt to post it gives me an error. Pretty new to this. Thanks in advance.
require_once('connect.php');
if (isset($_POST['add_product'])):
$product_description=$_POST['product_description'];
$price=$_POST['price'];
$reorder_level=$_POST['reorder_level'];
$current_level=$_POST['current_level'];
$imagename = $_FILES['image']['name'];
$add_this = "products/$imagename";
move_uploaded_file($_FILES['image']['tmp_name'],$add_this);
$my_query="INSERT INTO products VALUES ('','$product_description','$price','$reorder_level','$current_level', '$imagename')";
$result= mysqli_query($connection, $my_query);
if ($result):
echo "<b>Item Successfully Added!</b>";
echo "File ";
echo $_FILES['image']['name'];
echo " was uploaded - ";
echo $_FILES['image']['size'];
echo " bytes in size<br>Temporary name: ";
echo $_FILES['image']['tmp_name'];
echo " - file type: ";
echo $_FILES['image']['type'];
else:
echo "<b>ERROR: unable to post.</b>";
endif;
endif;
require_once 'header1.php';
?>
Here is the form im using
<H1>Add a New Product</H1>
<table>
<form method=post action="addproduct.php" enctype="multipart/form-data">
<tr><td><b>Product Description:</b><td><input type="text" name="product_description" size="30">
<tr><td><b>Price:</b><td><input type="text" name="price">
<tr><td><b>Re Order Level:</b><td><input type="text" name="reorder_level">
<tr><td><b>Stock Level:</b><td><input type="text" name="current_level">
<tr><td><b>Add Image:</b><td><input type="file" name="image">
<tr><td><input type="submit" name="add_product" >
</form>
</table>
</body>
<?php
require_once('connect.php');
$mysql = new MYSQLI("host", "username", "password", "database");
if (isset($_POST['add_product'])):
$product_description = $_POST['product_description'];
$price = $_POST['price'];
$reorder_level = $_POST['reorder_level'];
$current_level = $_POST['current_level'];
$imagename = $_FILES['image']['name'];
$add_this = "products/$imagename";
move_uploaded_file($_FILES['image']['tmp_name'],$add_this);
$mysql->query("INSERT INTO products (`NAME OF CELL IN TABLE WHERE YOU WANT SAVE0 $product_description`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $price`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $reorder_level`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $current_level`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $imagename`) VALUES ('{$product_description}', '{$price}', '{reorder_level}', '{$current_level}', '{$imagename}')");
if ($result) {
echo "<b>Item Successfully Added!</b>";
echo "File ";
echo $_FILES['image']['name'];
echo " was uploaded - ";
echo $_FILES['image']['size'];
echo " bytes in size<br>Temporary name: ";
echo $_FILES['image']['tmp_name'];
echo " - file type: ";
echo $_FILES['image']['type'];
}
else {
echo "<b>ERROR: unable to post.</b>";
}
require_once('header1.php');
?>
Try this, but set your information on line 3 ($mysql)
and on line 15 ($mysql->query).
Related
I have a form that the user could upload their image and write the id, I want the image to automatically rename to the id that they wrote in the form.The current code is able to rename the image according to the id in the folder to the desired id, however, i need the image name to change to the desired id in the database too, but the image name in the database is still the original name.
<?php
$servername="localhost";
$username="root";
$password="";
$db = mysqli_connect($servername,$username,$password,"ecom_product");
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
//$destination_path = getcwd().DIRECTORY_SEPARATOR;
$item_code = $_POST['code'];
$filename = $_FILES["image"]["name"];
$source = $_FILES["image"]["tmp_name"];
$path_parts = pathinfo($_FILES["image"]["name"]);
$extension = $path_parts['extension'];
$destination = "img/$item_code." . $extension;
move_uploaded_file($source, $destination);
// Get all the submitted data from the form
$item_code = $_POST['code'];
$cat_name = $_POST['category'];
$item_name = $_POST['item_name'];
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$price = $_POST['price'];
$sql = "INSERT INTO ecom_item (item_code, cat_name, item_name, image, text, price) VALUES ('$item_code','$cat_name','$item_name','$image','$text','$price')";
mysqli_query($db,$sql); // stores the submitted data into the database table : item
if(!is_dir("img/"))
{
mkdir("img/");
}
// move uploaded image to the folder : img
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<!--<link rel="stylesheet" type="text/css" href="formstyle.css">-->
</head>
<body>
<?php
$servername="localhost";
$username="root";
$password="";
$db = mysqli_connect($servername,$username,$password,"ecom_product");
$sql = "SELECT * FROM ecom_item ORDER BY item_code ASC";
$result = mysqli_query($db, $sql);
?>
<center>
<form name='show_item' action="exampleadditem.php" method='POST' align="center" enctype="multipart/form-data">
<h2 align="center">View Item</h2>
<td><input type="submit" name="upload" value="Add New Item" action="exampleadditem.php" style="WIDTH: 98px; HEIGHT: 36px" size="18"><td>
<br/><br/>
<table border=1 align="center" width="900">
<tr>
<th>Item Code<th>Category<th>Item Name<th>Image<th>Description<th>Price (RM)<th>Actions</th>
</tr>
<?php
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<div id='img_div'>";
echo "<td width='60'>".$row['item_code']."</td>";
echo "<td width='80'>".$row['cat_name']."</td>";
echo "<td width='80'>".$row['item_name']."</td>";
echo "<td width='65'><img src='img/".$row['image']."'width=30 height=30></td>";
echo "<td width='250'>".$row['text']."</td>";
echo "<td width='25'>".$row['price']."</td>";
echo"<td width='90'><a href='editform.php?item_code=".$row['item_code']."'>Edit</a> |
<a href='delete.php?item_code=".$row['item_code']."'>Delete</a></td>";
echo "</div>";
echo "</tr>";
}
?>
</table>
</center>
</form>
</body>
</html>
edit: the image name did change to item code in the img folder but in the database it remains the original name.
Database table image
<?php
include('../connect.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM discharge WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
echo '<img src=../'.$row['ppic'].' style="float:left; margin-right:10px;">';
echo '<img src=../'.$row['ppic1'].' style="float:left; margin-right:10px;">';
}
?>
<form action="editpicexec.php" method="post" enctype="multipart/form-data">
<br>
<input type="hidden" name="roomid" value="<?php echo $_GET['id']; ?>">
Select Image
<br>
<input type="file" name="image[]" multiple="multiple" /><br>
<input type="file" name="image1"><br>
<input type="submit" value="Upload">
</form>
discharge is my table database, I want to add picture multiple at in one input.
in this code I am opening a file one at a time, but I want to add multiple picture and then save in the field on the database
<?php
include('../connect.php');
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}else
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
$image_size= getimagesize($_FILES['image']['tmp_name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"../images/" . $_FILES["image"]["name"]);
$location="images/" . $_FILES["image"]["name"];
$roomid=$_POST['roomid'];
if(!$update=mysql_query("UPDATE discharge SET ppic = '$location' WHERE id='$roomid'"))
if (!isset($_FILES['image1']['tmp_name'])) {
echo "";
}else
$file=$_FILES['image1']['tmp_name'];
$image1= addslashes(file_get_contents($_FILES['image1']['tmp_name']));
$image1_name= addslashes($_FILES['image1']['name']);
$image1_size= getimagesize($_FILES['image1']['tmp_name']);
move_uploaded_file($_FILES["image1"]["tmp_name"],"../images/" . $_FILES["image1"]["name"]);
$location="images/" . $_FILES["image1"]["name"];
$roomid=$_POST['roomid'];
if(!$update=mysql_query("UPDATE discharge SET ppic1 = '$location' WHERE id='$roomid'"))
?>
Then this is my process I dont know how can I upload on database in single input with many pictures . ppic and ppic1 is the name of my field on my database.
if I understood your question right. You might want to use foreach to go through all file in image input like this:
foreach ($_FILES['image'] as $one_file){
$file=$one_file['tmp_name'];
// rest of code
// in the case you want to save all path in same field, change the line bellow like this
// if(!$update=mysql_query("UPDATE discharge SET ppic = concat(ppic, '$location' ) WHERE id='$roomid'"))
}
?>
Instead of concat(ppic, '$location' ) you can use CONCAT_WS(',', ppic, '$location') to separate it by comma.
First off, I am VERY new to PHP coding. I've been more than a few days getting everything to work that is working and have been watching hours of video. Yet, for the life of me, I cannot get this to "completely" function.
When I click my upload button, the author, date_time group, and the comment work fine. They are posting to the database and posting to the "GET" section when I click upload. The thumbnail on the other hand just gives the broken path image. I'm sure it's something I'm not defining correctly, but I am completely lost. I have posted my comment box form source code, connection, and functions. My database is in commentsection/comments/image. The "image" column of the database type is set to BLOB.
Please help...
SOURCE CODE:
<?php
echo "<form method='POST' enctype='multipart/form-data 'action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<label>Upload Image</label><br>
<input type='file' name='image' id='image'><br>,<br>
<textarea name='message'></textarea><br><br>
<button type='submit' name='commentSubmit'>Upload</button>
</form>";
getComments($conn);
?>
CONNECTION:
$conn = mysqli_connect('localhost','root','', 'commentsection');
if (!$conn) {
die("Connection failed:".mysqli_connect_error());
}
FUNCTIONS:
<?php
function setComments($conn) {
if (isset($_POST['commentSubmit'])) {
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$image = $_POST['image'];
$sql = "INSERT INTO comments (uid, date, image, message) values ('$uid', '$date','$image', '$message')";
$result = mysqli_query($conn, $sql);
}
}
function getComments($conn) {
$sql = "SELECT * FROM comments ORDER BY date DESC LIMIT 10";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<div class='commentbox'><p>";
echo $row['uid'];
echo $row['date']."<br>";
echo "<div class='thumbnail'>";
echo "<img src='".$row['image']."'>";
echo "</div>";
echo nl2br($row['message']);
echo "<p></div>"."<br>";
}
}
I'm sorry if this is a repost. But I have seen many questions without finding the right answer
i'm trying to upload multiple files + some information , but if i submit my form with 2 images it goes ok and the script runs perfect when i upload more then 2 or 3 files i get undefined indexs of all the form elements .
up.php
/////// Random name generator ////////
function random_name($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
//sql//
require("sql.php");
//////////
//!!! some vars !!!//
//
$total = count($_FILES['pimages']['name']);
//
$foldername = random_name(15);
$target_dir = "../images/projects/".$foldername."/";
$target_file = $target_dir . basename($_FILES["icon"]["name"]);
$uploadyes = 1;
$imageType = pathinfo($target_file,PATHINFO_EXTENSION);
$saveicon = $target_dir . "icon." .$imageType;
/////submited form vars /////
$linkedid = $_POST['lid'];
$date = date("y.m.d H:i:s");
$name = $_POST['projectname'];
$loc = $_POST['location'];
$type = $_POST['type'];
$des = $_POST['des'];
$precara = $_POST['cara'];
$client = $_POST['client'];
$col = $_POST['cost'];
$bua = $_POST['builtup'];
////////////////cara slice /////////////
$caraxarray = explode("," , $precara);
$cara = base64_encode(serialize($caraxarray));
echo $imageType ;
///////////////////////// Start of the upload check ////////////////////
if(isset($_POST['submit']) && !empty($name)) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
// Check if $uploadyes is set to 0 by an error
if (!isset($_POST['submit'])) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
mkdir($target_dir);
if (move_uploaded_file($_FILES["icon"]["tmp_name"], $saveicon)) {
//////////////////////////..........................//////////////////
// Loop through each file
$imgext = array();
for($i=0; $i<=$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['pimages']['tmp_name'][$i];
$x = $i + 1 ;
if ($tmpFilePath != ""){
//Setup our new file path
$pimgex = $_FILES['pimages']['name'][$i];
$pimageType = pathinfo($pimgex,PATHINFO_EXTENSION);
$newFilePath = $target_dir ."img".$x.".".$pimageType;
array_push($imgext , "$newFilePath");
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "yeaaaaaah";
}
}
}
$str = serialize($imgext);
$sql1 = "INSERT INTO projects (date, name, type, location, icon, imgext, folder, linkedid)
VALUES ('$date', '$name','$type', '$loc', '$saveicon' , '$str', '$foldername', '$linkedid')";
$sql2 = "INSERT INTO projectdetails (proname, prolocation, prodes, procara, client, col, builtarea, linkedid)
VALUES ('$name', '$loc','$des', '$cara', '$client' , '$col', '$bua', '$linkedid')";
mysqli_query($conn ,$sql1);
mysqli_query($conn ,$sql2);
mysqli_close($conn);
/////////////////...........................////////////////////////
header("location:cp.php");
} else {
echo "Sorry, there was an error uploading your file.";
}
}
projectsuploader.php
$lkid = random_name(8);
$tlink = random_name(6);
require("sql.php");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql1 = "SELECT id, date, name, type, location FROM projects";
$sql2 = "SELECT id, titleen FROM projectsnav";
$result = mysqli_query($conn, $sql1);
$types = mysqli_query($conn, $sql2);
//mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<h2>Projects Page</h2>
<h5>projects</h5>
<table>
<tr>
<td>#</td>
<td>Date & Time</td>
<td>Project name</td>
<td>Project type</td>
<td>Project location</td>
<!--<td>View</td>
<td>Edit</td>-->
<td>Remove</td>
</tr>
<?php
if (mysqli_num_rows($result) > 0) {
// output data of each row .$row["id"]
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["id"]."</td>";
echo "<td>".$row["date"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["type"]."</td>";
echo "<td>".$row["location"]."</td>";
echo "<td><a href='../del.php?id=".$row['id']."'>Remove</a></td> </tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</table>
<h4 id="addproject">Add Project</h3>
<h4 id="addtype">Add Type </h4>
<div id="frontlayer">
<div id="addpro">
<h2 style="text-align:center;"> add project </h2>
<form method="POST" action="up.php" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="50000000">
id:<input type="text" name="lid" value="<?php echo $lkid ; ?>" readonly> <br>
project name:<input type="text" name="projectname"><br>
Type:<select name="type">
<?php
if (mysqli_num_rows($types) > 0){
while($navrow = mysqli_fetch_assoc($types)) {
echo "<option value='".$navrow['titleen']."'>".$navrow['titleen']." </option>";
}
}else{
echo "<option>PLEASE ADD TYPES TO DATABASE FIRST!!!!ERROR 0 TYPES IN DATABASE</option>";
}
mysqli_close($conn);
?>
</select>
<br>
location:<input type="text" name="location"><br>
icon:<input type="file" name="icon" id="icon"><br>
images:<input type="file" name="pimages[]" id="pimages" multiple><br>
<input type="hidden" name="sendfiles" value="Send Files" />
<!--
------//////////////------
------//////////////------
------//////////////------
-->
description:<input type="text" name="des"><br>
caracteristic:<input type="text" name="cara" data-role="tagsinput"><br>
client:<input type="text" name="client"><br>
Collaborator:<input type="text" name="cost"><br>
Gross Area:<input type="text" name="builtup"><br>
<input type="submit" value="Upload" name="submit">
</form>
</div>
Sorry if it is bad writed i\m begginer , Thanks in advance for anyhelp
The problem were that there was a big file (4mb image) and php was not able to post this size of an image so you have to resize your image before upload ..
and big thanks for Felippe Duarte.
i'm new in programming and have been working on a searchable database which can retrieve images by typing in keywords and after pressing submit will show results and the picture.
But so far i have no luck in getting the picture to show(broken link/image) but my search form does work and does correctly retrieve the name or result.
My table in phpmyadmin name is shoes , and i have 3 columns, 1 id (int15 PRI) ,2 brand/model (varchar 50), 3 picture (longblob).
My code is relative simple and hope you can help me out =)
File name: search.php
<form action="search.php" method="POST">
Name: <input type ="text" name="search_name"> <input type="submit" value="Search">
<?php
if (isset($_POST['search_name'])) {
$search_name = $_POST['search_name'];
if (!empty($search_name)){
if (strlen($search_name)>=3) {
$query = "SELECT * FROM `shoes` WHERE `brand/model` LIKE '%".mysql_real_escape_string($search_name)."%'";
$query_run = mysql_query($query);
$query_num_rows = mysql_num_rows($query_run);
if ($query_num_rows>=1) {
echo $query_num_rows.' Results found:<br>';
while ($query_row = mysql_fetch_array($query_run)) {
$picture = $query_row['picture'];
echo "</br>";
echo $query_row ['brand/model'];
echo "</br>";
echo "</br>";
//header("content-type: image/jpeg");
echo "<img src=image.php?id=".$row['id']." width=300 height=200/>";
echo "</br>";
}
} else {
echo 'No Results Found.';
}
} else {
echo 'Text field must be more than 3 characters.';
}
} else {
echo 'Text Field Cannot be Empty!';
}
}
?>
i have a image.php here
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysql_connect("localhost","root","");
if(!$conn){
echo mysql_error();
}
$db = mysql_select_db("phsdatabase");
if(!$db){
echo mysql_error();
}
$id = $_GET['id'];
$query = "SELECT `picture` FROM shoes where id='$id'";
$query_run = mysql_query("$query",$conn);
if($query_run){
$row = mysql_fetch_array($query_run);
$type = "Content-type: image/jpeg";
header($type);
echo $row['picture'];
} else {
echo mysql_error();
}
?>
storeinfo.php to store new info,
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysql_connect("localhost","root","");
if(!$conn)
{
echo mysql_error();
}
$db = mysql_select_db("phsdatabase",$conn);
if(!$db)
{
echo mysql_error();
}
#$brandmodel = $_POST['brand/model'];
#$picture = addslashes (file_get_contents($_FILES['picture']['tmp_name']));
#$image = getimagesize($_FILES['picture']['tmp_name']);//to know about image type etc
//$imgtype = $image['mime'];
if (isset($_POST['brand/model'])){
$brandmodelentry = $_POST['brand/model'];
if (!empty($brandmodelentry)){
if (strlen($brandmodelentry)>=3) {
$query ="INSERT INTO shoes VALUES('','$brandmodel','$picture')";
$query_run = mysql_query($query,$conn);
echo '<br>';
echo "Information Stored Successfully!";
} else {
echo mysql_error();
}
echo '<br>';
echo '<br>';
echo "Thank you for Registering new information to our database!";
} else{
echo 'Text Field cannot be empty!';
}
}
?>
newentry.php which register new info
<form enctype="multipart/form-data" action="storeinfo.php" method="POST">
<center>Shoes Information</center>
Brand and Model Name<input type=text name="brand/model">
Picture of Shoes(Acceptable formats:<br>JPEG,JPG,PNG)<input type="file" name="picture" id ="picture">
<input type=submit name="submit" value="Store Information">
Your code is absolutely correct except single line i.e.
echo "<img src=image.php?id=".$row['id']." width=300 height=200/>";
You have to change the line to :
echo '<img src="data:image/jpeg;base64,'
.base64_encode($image['file_data']).'" width=300 height=200/>";
In my experience, the problem my image was broken when I tried to display it from database is the the length of the image, I mean from the database where you put the length of a varchar you should change it to long text.
Your image source should be image file extension not php extension, Please check :
echo "<img src='any jpg,png or gif exetension path' width='300' height='200' />";
for example:
echo "<img src='imagename.png' width='300' height='200' />";