Changing image name in XAMPP database by using PHP - php

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

Related

Multiple upload picture to mysql using php

<?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.

can't upload multiple files in a form

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.

Adding data through php into sql

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).

Delete Query won't work on the first row using MySQL & PHP

When I was trying to delete first row of this table, it won't delete, rather it shows me error that kindly put details in text box which I have used while Adding New Category.
IMAGE : https://dl.dropboxusercontent.com/u/88831139/1.jpg
Except Row 1, query works on each row. If I click delete for ID 2, 3 or 4, all works fine, except for Row 1. It does not work with ID=1.
Kindly do suggest me what to do.
NOTE: I have used session to keep the values in variables.
I am not deleting row i just update the status of that to keep it in record here is Code :
to ADD CATEGORY :
if(isset($_POST['category']))
{ $cat = $_POST['category'];
$validate_category = "SELECT * FROM Category WHERE CategoryName ='$cat'";
$result = mysql_query($validate_category);
$count = mysql_num_rows($result);
if(empty($cat))
{
session_start();
$msg = 'kindly Put Details completely';
$_SESSION['status'] = $msg;
$_SESSION['color'] = 'red';
header("location:../category.php");
}
else if($count==1)
{
session_start();
$msg = 'Category Already Exist !!! Kindly Choose any Other Category';
$_SESSION['status'] = $msg;
$_SESSION['color'] = 'red';
header("location:../category.php");
}
else{
$query = "INSERT INTO Category(CategoryName) values ('$cat')";
mysql_query($query);
session_start();
$msg = 'New Category has been Created';
$_SESSION['status'] = $msg;
$_SESSION['color'] = 'green';
header("location:../category.php");
}}
CODE TO DELETE ROW :
$delete_id = mysql_real_escape_string($_POST["delete_id"]);
$del_cat = mysql_result(mysql_query("SELECT CategoryName FROM Category WHERE ID = ".$delete_id), 0); // 1 = row
mysql_query("UPDATE Category SET hidden = '1' WHERE ID =".$delete_id);
session_start();
$msg = "'$del_cat' Category has been Deleted";
$_SESSION['status'] = $msg;
$_SESSION['color'] = 'green';
header("location:../category.php");
HOME PAGE :
<?php
session_start();
if(!isset($_SESSION['UserEmail']))
{
header("location:../login.php");
}
else if($_SESSION['UserRole'] != 'Admin')
{
header("location:../login.php");
}
include "../_inc/config.php";
?>
<html>
<head>
<title>Add Category</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php include "_lib/menu.php"; ?>
<h2>Add Category</h2>
<form action="_lib/AddCategory.php" method="POST">
Category : <input type='text' name="category"/>
<input type="Submit" value="Submit" />
<?php
if (isset($_SESSION['status'])){
$msg = $_SESSION['status'];
echo $msg;
unset($_SESSION['status']);
}
?>
<table border='1'>
<tr>
<th>ID</th>
<th>Category</th>
</tr>
<?php
$query1 = "SELECT * from Category where hidden = '0'";
$result = mysql_query($query1);
$i = 1;
while($row = mysql_fetch_array($result)) : ?>
<tr>
<td> <?php echo $i; $i=$i+1; ?> </td>
<td> <?php echo $row['CategoryName']; ?> </td>
<td>
<form action="_lib/DeleteCategory.php" method="POST" >
<input type="hidden" name="delete_id" value="<?php echo $row['ID']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
</table>
</form>
</body>
</html>

editing existing image php mysql

I have the following code that displays a given image using php echo id from a mysql table. The php is:
<?php include 'dbc.php'; page_protect();
$id=$_GET['id'];
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = #ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
?>
<?php
if($_FILES['photo'])
{
$target = "images/furnishings/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$pic = "images/furnishings/" .(mysql_real_escape_string($_FILES['photo']['name']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("update `furnishings` set `photo`='$pic' WHERE id='$id'") ;
echo "Image updated";
}
else
{
echo "Please select a new image to upload";
}
}
?>
The HTML is:
<form enctype="multipart/form-data" action="editfurnimage.php" method="POST">
<table width="450" border="2" cellpadding="5"class="myaccount">
<tr>
<td width="35%" class="myaccount">Current Image: </td>
<td width="65%"><img src='<?php
mysql_select_db("dbname", $con);
mysql_set_charset('utf8');
$result = mysql_query("SELECT * FROM furnishings WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
echo '' . $row['photo'] . '';
}
mysql_close($con);
?>' style="width:300px; height:300px;"></td>
</tr>
<tr>
<td class="myaccount">New Image: </td>
<td><input type="file" name="photo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" class="CMSbutton" value="Add" /></td>
</tr>
</table>
</form>
While the coding is adding the new image to the server, the mysql table doesnt seem to be updating with the new image - in fact no changes are being made - when I adjust the line:
mysql_query("update `furnishings` set `photo`='$pic' WHERE id='$id'") ;
to:
mysql_query("update `furnishings` set `photo`='$pic' WHERE id='8'") ;
it works though so assuming the issue is lying with this part of the code but not sure how to correct the code to pull the $id into the php correctly.
Finally, when the script runs I am trying to get the page "editfurnimage.php?id=$id" to reload following the user clicking the Add button - at the moment the page that is returned is "editfurnimage.php" which obviously doesnt show up any data from the table.
Any help much appreciated - and as always feel free to tear my coding apart - still learning!!
Thanks
JD
try to remove your single quotes around $id.
If your id field in the database in an int, then quotes should not be used around it.
EDIT: Missed this one - Where is $_GET['id'] being sent from, because your form sure isn't sending any id in the $_GET scope? Try adding the input with a name of 'id' and a value for it in to your form. also, use $_POST in your php file, not $_GET.
In your php, replace:
$id=$_GET['id'];
With
if(isset($_POST['id'])){
$id=$_POST['id'];
}else{
$id=$_GET['id'];
}
Then in your html add:
<input type="hidden" name="id" value="<?php echo $id; ?>"/>

Categories