i'm trying to save image in database and images folder in same time, the image it's saving in images folder but not in database can someone please help i don't know what im doing wrong.
add.php
<?php
if (!defined('WEB_ROOT')) {
exit;
}
$errorMessage = (isset($_GET['error']) && $_GET['error'] != '') ? $_GET['error'] : ' ';
?>
<script>
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCategory(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('catdiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<div class="content-box-header">
<h3>Add New Restaurant</h3>
</div>
<form action="processTopping.php?action=add" method="post" enctype="multipart/form-data" name="frmAddTopping" id="frmAddTopping">
<table width="100%" border="0" align="center" cellpadding="5" cellspacing="1" class="entryTable">
<tr>
<td width="150" class="label">Restaurant Name</td>
<td class="content"><input name="txtName" class="text-input large-input" type="text" id="txtName" /></td>
</tr>
<tr>
<td class="label">Restaurant Email</td>
<td class="content"><input name="txtEmail" class="text-input large-input" type="text" id="txtEmail" /></td>
</tr>
<tr>
<td class="label">Restaurant Phone</td>
<td class="content"><input name="txtPhone" class="text-input large-input" type="text" id="txtPhone" /></td>
</tr>
<tr>
<td class="label">Restaurant Address</td>
<td class="content"><input name="txtAddress" class="text-input large-input" type="text" id="txtAddress" /></td>
</tr>
<tr>
<td class="label">Restaurant Cuisine</td>
<td class="content"><input name="txtCuisine" class="text-input large-input" type="text" id="txtCuisine" /></td>
</tr>
<tr>
<td class="label">Restaurant Mini Order</td>
<td class="content"><input name="txtMini_order" class="text-input large-input" type="text" id="txtMini_order" /></td>
</tr>
<tr>
<td class="label">Restaurant Suburbs</td>
<td class="content"><input name="txtSuburbs" class="text-input large-input" type="text" id="txtSuburbs" /></td>
</tr>
<tr>
<td width="150" class="label">Restaurant Menu</td>
<td class="content"><input name="txtMenu" class="text-input large-input" type="text" id="txtMenu" /></td>
</tr>
<tr>
<td class="label">Restaurant Reviews</td>
<td class="content"><input name="txtReviews" class="text-input large-input" type="text" id="txtReviews" /></td>
</tr>
<tr>
<td class="label">Restaurant Logo</td>
<td class="content"><input name="txtLogo" class="text-input large-input" type="text" id="txtLogo" /></td>
</tr>
<tr>
<td class="label">Restaurant Takeaway Hours</td>
<td class="content"><input name="txtTakeawayHours" class="text-input large-input" type="text" id="txtTakeawayHours" /></td>
</tr>
<tr>
<td class="label">Restaurant Delivery Hours</td>
<td class="content"><input name="txtDeliveryHours" class="text-input large-input" type="text" id="txtDeliveryHours" /></td>
</tr>
<tr>
<td class="label">Restaurant Map</td>
<td class="content"><input name="txtMap" class="text-input large-input" type="text" id="txtMap" /></td>
</tr>
<tr>
<td class="label">Restaurant Promotions</td>
<td class="content"><input name="txtPromotions" class="text-input large-input" type="text" id="txtPromotions" /></td>
</tr>
<!-- <tr>
<td width="150" class="label">Image</td>
<td class="content"> <input name="fleImage" type="file" id="fleImage" class="box"> </td>
</tr>-->
<tr>
<td class="label" valign="middle">Images</td>
<td class="label">
<div id="main">
<table width="230" cellpadding="0">
<tr>
<td width="232" align="right">
<input type="file" name="fleImage[]" /></td>
</tr>
</table>
</div></td>
</tr>
</table>
<p align="center">
<input name="btnAddTopping" type="button" id="btnAddTopping" value="Add Restaurant" onClick="checkAddToppingForm();" class="button">
<input name="btnCancel" type="button" id="btnCancel" value="Cancel" onClick="window.location.href='index.php';" class="button">
</p>
</form>
processTopping.php
<?php
require_once '../../library/config.php';
require_once '../library/functions.php';
error_reporting(E_ALL);
checkUser();
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'add' :
addTopping();
break;
case 'modify' :
modifyTopping();
break;
case 'delete' :
deleteTopping();
break;
default :
// if action is not defined or unknown
// move to main Topping page
header('Location: index.php');
}
function addTopping()
{
$name = $_POST['txtName'];
$email = $_POST['txtEmail'];
$phone = $_POST['txtPhone'];
$address = $_POST['txtAddress'];
$cuisine = $_POST['txtCuisine'];
$mini_order = $_POST['txtMini_order'];
$suburbs = $_POST['txtSuburbs'];
$menu = $_POST['txtMenu'];
$reviews = $_POST['txtReviews'];
$logo = $_POST['txtLogo'];
$takeaway_hours = $_POST['txtTakeawayHours'];
$delivery_hours = $_POST['txtDeliveryHours'];
$map = $_POST['txtMap'];
$promotions = $_POST['txtPromotions'];
$sql = "INSERT INTO restaurant_info(name, email, phone, address, cuisine, mini_order, suburbs, menu, reviews, logo, takeaway_hours, delivery_hours, map, promotions)
VALUES ('$name','$email','$phone','$address','$cuisine','$mini_order','$suburbs','$menu','$reviews','$logo','$takeaway_hours','$delivery_hours','$map','$promotions')";
dbQuery($sql);
header('Location: index.php');
}
//image
$uploadDir = '../../images/';
for($i=0;$i<count($_FILES["fleImage"]["name"]);$i++)
{
if($_FILES["fleImage"]["tmp_name"][$i] != '')
{
$image = $_FILES["fleImage"];
if (trim($image['tmp_name'][$i]) != '') {
$ext = substr(strrchr($image['name'][$i], "."), 1); //$extensions[$image['type']];
// generate a random new file name to avoid name conflict
$imagePath = md5(rand() * time()) . ".$ext";
list($width, $height, $type, $attr) = getimagesize($image['tmp_name'][$i]);
// make sure the image width does not exceed the
// maximum allowed width
if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
$result = createThumbnail($image['tmp_name'][$i], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
$imagePath = $result;
} else {
$result = move_uploaded_file($image['tmp_name'][$i], $uploadDir . $imagePath);
}
if ($result) {
// create thumbnail
$thumbnailPath = md5(rand() * time()) . ".$ext";
$result = createFixThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH,THUMBNAIL_HEIGHT);
// create thumbnail failed, delete the image
if (!$result) {
unlink($uploadDir . $imagePath);
$imagePath = $thumbnailPath = '';
} else {
$thumbnailPath = $result;
}
} else {
// the product cannot be upload / resized
$imagePath = $thumbnailPath = '';
}
}
mysql_query("INSERT INTO restaurant_info(Rest_Logo)
VALUES ('$Rest_Logo')";
}
}
/*
Modify a Topping
*/
function modifyTopping()
{
$toppingId = (int)$_POST['hidToppingId'];
$name = $_POST['txtName'];
$email = $_POST['txtEmail'];
$phone = $_POST['txtPhone'];
$address = $_POST['txtAddress'];
$cuisine = $_POST['txtCuisine'];
$mini_order = $_POST['txtMini_order'];
$suburbs = $_POST['txtSuburbs'];
$menu = $_POST['txtMenu'];
$reviews = $_POST['txtReviews'];
$logo = $_POST['txtLogo'];
$takeaway_hours = $_POST['txtTakeawayHours'];
$delivery_hours = $_POST['txtDeliveryHours'];
$map = $_POST['txtMap'];
$promotions = $_POST['txtPromotions'];
$sql = "UPDATE restaurant_info
SET name='$name', email='$email', phone='$phone', address='$address', cuisine='$cuisine', mini_order='$mini_order', suburbs='$suburbs', menu='$menu', reviews='$reviews', logo='$logo', takeaway_hours='$takeaway_hours', delivery_hours='$delivery_hours', map='$map', promotions='$promotions'
WHERE rest_id = $toppingId";
dbQuery($sql);
header('Location: index.php');
}
/*
Remove a topping
*/
function deleteTopping()
{
if (isset($_GET['toppingId']) && (int)$_GET['toppingId'] > 0) {
$toppingId = (int)$_GET['toppingId'];
} else {
header('Location: index.php');
}
$sql = "DELETE FROM restaurant_info
WHERE rest_id = $toppingId";
dbQuery($sql);
header('Location: index.php');
}
?>
To save the file in database, you need to fetch content of file & save that in DB. You should choose datatype as longblob.
This can help you: http://forums.mysql.com/read.php?20,17671,27914
i just fixed it, i had to do some changes to the sql code.
<?php
require_once '../../library/config.php';
require_once '../library/functions.php';
error_reporting(E_ALL);
checkUser();
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'add' :
addTopping();
break;
case 'modify' :
modifyTopping();
break;
case 'delete' :
deleteTopping();
break;
default :
// if action is not defined or unknown
// move to main Topping page
header('Location: index.php');
}
function addTopping()
{
if($_FILES['bgImg']['tmp_name']!='')
{
$srcFile = $_FILES['bgImg']['tmp_name'];
$size = $_FILES['bgImg']['size'];
if($size<5227520) //if file is less than 5MB
{
$ext = substr(strrchr($_FILES['bgImg']['name'], "."), 1);
$ext = strtolower($ext);
if (($ext != "jpg") && ($ext != "jpeg") && ($ext != "png") && ($ext != "gif"))
{
//print error message
print "<script>alert('Unknown File Format Detected')</script>";
print "<script>window.location='index.php'</script>";
exit;
}
else
{
$img_name = md5(rand() * time()) . ".$ext";
$dest = '../../testingImageIntoFolderAndDatabase/upload/';
$name = $_POST['txtName'];
$email = $_POST['txtEmail'];
$phone = $_POST['txtPhone'];
$address = $_POST['txtAddress'];
$cuisine = $_POST['txtCuisine'];
$mini_order = $_POST['txtMini_order'];
$suburbs = $_POST['txtSuburbs'];
$menu = $_POST['txtMenu'];
$reviews = $_POST['txtReviews'];
$logo = $_POST['txtLogo'];
$takeaway_hours = $_POST['txtTakeawayHours'];
$delivery_hours = $_POST['txtDeliveryHours'];
$map = $_POST['txtMap'];
$promotions = $_POST['txtPromotions'];
//copy new image
move_uploaded_file($_FILES['bgImg']['tmp_name'],$dest.$img_name);
dbQuery("insert into restaurant_info set Rest_Logo='$img_name', name='$name', email='$email', phone='$phone', address='$address', cuisine='$cuisine', mini_order='$mini_order', suburbs='$suburbs', menu='$menu', reviews='$reviews', logo='$logo', takeaway_hours='$takeaway_hours', delivery_hours='$delivery_hours', map='$map', promotions='$promotions'");
print "<script>window.location='index.php'</script>";
exit;
}
}
else
{
print "<script>alert('File Size Exceeded!')</script>";
print "<script>window.location='index.php'</script>";
exit;
}
}
}
/*
Modify a Topping
*/
function modifyTopping()
{
$toppingId = (int)$_POST['hidToppingId'];
$name = $_POST['txtName'];
$email = $_POST['txtEmail'];
$phone = $_POST['txtPhone'];
$address = $_POST['txtAddress'];
$cuisine = $_POST['txtCuisine'];
$mini_order = $_POST['txtMini_order'];
$suburbs = $_POST['txtSuburbs'];
$menu = $_POST['txtMenu'];
$reviews = $_POST['txtReviews'];
$logo = $_POST['txtLogo'];
$takeaway_hours = $_POST['txtTakeawayHours'];
$delivery_hours = $_POST['txtDeliveryHours'];
$map = $_POST['txtMap'];
$promotions = $_POST['txtPromotions'];
$sql = "UPDATE restaurant_info
SET name='$name', email='$email', phone='$phone', address='$address', cuisine='$cuisine', mini_order='$mini_order', suburbs='$suburbs', menu='$menu', reviews='$reviews', logo='$logo', takeaway_hours='$takeaway_hours', delivery_hours='$delivery_hours', map='$map', promotions='$promotions'
WHERE rest_id = $toppingId";
dbQuery($sql);
header('Location: index.php');
}
/*
Remove a topping
*/
function deleteTopping()
{
if (isset($_GET['toppingId']) && (int)$_GET['toppingId'] > 0) {
$toppingId = (int)$_GET['toppingId'];
} else {
header('Location: index.php');
}
$sql = "DELETE FROM restaurant_info
WHERE rest_id = $toppingId";
dbQuery($sql);
header('Location: index.php');
}
?>
Related
I have created a test form just to try to Insert image into "student" table of mysql and "images" folder. But image not insert into database and images folder. The code below is just a test, I want to submit but it isntisn't.
**Mysql Database:**
CREATE TABLE STUDENT
(
STD_SL_NO INT(10) NOT NULL AUTO_INCREMENT,
STD_NAME VARCHAR(140) NOT NULL,
STD_FNAME VARCHAR(140) NOT NULL,
STD_MNAME VARCHAR(140) NOT NULL,
STD_BDATE DATE NOT NULL,
STD_GENDER VARCHAR(10) NOT NULL,
STD_RELIGIOUS VARCHAR(20) NOT NULL,
STD_CURR_ADDRESS TEXT NOT NULL,
STD_MOBILE CHAR(12),
STD_ROLL_NO INT(10) NOT NULL,
STD_PHOTO BLOB,
USER_NAME VARCHAR(50),
ENTRY_DATE TIMESTAMP (6),
PRIMARY KEY(STD_SL_NO, STD_ROLL_NO, STD_REG_NO)
)ENGINE=InnoDB;
**Form HTML & PHP:**
<!DOCTYPE html>
<html>
<head>
<title> Student Information Entry Form </title>
</head>
<body>
<form name="form1" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<table>
<tr>
<td><h4> Student Name</h4></td>
<td> <h5> <input type="text" name="t1" size="30"/></h5></td>
</tr>
<tr>
<td><h4> Student's Father Name</h4></td>
<td> <h5> <input type="text" name="t2" size="30"/></h5></td>
</tr>
<tr>
<td><h4> Student's Mother Name</h4></td>
<td> <h5> <input type="text" name="t3" size="30"/></h5></td>
</tr>
<tr>
<td><h4> Student's Birth Date</h4></td>
<td> <h5> <input type="date" name="t4" /></h5></td>
</tr>
<tr>
<td><h4> Student's Gender </h4></td>
<td>
<?php
$con=mysqli_connect("localhost", "root", "ew6wLoLOro", "result");
$sql=mysqli_query($con, "select gender_sl_no, gender_name from gender");
while($row=mysqli_fetch_array($sql))
{
echo '<table>
<input type="radio" name="t5" value='.$row['gender_name'].'
checked="checked"/>
'.$row['gender_name'].'
</table>';
}
?>
</td>
</tr>
<tr>
<td><h4> Please Select Your Religion</h4></td>
<td> <h5>
<div>
<select name="t6">
<option>Selection</option>
<?php
$sql=mysqli_query($con, "select religion_name from religion");
while($row=mysqli_fetch_array($sql))
{
?>
<option> <?php echo $row["religion_name"]; ?></option>
<?php
}
?>
</select> </div> </h5>
</td>
</tr>
<tr>
<td><h4>House No/Village,P.O/<br>Detail address except above </h4></td>
<td> <h5> <input type="text" name="t7" size="40" /></h5></td>
</tr>
<tr>
<td><h4>Entry Student Mobile No.</h4></td>
<td> <h5> <input type="text" name="t15" maxlength="11"
onpaste="return false;" onkeypress="StdMobile(event)">
<script>
function StdMobile(evt)
{
var anwar = String.fromCharCode(evt.which);
if(!(/[0-9]/.test(anwar)))
{
evt.preventDefault();
}
}
</script>
</h5></td>
</tr>
<tr>
<td><h4> Student Roll No. </h4></td>
<td> <h5> <input type="text" name="t23" maxlength="6"
onkeypress="StdRoll(event)" >
<script>
function StdRoll(evt)
{
var elaf=String.fromCharCode(evt.which);
if(!(/[0-9]/.test(elaf)))
{
evt.preventDefault();
}
}
</script>
</h5></td>
</tr>
<tr>
<td><h3> Student Photo</h3></td>
<td> <h5> <input type="file" name="file"/>
</h5></td>
</tr>
<tr>
<td> </td>
<td><input type ="submit" name="submit"/> </td>
</tr>
</table>
</form>
<?php
$con=mysqli_connect("localhost", "root", "ew6wLoLOro", "result");
if(!$con)
{
die('Could not connect:'.mysqli_connect_error());
}
if(isset($_POST['submit']))
{
$t1 = (isset($_POST['t1']) ? $_POST['t1']:null);
$t2 = (isset($_POST['t2']) ? $_POST['t2']:null);
$t3 = (isset($_POST['t3']) ? $_POST['t3']:null);
$t4 = (isset($_POST['t4']) ? $_POST['t4']:null);
$t5 = (isset($_POST['t5']) ? $_POST['t5']:null);
$t6 = (isset($_POST['t6']) ? $_POST['t6']:null);
$t7 = (isset($_POST['t7']) ? $_POST['t7']:null);
$t15 = (isset($_POST['t15']) ? $_POST['t15']:null);
$t23 = (isset($_POST['t23']) ? $_POST['t23']:null);
$file = (isset($_FILES['file']));
$file_name = $file['name'];
$file_type = $file ['type'];
$file_size = $file ['size'];
$file_path = $file ['tmp_name'];
if($file_name!="" && ($file_type="image/jpeg"||$file_type="image/png"||$file_type="image/gif")&& $file_size<=614400)
{
if(move_uploaded_file ($file_path,'images/'.$file_name))
{
$query="insert into student values(default, '$t1', '$t2', '$t3', '$t4', '$t5', '$t6', '$t7', '$t15', '$t23', '$file_name', default, default)";
$result = mysqli_query($con, $query);
if($result==true)
{
echo "File Uploaded";
}
}
}
}
?>
try with this code
Form
<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
PHP Code"
<?php
include 'conf.php';
if ($_FILES["image"]["error"] > 0)
{
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
echo"<font size = '5'><font color=\"#0CF44A\">SAVED<br>";
$file="images/".$_FILES["image"]["name"];
$sql="INSERT INTO eikones (auxon, path) VALUES ('','$file')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<font size = '5'><font color=\"#0CF44A\">SAVED TO DATABASE";
}
mysql_close();
?>
Use this api. need little modify
/function to upload logo image/
public function upload_logo($filename,$temp_name,$filesize,$dir){
global $postClass;
$upload_size = imagesize*1424*1424;
$file_name = $filename;
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $temp_name);
if($mime == 'image/jpeg' || $mime == 'image/png' || $mime == 'image/jpg' || $mime == 'image/JPG' || $mime == 'application/pdf')
{
if($filesize < $upload_size)
{
$temp = $temp_name;
$extention = explode('.',$file_name);
$name = rand(1,100).'_'.time().'.'.$extention[1];
if($mime == 'application/pdf'){
if(move_uploaded_file($temp,"$dir/$name")){
if(strpos($dir, '/') !== false){
$dir1 = explode('/', $dir);
$dir = $dir1[1];
}
else{
$dir =$dir;
}
return $dir.'/'.$name;
}
else{
return 1;
}
}
else{
$image = $postClass->compress($temp, "$dir/$name", 70);
//if(move_uploaded_file($temp,"$dir/$name"))
if($image)
{
if(strpos($dir, '/') !== false){
$dir1 = explode('/', $dir);
$dir = $dir1[1];
}
else{
$dir =$dir;
}
return $dir.'/'.$name;
}else{
return 1;
}
}
}else{
return 2;
}
}else{
return 3;
}
}
customer_register.php
<?php
session_start();
?>
<form action="customer_register.php" method="post" enctype="multipart/form-data">
<?php
if (isset($_POST['c_name']) && isset($_POST['c_email']) && isset($_POST['c_usrname']) && isset($_POST['c_password']) && isset($_POST['c_country']) && isset($_POST['c_city']) && isset($_POST['c_contact']) && isset($_POST['c_address']) && isset($_FILES['c_image']['name'])) {
$c_ip_add = getIp();
$c_name = $_POST['c_name'];
$c_email = $_POST['c_email'];
$c_username = $_POST['c_usrname'];
$c_password = $_POST['c_password'];
$c_country = $_POST['c_country'];
$c_city = $_POST['c_city'];
$c_contact = $_POST['c_contact'];
$c_address = $_POST['c_address'];
$c_image = #$_FILES['c_image']['name'];
$c_tmp_name = #$_FILES['c_image']['tmp_name'];
$location = 'customer/customer_images/';
if (!empty($c_name) && !empty($c_email) && !empty($c_username) && !empty($c_password) && !empty($c_country) && !empty($c_city) && !empty($c_contact) && !empty($c_address) && !empty($c_image)) {
move_uploaded_file($c_tmp_name, $location.$c_image);
$select_user = "SELECT customers_username FROM customers WHERE customers_username = '$c_username'";
$run_select_user = mysqli_query($conn, $select_user);
if (mysqli_num_rows($run_select_user) == NULL) {
$insert_customer = "INSERT INTO customers(customers_ip, customers_name, customers_email, customers_username, customers_pass, customers_country, customers_city, customers_contact, customers_address, customers_image) VALUES ('$c_ip_add', '$c_name', '$c_email', '$c_username', '$c_password', '$c_country', '$c_city', '$c_contact', '$c_address', '$c_image')";
$run_insert_customer = mysqli_query($conn, $insert_customer);
$select_cart = "SELECT * FROM cart WHERE ip_add = '$c_ip_add'";
$run_select_cart = mysqli_query($conn, $select_cart);
$check_cart = mysqli_num_rows($run_select_cart);
if ($check_cart == 0) {
$_SESSION['customer_email'] = $c_email;
$_SESSION['username'] = $c_username;
echo '<script>alert("Account has been successfully created")</script>';
echo '<script>window.open("customer/my_account.php","_self")</script>';
} else {
$_SESSION['customer_email'] = $c_email;
$_SESSION['username'] = $c_username;
echo '<script>alert("Account has been successfully created")</script>';
echo '<script>window.open("checkout.php","_self")</script>';
}
} else {
echo "<div align='center' style='color:white; font-size:20px; padding:20px 0px;'><b>The Username already exists. Please try another username.</b></div>";
}
} else {
echo "<div align='center' style='color:white; font-size:20px; padding:20px 0px;'><b>All Fileds are required</b></div>";
}
}
?>
<table align="center" width="750">
<thead>
<tr align="center">
<th colspan="3"><h1>Create an Account</h1></th>
</tr>
</thead>
<tbody>
<tr>
<td id="label" align="right">Name:</td>
<td><input type="text" name="c_name" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Email:</td>
<td><input type="text" name="c_email" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Username:</td>
<td><input type="text" name="c_usrname" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Password:</td>
<td><input type="password" name="c_password" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Image:</td>
<td><input type="file" name="c_image" required></td>
</tr>
<tr>
<td id="label" align="right">Country:</td>
<td>
<select name="c_country">
<option size="50">Select Country</option>
<?php countries(); ?>
</select>
</td>
</tr>
<tr>
<td id="label" align="right">City:</td>
<td><input type="text" name="c_city" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Contact:</td>
<td><input type="text" name="c_contact" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Address:</td>
<td><input type="text" name="c_address" size="40" required></td>
</tr>
<tr align="center">
<td colspan="3"><input type="submit" name="register" value="Create Account"></td>
</tr>
</tbody>
</table>
</form>
customer_login.php
<?php
session_start();
?>
<form method="post" action="">
<table width="500" align="center" bgcolor="skyblue">
<thead>
<tr align="center">
<th colspan="4"><h2>Login or Register to Buy!</h2></th>
</tr>
</thead>
<tbody>
<tr>
<td align="right"><b>Email:</b></td>
<td><input type="text" name="email" placeholder="Enter Email"></td>
</tr>
<tr>
<td align="right"><b>Password:</b></td>
<td><input type="password" name="pass" placeholder="Enter Password"></td>
</tr>
<tr align="center">
<td colspan="4">Forgot Password?</td>
</tr>
<tr align="center">
<td colspan="3"><input type="submit" name="login" value="Login"></td>
</tr>
</tbody>
</table>
<h2 style="float:right; padding:10px;">New? Register Here</h2>
</form>
<?php
if (isset($_POST['email']) && isset($_POST['pass'])) {
$email = $_POST['email'];
$pass = $_POST['pass'];
if (!empty($email) && !empty($pass)) {
$select_id = "SELECT * FROM customers WHERE customers_email = '$email' AND customers_pass = '$pass'";
$run_select_id = mysqli_query($conn, $select_id);
foreach ($run_select_id as $details) {
$usrname = $details['customers_username'];
$id = $details['customers_id'];
}
$num_run_select = mysqli_num_rows($run_select_id);
if ($num_run_select == NULL) {
echo '<script>alert("Invalid : Email/Password combination")</script>';
exit();
}
$c_ip_add = getIp();
$select_cart = "SELECT * FROM cart WHERE ip_add = '$c_ip_add'";
$run_select_cart = mysqli_query($conn, $select_cart);
$check_cart = mysqli_num_rows($run_select_cart);
if ($num_run_select > 0 AND $check_cart == 0) {
$_SESSION['customer_email'] = $email;
$_SESSION['username'] = $usrname;
$_SESSION['id'] = $id;
echo "<script>alert('You Have Logged In Succesfully')</script>";
echo "<script>window.open('customer/my_account.php','_self')</script>";
exit();
} else {
$_SESSION['customer_email'] = $email;
$_SESSION['username'] = $usrname;
$_SESSION['id'] = $id;
echo "<script>alert('You Have Logged In Succesfully')</script>";
echo "<script>window.open('checkout.php','_self')</script>";
}
} else {
echo 'Please enter valid email ID';
}
}
?>
my_account.php
<?php
session_start();
?>
<ul id="categories">
<?php
$location = 'customer_images/';
$usr_email = $_SESSION['customer_email'];
$user_name = #$_SESSION['username'];
$usr_id = $_SESSION['id'];
$select_image = "SELECT * FROM customers WHERE customers_id = '$usr_id'";
$run_image = mysqli_query($conn,$select_image);
foreach ($run_image as $select_all_data) {
$id = $select_all_data['customers_id'];
$name = $select_all_data['customers_name'];
$username = $select_all_data['customers_username'];
$email = $select_all_data['customers_email'];
$country = $select_all_data['customers_country'];
$city = $select_all_data['customers_city'];
$contact = $select_all_data['customers_contact'];
$address = $select_all_data['customers_address'];
$image = $select_all_data['customers_image'];
echo "<li style=''><img src='$location$image' height='150' width='174' style='text-align:center; border:3px solid black; padding:4px; border-radius: 109px;'></li>";
}
?>
<li>My Orders</li>
<li>Edit Account</li>
<li>Change Password</li>
<li>Delete Account</li>
<li>Logout</li>
</ul>
</div>
<div class="content_area2">
<?php cart(); ?>
<div id="my_account_menu">
<span>
<?php
if (isset($_SESSION['customer_email'])) {
echo "Welcome <i style='color:orange;'>" . $_SESSION['username']. ' </i>';
}
?>
<?php
if (!isset($_SESSION['customer_email'])) {
echo "<a href='../checkout.php' style='color:white;'>Login</a>";
} else {
echo "<a href='../logout.php' style='color:orange;'>Logout</a>";
}
?>
</span>
</div>
<?php getIp(); ?>
<div id="products_box">
<?php
if (!isset($_GET['my_orders']) && !isset($_GET['edit_account']) && !isset($_GET['change_pass']) && !isset($_GET['delete_account'])) {
?>
<div style="text-align:center;">
<table>
<tbody>
<tr>
<td id="label">Name : </td>
<td id="detail"><?php echo #$name; ?></td>
</tr>
<tr>
<td id="label">Username (Display Name) : </td>
<td id="detail"><?php echo #$username; ?></td>
</tr>
<tr>
<td id="label">Email : </td>
<td id="detail"><?php echo #$email; ?></td>
</tr>
<tr>
<td id="label">City : </td>
<td id="detail"><?php echo #$city; ?></td>
</tr>
<tr>
<td id="label">Contact : </td>
<td id="detail"><?php echo #$contact; ?></td>
</tr>
<tr>
<td id="label">Address : </td>
<td id="detail"><?php echo #$address; ?></td>
</tr>
</tbody>
</table>
</div>
<div style="padding:20px;"><b>You can see your orders by clicking this link</b></div>
<?php
}
?>
The problem is when I login it is working fine but when I register the user it gives the error undefined
$usr_id = $_SESSION['id'];
in my_account.php and all the information about the user is not displayed
I HAVE STARTED THE SESSION
I think you forget to call session_start before to do anything, even when there is no existing session.
<?php
session_start()
// your code...
You may want to look how it works with the basic example from the session_start function
As stated within the PHP session_start documentation:
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
So you may want to include this call after PHP opening tag <?php as I wrote above
You have to initiate the session by using session_start() on every page where you want to use the session. And this is missing on my_account.php
Ex:
<?php
session_start();
// your code
nowhere in your customer_register.php file do you actually set $_SESSION['id'].
in addition to this:
there are no form tags around your register form, so its hard to see how any data is getting into the script anyway.
your'e also silencing (#) errors. If this is a learning task, which from your comments I assume it is, thats a very counterproductive thing to do.
As you only set $_SESSION['id'] in the login handing script, its not going to be available across pages unless they go through that form. Its hard to tell from your code what your'e intended user journey is, but as it stands at the moment it looks like your'e expecting them to register, then be able to see the account page as a logged in user.
Just set $_SESSION['id'] in the register script, or dispense with it entirely and use the username (seeing as you validate it as unique anyway).
Also, your'e query in the my_account.php is looking for a column customer_id which (as far as I can see) you dont actually set in the insert statement.
This is the trouble with programming, it only does what you tell it to do.
if(isset($_POST['upload'])){
$name = $_POST['name'];
$album_id = $_POST['album'];
$file = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$random_name = rand();
if(empty($name) or empty($file)) {
echo "Please Fill all the Fields ! <br /><br />";
} else {
move_uploaded_file$file_tmp, 'uploads/'.$random_name.'.jpg');
mysql_query("INSERT INTO photos VALUE('', '$name', '$album_id', '$random_name.jpg')");
echo "Photo Uploaded !! <br /><br />";
}
}
This is how i managed to do it hope this helps
<?
function openDB()
{
global $conn, $username,$host,$password,$db;
$host = "localhost";
$username ="username";
$password= "password";
$db = "databasename";
$conn = mysql_connect($host, $username,$password) or die(mysql_error());
mysql_select_db($db,$conn) or die(mysql_error());
}
function closeDB()
{
global $conn;
mysql_close($conn);
}
?>
<form action="<? echo $_SERVER[PHP_SELF];?>" method="post" enctype="multipart/form-data">
<table>
<tr>
<td align="left"><b>Product Image:</b></td>
<td><input type="file" accept="image/*" name="product_image" size="60">
</td>
</tr>
<tr>
<td align="left"><b>Product File1:</b></td>
<td><input type="file" accept="*/*" name="product_support_file" size="60">
</td>
</tr>
<tr>
<td align="left"><b>Product File2:</b></td>
<td><input type="file" accept="*/*" name="product_support_file2" size="60">
</td>
</tr>
<tr>
<td align="left"><b>Product Price:</b></td>
<td><input type="text" name="product_price" size="60" required></td>
</tr>
<tr>
<td colspan="7" align="right"><input type="submit" name="insert_product" value="Insert Product Now"></td></tr>
</table>
</form>
<?
openDB();
$product_id = $_POST['product_id'];
$product_title = $_POST['product_title'];
$product_cat = $_POST['product_cat'];
$product_type = $_POST['product_type'];
$product_price = $_POST['product_price'];
$product_desc = $_POST['product_desc'];
$product_keywords = $_POST['product_keywords'];
$product_link = $_POST['product_link'];
//getting the image from the feild
$product_image = $_FILES['product_image']['name'];
$product_image_tmp = $_FILES['product_image']['tmp'];
$product_support_file = $_FILES['product_support_file']['name'];
$product_support_file_tmp = $_FILES['product_support_file']['tmp'];
$product_support_file2 = $_FILES['product_support_file2']['name'];
$product_support_file2_tmp = $_FILES['product_support_file2']['tmp'];
if(isset($_POST['insert_product']))
{
//gets the Text Feild Data
$insert_product = "insert into products(product_id,product_cat, product_type, product_title,
product_price, product_desc, product_image, product_support_file, product_support_file2, product_keywords,product_link)
values('','$product_cat','$product_type','$product_title',
'$product_price','$product_desc','$product_image','$product_support_file','$product_support_file2','$product_keywords','$product_link')";
if(mysql_query($insert_product))
{
//echo "
//Please enter the file path you wish to add your image to:
//<br><input type='text' name='' value=''></input>";
$file_directory ="../yourdirectory";
foreach($_FILES as $file_name => $file_array)
{
if(is_uploaded_file($file_array["tmp_name"]))
{
move_uploaded_file($file_array["tmp_name"],"$file_directory/"
.$file_array["name"]) or die ("Could not copy");
}
}
echo"<script language='Javascript'>window.open('ConformationUpload.php');</script>";
}
else{
echo"Product adding has been unsuccessfull<b>",mysql_error(),"</b>";
}
closeDB();
}
?>
i am a beginner and am trying to make a form validation with PHP. i want to check if one of the inputs is empty, the form says that the empty input is required.
I show the php script behind.
<?php
$titleErr = $authorErr = $keywordsErr = $contentErr = "";
$title = $author = $keywords = $content = "";
if (empty($_POST["submit"])) {
if(empty($_POST["title"])){
$titleErr = "title is required";
}
if(empty($_POST["author"])){
$authorErr = "author name is required";
}
if(empty($_POST["keywords"])){
$keywordsErr = "keywords are required";
}
if(empty($_POST["content"])){
$contentErr = "This field is required";
}
}
?>
<form method="post" action="insert_post.php">
<table width="600" align="center" border="10">
<tr>
<td align="center" bgcolor="yellow" colspan="6"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="38">
<span style="color:red;"><?php echo $titleErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author" size="38">
<span style="color:red;"><?php echo $authorErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Keywords:</td>
<td><input type="text" name="keywords" size="38">
<span style="color:red;"><?php echo $keywordsErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post Content</td>
<td><textarea name="content" cols="30" rows="15"></textarea>
<span style="color:red;"><?php echo $contentErr; ?></span>
</td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
include("includes/connect.php");
if(isset($_POST['submit'])){
$title = $_POST['title'];
$date = date('d-m-Y');
$author = $_POST['author'];
$keywords = $_POST['keywords'];
$content = $_POST['content'];
$image = $_FILES['image'] ['name'];
$image_tmp = $_FILES['image'] ['tmp_name'];
move_uploaded_file($image_tmp, "../images/$image");
$query = "INSERT INTO posts (post_title, post_date, post_author, post_keywords, post_image, post_content) VALUES('$title', '$date', '$author', '$keywords', '$image', '$content')";
$result = mysqli_query($conn, $query);
if($query){
echo"<center><h1>Post Published Succesfully!</h1></center>";
}
}
?>
The problem is i want to stop the scrit if the inputs are empty but i can't use functions like: exit() and break;.
and if i submit, the form sends empty values to the database :C.
how can i solve this problem?
We make use of session variables which temporarily stores data locally. To use sessions we must always start sessions by session_start() at the start of every page to be able to access the variables. Now we can store data and pass it to whatever page we want to without having to send it - we just store it and then grab it.
index.php
<?php
session_start();
$titleErr = $authorErr = $keywordsErr = $contentErr = "";
$title = $author = $keywords = $content = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["title"])){
$titleErr = "title is required";
}
if(empty($_POST["author"])){
$authorErr = "author name is required";
}
if(empty($_POST["keywords"])){
$keywordsErr = "keywords are required";
}
if(empty($_POST["content"])){
$contentErr = "This field is required";
}
if(!empty($_POST["title"]) && !empty($_POST["author"]) && !empty($_POST["keywords"]) && !empty($_POST["content"])){
$_SESSION["title"] = $_POST["title"];
$_SESSION["author"] = $_POST["author"];
$_SESSION["keywords"] = $_POST["keywords"];
$_SESSION["content"] = $_POST["content"];
$_SESSION["image"] = $_FILES["image"];
header("location: insert_post.php");
exit();
}
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="600" align="center" border="10">
<tr>
<td align="center" bgcolor="yellow" colspan="6"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="38" value="<?php if(isset($_POST['title'])){ echo $_POST['title']; }; ?>">
<span style="color:red;"><?php echo $titleErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author" size="38" value="<?php if(isset($_POST['author'])){echo $_POST['author']; }; ?>">
<span style="color:red;"><?php echo $authorErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Keywords:</td>
<td><input type="text" name="keywords" size="38" value="<?php if(isset($_POST['keywords'])){echo $_POST['keywords']; }; ?>">
<span style="color:red;"><?php echo $keywordsErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post Content</td>
<td><textarea name="content" cols="30" rows="15" value="<?php if(isset($_POST['content'])){echo $_POST['content']; }; ?>"></textarea>
<span style="color:red;"><?php echo $contentErr; ?></span>
</td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
insert_post.php
<?php
session_start();
include("includes/connect.php");
$title = $_SESSION['title'];
$author = $_SESSION['author'];
$keywords = $_SESSION['keywords'];
$content = $_SESSION['content'];
$date = date('d-m-Y');
$image = $_SESSION['image']['name'];
$image_tmp = $_SESSION['image']['tmp_name'];
move_uploaded_file($image_tmp, "../images/$image");
$query = "INSERT INTO posts (post_title, post_date, post_author, post_keywords, post_image, post_content) VALUES('$title', '$date', '$author', '$keywords', '$image', '$content')";
$result = mysqli_query($conn, $query);
if($query){
echo"<center><h1>Post Published Succesfully!</h1></center>";
}
else{
echo "<center><h1>Error! Post was not published!</h1></center>";
}
echo $title . " " . $author . " " . $keywords . " " . $content;
?>
Btw, you should be using prepared statements for your database inserts to prevent SQL-injections. Read more about it here.
You don't hAve to Break the Script using the Exit Funktion. Just prove if the error variables aren't empty and only in the Case when they aren't empty send a dB-request.
Chenge these lines:
include("includes/connect.php");
if(isset($_POST['submit'])){
to
include("includes/connect.php");
if( isset($_POST['submit']) //Fix here, it will only insert if all error message
&& empty($titleErr) //are empty.
&& empty($authorErr)
&& empty($keywordsErr)
&& empty($contentErr) ){
Edit
And also change this line
if (empty($_POST["submit"])) {
To
if (isset($_POST["submit"])) {
On the init of your script. The empty function will return true if you did not submit the page, that's why you are hving the error messages.
I have problem with my script. It uploads image in my hosting server. There created folders with images are missing from hosting server next day or next week not all images of course - 18-19% of all for 2 weeks. I asked them. They told me- the problem is in my php code. If someone can help I will be happy. May be I add some 0777 in mkdir()???? I don't know. I am thinking at the all time...
<?php
if (isset($_FILES['myfile'])) {
$ip = getRealIpAddr();
$usernameupload = $user_data['username'];
$title = sanitize($_POST['title']);
$description = sanitize($_POST['description']);
if (empty($_POST['folder']) === true) { $folder = sanitize($_POST['folder_option']);} else { $folder = sanitize($_POST['folder']);}
$date = date('M-d-Y');
$code = "";
$errors = array();
$allowed_ext =array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['myfile']['name'];
$file_size = $_FILES['myfile']['size'];
$file_tmp = $_FILES['myfile']['tmp_name'];
$extension=explode('.',$file_name);
$file_ext=strtolower(end($extension));
if (isset($_POST['submitupload'])) {
if ($_FILES['myfile']['name'] == ""){
$errors[] = ' *Upload file';
} else if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = ' *Extension not allowed';
}
}
if ($file_size > 5042880) {
$errors[] = 'File size must be under 5mb';
}
if (strlen($folder) > 50) {
$errors[] = 'Your new folder name must be max 50 characters';
}
if (empty($_POST['title'])) {
$errors[] = 'Please Fill Title';
}
if (strlen($_POST['title']) > 255) {
$errors[] = 'Your title must be max 255 characters';
}
if (empty($errors)) {
require('db.inc.php');
$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$length = 50;
for ($i = 0; $i <= $length; $i++) {
$rand = rand() % strlen($charset);
$tmp = substr($charset, $rand, 1);
$code .= $tmp;
}
$query = mysql_query("SELECT code FROM files WHERE code='$code'");
$numrows = mysql_num_rows($query);
while ($numrows != 0) {
for ($i = 0; $i <= $length; $i++) {
$rand = rand() % strlen($charset);
$tmp = substr($charset, $rand, 1);
$code .= $tmp;
}
$query = mysql_query("SELECT code FROM files WHERE code='$code'");
$numrows = mysql_num_rows($query);
}
mkdir("files/$code");
mkdir("files/thumbs/$code");
if (move_uploaded_file($file_tmp, "files/$code/".$file_name)) {
$file = "";
$query = mysql_query("INSERT INTO files VALUES ('', '$usernameupload', '$ip', '$title', '$code', '$folder', '$description', '$file_name', '$file_ext', '$file_size', '$date')");
$query1 = mysql_query("INSERT INTO votes VALUES ('', '', '', '$code')");
create_thumb('files/'.$code.'/', $file_name, 'files/thumbs/' . $code . '/');
header("Location: userdownload.php?code=$code");
exit();
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td id="editfill">Image:*</td>
<td><input type="file" name="myfile" id="fileup"></td>
<tr>
<td></td>
<td><?php
if (isset($_POST['submitupload'])) {
if ($_FILES['myfile']['name'] == ""){
echo '<div id="errormsg"> *Upload file </div>';
} else if (in_array($file_ext, $allowed_ext) === false) {
echo '<div id="errormsg"> *Allowed extension: .jpg, .jpeg, .png, .gif</div>';
} else if ($file_size > 5042880) {
echo '<div id="errormsg"> *File size must be under 5mb </div>';
}
}
?></td>
</tr>
</tr>
<tr>
<td id="editfill">Title:*</td>
<td><input type="text" name="title" id="title" value="<?php if (isset($_POST['submitupload'])) echo htmlentities($_POST['title']); ?>" maxlength="255"></td>
<tr>
<td></td>
<td><?php
if (isset($_POST['submitupload'])) {
if (empty($_POST['title'])) {
echo '<div id="errormsg"> *Please fill title </div>';
}
if (strlen($_POST['title']) > 255) {
echo '<div id="errormsg"> *Your title must be max 255 characters</div>';
}
}
?></td>
</tr>
</tr>
<tr>
<td id="editfill">Create Album:</td>
<td><input type="text" name="folder" id="title" value="<?php if (isset($_POST['submitupload'])) echo htmlentities($_POST['folder']); ?>" maxlength="50">
</td>
<tr>
<td></td>
<td><?php
if (strlen($folder) > 50) {
echo '<div id="errormsg"> *Your new album name must be max 50 characters</div>';
}
?></td>
</tr>
</tr>
<tr>
<td id="editfill">Your Albums:</td>
<td>
<select name="folder_option" class="select">
<option></option>
<?php
$mysql_folder = mysql_query("SELECT `folder_name` FROM `files` WHERE `username` = '$usernameupload' AND `folder_name` > '' GROUP BY `folder_name` ORDER BY `folder_name` ASC");
while ($query_row = mysql_fetch_array($mysql_folder)) {
$filefolder = $query_row['folder_name'];
echo '<option value="' . $filefolder . '">' . $filefolder . '</option>';
}
?>
</select>
</td>
<tr>
<td></td>
<td></td>
</tr>
</tr>
<tr>
<td id="editfill">Description:</td>
<td><textarea name="description" id="description"><?php if (isset($_POST['submitupload'])) echo htmlentities($_POST['description']); ?></textarea></td>
<tr><td></td>
<td>
</td>
</tr>
</tr>
<tr>
<td></td>
<td><center><br><input type="submit" name="submitupload" id="submitupload" value="Upload"></center></td>
</tr>
</table>
</form>
Try this one to efficiently see if mkdir creation doesnt failed.
else folder and image surely will not be exist even it is added unto your database.
//previous code...
mkdir("files/$code");
mkdir("files/thumbs/$code");
//change to this...
if (!mkdir("files/$code", 0777, true)) {
die('Failed to create folders...');
}
if (!mkdir("files/thumbs/$code", 0777, true)) {
die('Failed to create sub folders...');
}