i am inserting data into mysql using php it's work partialy it's inserting everything but not single quotes(') ex. principle's message. and when i insert it like principle"s message. it's inserting in database but it's only displaying principle in text box after inserting. and my file is save.php is here.
<?php session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['user'])) {
if($_GET['catId'] == '' || $_GET['catId'] == null)
header('location:../user/logout.php');
$inc = -1;
if($_POST['title'] == '' || $_POST['title'] == null) {
$inc++;$_SESSION['error'][$inc] = "TITLE IS REQUIRED";
}
$selectImg=mysql_query("SELECT pri_img FROM aboutus_tbl WHERE id=4");
if ($_GET['catId']==4) {
if($_FILES["file"]["name"]) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 5242880)
&& in_array($extension, $allowedExts))
$imageNewName = md5(date("l, F d, Y h:i" ,time()) . (microtime())) . "." . $extension;
else {
$inc++;$_SESSION['error'][$inc] = "IVALID IMAGE";
}
}
else {
$inc++;$_SESSION['error'][$inc] = "IMAGE IS REQUIRED";
}
}
function inputValues() {
$_SESSION['values']['title'] = $_POST['title'];
$_SESSION['values']['sub_title1'] = $_POST['sub_title1'];
$_SESSION['values']['desc1'] = $_POST['desc1'];
$_SESSION['values']['sub_title2'] = $_POST['sub_title2'];
$_SESSION['values']['desc2'] = $_POST['desc2'];
$_SESSION['values']['sub_title3'] = $_POST['sub_title3'];
$_SESSION['values']['desc3'] = $_POST['desc3'];
header("location:../../views/aboutus_content/list.php?catId=".$_GET['catId']);
}
if($inc > -1)
inputValues();
else {
require_once('../../includes/connect.php');
if($_GET['catId']==4 && isset($_FILES["file"]["name"])) {
$update="UPDATE aboutus_tbl SET title='".$_POST['title']."',sub_title1='".$_POST['sub_title1']."',desc1='".$_POST['desc1']."',sub_title2='".$_POST['sub_title2']."',desc2='".$_POST['desc2']."',sub_title3='".$_POST['sub_title3']."',desc3='".$_POST['desc3']."',pri_img='".$imageNewName."' WHERE id='".$_GET['catId']."'";
}
else{
$update="UPDATE aboutus_tbl SET title='".$_POST['title']."',sub_title1='".$_POST['sub_title1']."',desc1='".$_POST['desc1']."',sub_title2='".$_POST['sub_title2']."',desc2='".$_POST['desc2']."',sub_title3='".$_POST['sub_title3']."',desc3='".$_POST['desc3']."' WHERE id='".$_GET['catId']."'";
}
if(mysql_query($update)) {
if($_GET['catId']==4 && isset($_FILES["file"]["name"])) {
move_uploaded_file($_FILES["file"]["tmp_name"],"../../public/img/principal/".$imageNewName);
unlink("../../public/img/principal/".mysql_result($selectImg, 0, "pri_img"));
}
$_SESSION['message'] = $_POST['title']." SUCESSFULLY UPDATED";
header('location:../../views/aboutus_content/list.php?catId='.$_GET['catId']);
} else {
$_SESSION['error'] = "ERROR : '".mysql_error()."' CODE : ".mysql_errno();
inputValues();
}
}
} else
header('location:../user/logout.php')
?>
and designing file is here list.php
<?php
ob_start();
include '../../includes/header.php';
if(!isset($_GET['catId']) || $_GET['catId']=='')
header('location:../error');
$contactResult = mysql_query("SELECT * FROM aboutus_tbl WHERE id='".$_GET['catId']."'");
if(mysql_num_rows($contactResult) != 1)
header('location:../error');
else {
?>
<div class="mainbar">
<div class="page-head">
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<h2><i class="fa fa-desktop"></i> <?php echo mysql_result($contactResult, 0, "title");?> Content</h2>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="container">
<?php
if(isset($_SESSION['error'])) {
echo"<div class='alert alert-danger'>";
for($i=0;$i<sizeof($_SESSION['error']);$i++)
echo "<p><b>".$_SESSION['error'][$i]."</b></p>";
echo"</div>";
unset($_SESSION['error']);
}
if(isset($_SESSION['message'])) {
echo"<div class='alert alert-success'><p><b>".$_SESSION['message']."</b></p></div>";
unset($_SESSION['message']);
}
?>
<div class="hide alert alert-danger" id="errorContainer"></div>
<div class="row">
<div class="col-lg-12">
<form action="../../controllers/aboutus_content/save.php?catId=<?php echo $_GET['catId'];?>" method="post" class="contactForms" role="form" enctype="multipart/form-data">
<div class="col-lg-6">
<div class="form-group">
<label for="title"><span class="text-danger">* </span>Title</label>
<input name="title" id="title" data-validation-allowing="'" class="form-control" placeholder="Enter Title" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['title']; echo mysql_result($contactResult, 0, "title");?>" />
</div>
<div class="form-group">
<label for="sub_title1"><span class="text-danger">* </span>Sub Title 1</label>
<input name="sub_title1" id="sub_title1" data-validation-allowing="'" class="form-control" placeholder="Enter Sub Title 1" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['sub_title1']; else echo mysql_result($contactResult, 0, "sub_title1");?>" />
</div>
<div class="form-group">
<label for="desc1"><span class="text-danger">* </span>Description 1</label>
<textarea name="desc1" id="desc1" data-validation-allowing="'" class="form-control" placeholder="Enter Description 1"><?php if(isset($_SESSION['values'])) echo $_SESSION['values']['desc1']; else echo mysql_result($contactResult, 0, "desc1");?></textarea>
</div>
<div class="form-group">
<label for="sub_title2"><span class="text-danger">* </span>Sub Title 2</label>
<input name="sub_title2" id="sub_title2" data-validation-allowing="'" class="form-control" placeholder="Enter Sub Title 2" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['sub_title2']; else echo mysql_result($contactResult, 0, "sub_title2");?>" />
</div>
<div class="form-group">
<label for="desc2"><span class="text-danger">* </span>Description 2</label>
<textarea name="desc2" id="desc2" data-validation-allowing="'" class="form-control" placeholder="Enter Description 2"><?php if(isset($_SESSION['values'])) echo $_SESSION['values']['desc2']; else echo mysql_result($contactResult, 0, "desc2");?></textarea>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="sub_title3"><span class="text-danger">* </span>Sub Title 3</label>
<input name="sub_title3" id="sub_title3" data-validation-allowing="'" class="form-control" placeholder="Enter Sub Title 3" value="<?php if(isset($_SESSION['values'])) echo $_SESSION['values']['sub_title3']; else echo mysql_result($contactResult, 0, "sub_title3");?>" />
</div>
<div class="form-group">
<label for="desc3"><span class="text-danger">* </span>Description 3</label>
<textarea name="desc3" id="desc3" data-validation-allowing="'" class="form-control" placeholder="Enter Description 3"><?php if(isset($_SESSION['values'])) echo $_SESSION['values']['desc3']; else echo mysql_result($contactResult, 0, "desc3");?></textarea>
</div>
<div class="form-group">
<label for="pri_img"><span class="text-danger">* </span>Principle Image(Only For Principal's Message)</label>
<input type="file" name="file" id="file" class="form-control">
</div>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-info" value="Save" />
Reset
</div>
</form>
</div>
</div>
</div>
</div>
<?php
}
?>
<script type="text/javascript">
window.onload = function() {
$(document).ready(function() {
$('.aboutus_content').addClass('current');
$('.aboutus_content').addClass('open');
$(".courImgItm<?php echo $_GET['catId']?>").addClass('active');
});
}
</script>
<?php
include '../../includes/footer.php';
if(isset($_SESSION['values']))
unset($_SESSION['values']);
ob_flush();
?>
please help me.
Run your string through this first:
mysql_real_escape_string($string);
It'll fix it for ya
try using this way
in your sql query---
$m1=$_REQUEST['message'];
$msg='".str_replace("\"",""",str_replace("'","''",$m1))."';
hope this will help
Related
I am working on a basic e-commerce website using PHP/MYSQL. I just need to know how I can upload multiple images for a product and then display them on the product details page in this format Example of what I'm trying to implement
I've been trying to figure out how I can display these images (multiple images for 1 product). I really don't understand how it should work! so any advice on simple terms would be appreciated.
Currently, I can only upload 1 image per product.
Here is what I have so far (1 Image per product),
For the Product Class Page
<?php
class Product{
private $db;
private $fm;
public function __construct(){
$this->db = new Database();
$this->fm = new Format();
}
public function productInsert($data, $file){
$productName = mysqli_real_escape_string($this->db->link, $data['productName']);
$catId = mysqli_real_escape_string($this->db->link, $data['catId']);
$body = mysqli_real_escape_string($this->db->link, $data['body']);
$price = mysqli_real_escape_string($this->db->link, $data['price']);
$type = mysqli_real_escape_string($this->db->link, $data['type']);
$town = mysqli_real_escape_string($this->db->link, $data['town']);
$quantity = mysqli_real_escape_string($this->db->link, $data['quantity']);
$email = mysqli_real_escape_string($this->db->link, $data['email']);
$phone = mysqli_real_escape_string($this->db->link, $data['phone']);
$contactName = mysqli_real_escape_string($this->db->link, $data['contactName']);
$permited = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $file['image']['name'];
$file_size = $file['image']['size'];
$file_temp = $file['image']['tmp_name'];
$div = explode('.', $file_name);
$file_ext = strtolower(end($div));
$unique_image = substr(md5(time()), 0, 10).'.'.$file_ext;
$uploaded_image = "../uploads/".$unique_image;
if($productName == "" || $catId == "" || $price == "" || $file_name == "" || $town == "" || $quantity == "" || $email == "" || $phone == "" || $contactName == ""){
$msg = "<span class='error'>Fields must not be empty!</span>";
return $msg;
} elseif ($file_size >1048567) {
echo "<span class='error'>Image Size should be less then 1MB!
</span>";
} elseif (in_array($file_ext, $permited) === false) {
echo "<span class='error'>You can upload only:-".implode(', ', $permited)."</span>";
} else{
move_uploaded_file($file_temp, $uploaded_image);
$query = "INSERT INTO products(productName, catId, body, price, image, type, town, quantity, email, phone, contactName) VALUES('$productName','$catId','$body','$price','$uploaded_image', '$type','$town','$quantity','$email','$phone','$contactName')";
$inserted_row = $this->db->insert($query);
if($inserted_row){
$msg = "<span class='success'> Your Offer is Added Successfully. </span>";
return $msg;
} else{
$msg = "<span class='error'> Sorry! Your offer is not added! Try again later. </span>";
return $msg;
}
}
}
For the Add Product Page
<?php
$product = new Product();
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])){
$insertProduct = $product->productInsert($_POST, $_FILES);
}
?>
<form action="" method="post" enctype='multipart/form-data'>
<!-- Add Product start -->
<div class="location">
<!-- Product select start -->
<div class="styled-select-car">
<select name="catId" id="my_selection" style ="font-size:18px;">
<option value="">Select the Offer Category* (Required)</option>
<?php
$cat = new Category();
$getCat = $cat->getAllCat();
if($getCat){
while($result = $getCat->fetch_assoc()){
?>
<option value="<?php echo $result['catId'];?>"><?php echo $result['catName'];?></option>
<?php } } ?>
<br>
</select>
</div>
<!-- Product select end -->
<div class="input-group pick-up">
<span class="input-group-addon"><span class="glyphicon glyphicon-map-marker"></span> Offer*</span>
<input type="text" name="productName" id="pick-up-location" class="form-control " placeholder="Enter Your Product or Service Title (Required)">
</div>
<br>
<div class="input-group pick-up">
<span class="input-group-addon"><span class="glyphicon glyphicon-map-marker"></span> Price* </span>
<input type="text" name="price" id="pick-up-location" class="form-control " placeholder="Enter Your Product or Service Price (Required)">
</div>
<br>
<div class="input-group pick-up">
<span class="input-group-addon"><span class="glyphicon glyphicon-map-marker"></span> Location* </span>
<input type="text" name="town" id="pick-up-location" class="form-control " <?php if(Session::get("customerTown")) {?>value="<?php echo Session::get("customerTown");?>" <?php } else { ?> placeholder="Enter Your Location Description (Required)" <?php } ?>>
</div>
<br>
<div class="input-group pick-up">
<span class="input-group-addon"><span class="glyphicon glyphicon-map-marker"></span> Quantity* </span>
<input type="text" name="quantity" id="pick-up-location" class="form-control " placeholder="Enter Your Product's or Service Quantity* (Required)">
</div>
<br>
<div class="input-group pick-up">
<span class="input-group-addon"><span class="glyphicon glyphicon-map-marker"></span> Email*</span>
<input type="text" name="email" id="pick-up-location" class="form-control " <?php if(Session::get("customerEmail")) {?>value="<?php echo Session::get("customerEmail");?>" <?php } else { ?> placeholder="Enter Your Email Address (Required)" <?php } ?>>
</div>
<br>
<div class="input-group pick-up">
<span class="input-group-addon"><span class="glyphicon glyphicon-map-marker"></span> Phone Number* </span>
<input type="text" name="phone" id="pick-up-location" class="form-control " <?php if(Session::get("customerPhone")) {?>value="<?php echo Session::get("customerPhone");?>" <?php } else { ?> placeholder="Enter Your Phone Number (Required)" <?php } ?>>
</div>
<br>
<div class="input-group pick-up">
<span class="input-group-addon"><span class="glyphicon glyphicon-map-marker"></span> Contact Name* </span>
<input type="text" name="contactName" id="pick-up-location" class="form-control " <?php if(Session::get("customerName")) {?>value="<?php echo Session::get("customerName");?>" <?php } else { ?> placeholder="Enter Your Contact Name (Required)" <?php } ?> >
</div>
<br>
<div class="input-group pick-up">
<span class="input-group-addon"><span class="glyphicon glyphicon-map-marker"></span> Product Image* </span>
<input type="file" name="image" class="form-control" placeholder="">
</div>
<br>
<p><b>Give a detailed description of your product or service(Required):</b></p>
<textarea name="body" ></textarea>
</div>
<input style ="font-size:18px;" type="submit" class="submit" name="submit" value="Add Offer" >
</form>
For the Product Details Page
<?php
if(!isset($_GET['productid']) || $_GET['productid'] == NULL){
echo "<script>window.location = '404.php'; </script>";
} else {
$id = preg_replace('/[^-a-zA-Z0-9_]/', '', $_GET['productid']);
}
?>
<div class="main">
<div class="content">
<div class="section group">
<div class="cont-desc span_1_of_2">
<?php
$getProduct = $product->getSingleProduct($id);
if($getProduct){
while($result = $getProduct->fetch_assoc()){
?>
<div class="grid images_3_of_2">
<img src="<?php echo $result['image']; ?>" alt="" />
</div>
<div class="desc span_3_of_2">
<div class="product-information"><!--/product-information-->
<h2><?php echo $result['productName']; ?></h2>
<p>Contact Name: <?php if($result['contactName'] == NULL){ ?>
Guest
<?php } else { echo $result['contactName'];}
?> </p>
<img src="images/rating.png" alt="" /></br>
<span>
<span>FCFA <?php echo number_format($result['price']); ?></span>
<label>Quantity:</label>
<input type="text" value="<?php echo $result['quantity']; ?>" />
</span>
<p><b>Availability:</b> In Stock</p>
<p><b>Category:</b> <?php echo $result['catName']; ?></p>
<p><b>Town:</b> <?php echo $result['town']; ?></p>
<?php
$contact = $result['phone'];
$contact = substr_replace($contact,"*******",2,6);
?>
<p><b>Telephone:</b> <?php echo $contact; ?></p>
<p><b>Email:</b> <?php echo mask_email($result['email']); ?></p>
<img src="images/share.png" class="share img-responsive" alt="" />
<div class="add-cart">
<form action="" method="post">
<input type="submit" class="buysubmit" name="submit" value="View Contact Details"/>
</form>
</div>
<span style="color: red; font-size: 18px;">
<?php
if(isset($addCart)){
echo $addCart;
}
?>
</span>
</div><!--/product-information-->
</div>
<div class="product-desc">
<h2>Offer Details</h2>
<pre> <?php echo $result['body']; ?> </pre>
</div>
<?php } } ?>
Can anyone help me on how I can modify this code to be able to upload multiple images per product and to be able to retrieve these image on the product details page?
To upload multiple images you can use
<input type="file" name="image[]" multiple>
and to retrieve images just loop through with the mysql_fetch_array() method
$sql="SELECT *
FROM tbl_image
WHERE productId= 1 ";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query))
{
$image=$row ['photo'];
echo '<img src="path/'.$image.'" width="360" height="150">';
}
PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
header('location: no_acces.php');
exit();
} else {
$id_user = $_SESSION['userid'];
$q_user = mysqli_query($conn, "SELECT * FROM users WHERE id = $id_user");
if (mysqli_num_rows($q_user) === 1) {
$r_user = mysqli_fetch_assoc($q_user);
} else {
unset($_SESSION['login']);
unset($_SESSION['userid']);
header('location: no_acces.php');
exit();
}
}
$error = "";
$userQuery = mysqli_query($conn, "SELECT username FROM users");
$user = mysqli_fetch_assoc($userQuery);
$id = $_GET['id'];
if (isset($_POST['edit_contact'])) {
$roepnaam = $_POST['roepnaam'];
$naam = $_POST['naam'];
$land = $_POST['land'];
$bedrijf = $_POST['bedrijf'];
$adres1 = $_POST['adres1'];
$adres2 = $_POST['adres2'];
$stad = $_POST['stad'];
$postcode = $_POST['postcode'];
$provincie = $_POST['provincie'];
$telefoon = $_POST['telefoon'];
$email = $_POST['email'];
$captcha= $_POST['g-recaptcha-response'];
if(!$captcha){
$error = "Er is een fout opgetreden";
}
if ($error == "") {
$insertUser = ("UPDATE address SET
roepnaam = '$roepnaam', naam = '$naam', bedrijf = '$bedrijf', telefoon = '$telefoon', email = '$email', adres1 = '$adres1', adres2 = '$adres2', stad = '$stad', postcode = '$postcode', provincie = '$provincie', land = '$land' WHERE id = $id");
if (mysqli_query($conn, $insertUser)) {
$_SESSION['edit_contact'] = true;
header('location: address_book.php');
} else {
$error = "Er is een fout opgetreden";
}
}
}
?>
HTML Code
<!DOCTYPE html>
<html lang="en">
<body>
<form action="" method="post">
<?php if ($error !== "") { ?>
<div class="row">
<div class="col-md-12 error">
<?php echo $error; ?>
</div>
</div>
<?php } ?>
<label for="firstName" class="control-label">Naam:</label>
<div class="row ">
<div class="col-md-6">
<input type="text" class="form-control" id="firstName" placeholder="Roepnaam" name="roepnaam" value="<?php if (isset($_POST['roepnaam'])) { echo $_POST['roepnaam']; } ?>" required/>
</div>
<div class="col-md-6">
<input type="text" class="form-control" id="lastName" placeholder="Naam" name="naam" value="<?php if (isset($_POST['naam'])) { echo $_POST['naam']; } ?>" required/>
</div>
</div>
<label for="username" class="control-label">Bedrijf:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="username" placeholder="Bedrijf" name="bedrijf" value="<?php if (isset($_POST['bedrijf'])) { echo $_POST['bedrijf']; } ?>" required/>
</div>
</div>
<label for="password" class="control-label">Telefoonnummer:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Telefoonnummer" name="telefoon" value="<?php if (isset($_POST['telefoon'])) { echo $_POST['telefoon']; } ?>" required/>
</div>
</div>
<label for="email" class="control-label">Email:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="email" placeholder="E-mailadres" name="email" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } ?>" required/>
</div>
</div>
<label for="adres1" class="control-label">Adres:</label>
<div class="row">
<div class="col-md-12">
<input type="text" class="form-control" id="adres1" placeholder="Adres 1" name="adres1" value="<?php if (isset($_POST['adres1'])) { echo $_POST['adres1']; } ?>" required/>
</div>
</div>
<div class="row padding-top-10">
<div class="col-md-12">
<input type="text" class="form-control" id="adres2" placeholder="Adres 2" name="adres2" value="<?php if (isset($_POST['adres2'])) { echo $_POST['adres2']; } ?>"/>
</div>
</div>
<div class="row">
<div class="col-md-3">
<label for="postcode" class="control-label">Postcode:</label>
</div>
<div class="col-md-5">
<label for="city" class="control-label">Stad:</label>
</div>
<div class="col-md-4">
<label for="regio" class="control-label">Regio:</label>
</div>
</div>
<div class="row ">
<div class="col-md-3">
<input type="text" class="form-control" id="postcode" placeholder="Postcode" name="postcode" value="<?php if (isset($_POST['postcode'])) { echo $_POST['postcode']; } ?>" required/>
</div>
<div class="col-md-5">
<input type="text" class="form-control" id="city" placeholder="Stad" name="stad" value="<?php if (isset($_POST['stad'])) { echo $_POST['stad']; } ?>" required/>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="regio" placeholder="Provincie" name="provincie" value="<?php if (isset($_POST['provincie'])) { echo $_POST['provincie']; } ?>" required/>
</div>
</div>
<label for="land" class="control-label">Land:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Land" name="land" value="<?php if (isset($_POST['land'])) { echo $_POST['land']; } ?>" required/>
</div>
</div>
<div class="row">
<div class="col-md-8 padding-top-10 ">
<div class="g-recaptcha " data-sitekey="6LcCsBoTAAAAAK72uzyJSrgWwD8xuF6jFIfgFaHX"></div>
</div>
</div>
<div class="row">
<div class="col-md-2 padding-top-10">
<input type="submit" name="edit_contact" class="btn btn-succes" value="Wijzigen">
</div>
<div class="col-md-2 padding-top-10">
<input type="text" name="delete_contact" action="delete_contact.php" class="btn btn-succes" value="Contact verwijderen">
</div>
</div>
</form>
</body>
</html>
PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true || !isset($_SESSION['userid']) || $_SESSION['userid'] == "") {
header('location: login.php');
exit();
} else {
session_regenerate_id();
}
$id = $_GET['id'];
$query = "DELETE FROM address WHERE id= $id";
mysqli_query ($query);
if (mysql_affected_rows() == 1) {
header('location: addressbook.php');
} else {
echo "Verwijderen mislukt";
}
?>
I'm trying to make a delete button for my contacts within the addressbook. but everytime I click "Contact verwijderen" the webpage resets it self and the contact won't be deleted. Could anyone help me to fix this?
You input is a text input and you don't have a form asociated with it,create one and change the type of submit to submit
<form action="delete_contact.php" method="post">
//other inputs
<input type="submit" name="delete_contact" class="btn btn-succes" value="Contact verwijderen">
</form>
You are mixing MySQL and MySQLi functions:
mysqli_query ($query);
if (mysql_affected_rows() == 1)
You cannot mix MySQL with MySQLi, your code should be:
mysqli_query ($query);
if (mysqli_affected_rows($conn) == 1)
Add a normal link to delete the contact, you don't need a form.
<a href="delete_contact.php?id=<?php echo $id ?>">
Contact verwijderen
</a>
The following code for create edit form to update records. If I give all field it update correctly if I didn't change image it does not update the record. I want to update record without change image and also I want to update records by only changing the image.
<section id="main-content">
<section class="wrapper">
<h3><i class="fa fa-angle-right"></i> About Components</h3>
<!-- BASIC FORM ELELEMNTS -->
<div class="row mt">
<div class="col-lg-12">
<div class="form-panel">
<h3><i class="fa fa-angle-right"></i> Team Update</h3>
<form class="form-horizontal style-form" enctype="multipart/form-data" method="post">
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<textarea type="text" name="Title" class="form-control" required><?php echo $img['a_title']; ?></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea type="text" name="Description" class="form-control" required><?php echo $img['a_description']; ?></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Picture</label>
<div class="col-sm-10">
<div class="clear" id="im">
<?php echo "<img src='/myproject/cp/image/".$img['a_image']."'height='50' width='50' >"; ?>
<button type="button" id="remove" >remove</button>
</div>
<div id="browse" style="display:none;">
<input type="file" name="imageupload" value="imageupload" />
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label"></label>
<div class="col-sm-10">
<input class="btn btn-theme" id="focusedInput" type="submit" name="submit" value="Submit" />
</div>
</div>
<a class="btn btn-primary" href="about.php">
<span>List view</span>
</a>
</form>
</div>
</div><!-- col-lg-12-->
</div><!-- /row --><?php
if(isset($_POST['submit']))
{
$var=$_GET['a_id'];
$file=$_SERVER['DOCUMENT_ROOT'].'myproject/cp/image/'.$img['a_image'];
unlink($file);
$var1=$_POST['Title'];
$var2=$_POST['Description'];
$image=$_FILES['imageupload']['name'];
$root=$_SERVER['DOCUMENT_ROOT'].'/myproject/cp/image/';
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$expo=explode(".", $_FILES["imageupload"]["name"]);
$upload_exts = end($expo);
if ((($_FILES["imageupload"]["type"] == "image/gif")|| ($_FILES["imageupload"]["type"] == "image/jpeg")|| ($_FILES["imageupload"]["type"] == "image/png")|| ($_FILES["imageupload"]["type"] == "image/jpg"))&& ($_FILES["imageupload"]["size"] < 2000000)&& in_array($upload_exts,$file_exts))
{
if ($_FILES["imageupload"]["error"] > 0)
{
echo "Return Code: " . $_FILES["imageupload"]["error"] . "<br>";
}
else
{
$image= rand(0,9999).'.'.$upload_exts;
move_uploaded_file($_FILES["imageupload"]["tmp_name"],$root.$image);
$sql=mysql_query("UPDATE about SET a_title='".$var1."',a_description='".$var2."',a_image='".$image."' WHERE a_id='".$var."'") or die(mysql_error());
echo "<meta http-equiv=refresh content=\"0; URL=about.php\">";
}
}
}
?>
As you said in comment , when you save the edits all other details get saved but your image get's removed even if you haven't changed it , clearly it's your php code , even before checking that if you are submiting an image or not you already doing an unlink on it , you have to use the edit below :
<?php
if(isset($_POST['submit']))
{
$var=$_GET['a_id'];
$file_del =$_SERVER['DOCUMENT_ROOT'].'myproject/cp/image/'.$img['a_image'];
$var1=$_POST['Title'];
$var2=$_POST['Description'];
$image=$_FILES['imageupload']['name'];
$root=$_SERVER['DOCUMENT_ROOT'].'/myproject/cp/image/';
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$expo=explode(".", $_FILES["imageupload"]["name"]);
$upload_exts = end($expo);
if ((($_FILES["imageupload"]["type"] == "image/gif")|| ($_FILES["imageupload"]["type"] == "image/jpeg")|| ($_FILES["imageupload"]["type"] == "image/png")|| ($_FILES["imageupload"]["type"] == "image/jpg"))&& ($_FILES["imageupload"]["size"] < 2000000)&& in_array($upload_exts,$file_exts))
{
if ($_FILES["imageupload"]["error"] > 0)
{
echo "Return Code: " . $_FILES["imageupload"]["error"] . "<br>";
}
else
{
unlink($file_del);
$image= rand(0,9999).'.'.$upload_exts;
move_uploaded_file($_FILES["imageupload"]["tmp_name"],$root.$image);
$sql=mysql_query("UPDATE about SET a_title='".$var1."',a_description='".$var2."',a_image='".$image."' WHERE a_id='".$var."'") or die(mysql_error());
echo "<meta http-equiv=refresh content=\"0; URL=about.php\">";
}
}
}
I would like to ask your help. I wrote a code which checks if all the fields are filled in and if the file is not larger than 1 MB. If everything is correct the file successfuly uploads to MySQL database. But if the file size is larger than 1 MB the code stops working. The error doesnt show up and all the fields become empty. Here`s the code (some of it is in Lithuanian, sorry):
<?php
error_reporting(E_ERROR);
session_start();
if (isset($_SESSION['login'])){
include 'config.php';
$username = $_SESSION['login'];
$result = mysqli_query($db,"SELECT * FROM users WHERE username='$username'");
$rws = mysqli_fetch_array($result);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$autorius = mysqli_real_escape_string($db,$_POST['autorius']);$pavadinimas = mysqli_real_escape_string($db,$_POST['pavadinimas']);$puslapiai = mysqli_real_escape_string($db,$_POST['puslapiai']);$tema = mysqli_real_escape_string($db,$_POST['tema']);$pmintis = mysqli_real_escape_string($db,$_POST['pmintis']);$pveikejai = mysqli_real_escape_string($db,$_POST['pveikejai']);$aveikejai = mysqli_real_escape_string($db,$_POST['aveikejai']);$epizodas = mysqli_real_escape_string($db,$_POST['epizodas']);$nuomone = mysqli_real_escape_string($db,$_POST['nuomone']);$apie = mysqli_real_escape_string($db,$_POST['apie']);$foto = mysqli_real_escape_string($db,$_POST['foto']);$user_id = $rws['id'];
if (!empty($autorius) && !empty($pavadinimas) && !empty($puslapiai) && !empty($tema) && !empty($pmintis) && !empty($pveikejai) && !empty($aveikejai) && !empty($epizodas) && !empty($nuomone) && !empty($apie) && isset($foto) && $_FILES['foto']['size'] > 0 && $_FILES['foto']['size'] < 1000001) {
$fileName = $_FILES['foto']['name'];$tmpName = $_FILES['foto']['tmp_name'];$fileSize = $_FILES['foto']['size'];$fileType = $_FILES['foto']['type'];
$fp = fopen($tmpName, 'r');
$foto = fread($fp, filesize($tmpName));
$foto = addslashes($foto);
fclose($fp);
$query = "INSERT INTO books (id_user, autorius, pavadinimas, puslapiai, tema, pmintis, pveikejai, aveikejai, epizodas, nuomone, apie, foto, name, type, size) ".
"VALUES ('$user_id', '$autorius', '$pavadinimas', '$puslapiai', '$tema', '$pmintis', '$pveikejai', '$aveikejai', '$epizodas', '$nuomone', '$apie', '$foto', '$fileName', '$fileType', '$fileSize')";
$result = mysqli_query($db,$query);
$success = "Knygos aprašymas įkeltas";
echo $_FILES['foto']['size'];
}
else if (empty($autorius) || empty($pavadinimas) || empty($puslapiai) || empty($tema) || empty($pmintis) || empty($pveikejai) || empty($aveikejai) || empty($epizodas) || empty($nuomone) || empty($apie)) {
$error = "Užpildykite visus laukelius!";
}
else if (empty($foto)){
$error = "Pasirinkite viršelio nuotrauką!";
}
else if ($_FILES['foto']['size'] > 1000001){
$error = "Viršelio nuotraukos dydid neturi viršyti 1 MB!";
}
}
?>
<?php include 'bin/includes/header.html'; ?>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Įkelti knygos aprašymą
<small>Ikelkite savo knygos aprašymą</small>
</h1>
<ol class="breadcrumb">
<li>Pagrindinis
</li>
<li class="active">Įkelti knygos aprašymą</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-8">
<form name="upload" id="upload" method="post" enctype="multipart/form-data">
<div class="control-group form-group">
<?php
if(isset($success)) {
echo '<label style="color: #44FF00;">';
echo $success;
echo '</label>';
}
else {
echo '<label style="color: #FF3700;">';
echo $error;
echo '</label>';
} ?>
<div class="controls">
<input type="text" class="form-control" name="autorius" maxlength="60" placeholder="Autorius" value="<?php if(!empty($_POST['autorius'])) echo $_POST['autorius'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="pavadinimas" maxlength="255" placeholder="Pavadinimas" value="<?php if(!empty($_POST['pavadinimas'])) echo $_POST['pavadinimas'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="puslapiai" placeholder="Puslapių skaičius" value="<?php if(!empty($_POST['puslapiai'])) echo $_POST['puslapiai'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="pveikejai" maxlength="999" placeholder="Pagrindiniai veikėjai" value="<?php if(!empty($_POST['pveikejai'])) echo $_POST['pveikejai'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="aveikejai" maxlength="999" placeholder="Antraeiliai veikėjai" value="<?php if(!empty($_POST['aveikejai'])) echo $_POST['aveikejai'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Tema" rows="2" class="form-control" name="tema" maxlength="999" style="resize:none"><?php if(!empty($_POST['tema'])) echo $_POST['tema'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Pagrindinė mintis" rows="2" class="form-control" name="pmintis" maxlength="999" style="resize:none"><?php if(!empty($_POST['pmintis'])) echo $_POST['pmintis'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Siužetas" rows="5" class="form-control" name="apie" maxlength="2999" style="resize:none"><?php if(!empty($_POST['apie'])) echo $_POST['apie'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Įsimintiniausias epizodas" rows="3" class="form-control" name="epizodas" maxlength="2999" style="resize:none"><?php if(!empty($_POST['epizodas'])) echo $_POST['epizodas'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Nuomonė apie knygą" rows="3" class="form-control" name="nuomone" maxlength="999" style="resize:none"><?php if(!empty($_POST['nuomone'])) echo $_POST['nuomone'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<label>Įkelti viršelį (max 1MB)</label>
<input name="foto" type="file" id="foto">
<p class="help-block"></p>
</div>
<button type="submit" class="btn btn-primary">Įkelti</button>
</div>
</form>
</div>
</div>
<?php include 'bin/includes/footer.html'; ?>
<?php } else {
header("location: index.php");
}
Thanks for your help!
You should use this to get the file size:
$size = filesize($_FILES['foto']['tmp_name']);
This returns the filesize in byte. One MB are 1048576 bytes. You should check for the function not returning false.
In general: You should use exceptions for this purpose, it is much simplier to check for a condition and then check again. If you just want to use if-else-statements, you should rearrange it (check for errors first and then upload the thing in the else-case).
Why are you not saving the files in filesystem? This is a lot easier...
I have problem with the Uploading in my Project
This is my Code Of 'User' class
<?php
class User{
public function uploadAvatar() {
$alowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["avatar"]["name"]);
$extention = end($temp);
if(($_FILES["avatar"]["type"] == "image/gif")
|| ($_FILES["avatar"]["type"] == "image/jpeg")
|| ($_FILES["avatar"]["type"] == "image/jpg")
|| ($_FILES["avatar"]["type"] == "image/pjpeg")
|| ($_FILES["avatar"]["type"] == "image/x-png")
|| ($_FILES["avatar"]["type"] == "image/png")
&& ($_FILES["avatar"]["size"] > 50000)
&& in_array($extention, $alowedExts)) {
if($_FILES["avatar"]["error"] > 0) {
redirect('register.php', $_FILES['avatar']['error'],'error');
} else {
if (file_exists("/images/avatars/" . $_FILES["avatar"]["name"])) {
redirect('register.php', 'File Already Exists', 'error');
} else{
move_uploaded_file($_FILES["avatar"]["tmp_name"],
"images/avatars/" . $_FILES["avatar"]["name"]);
return true;
}
}
} else {
redirect('register.php','invalid file type','error');
}
}
}?>
and here is my Register
<?php
//create User Object
$user = new User;
if(isset($_POST['register'])){
//create Data Array
$data = Array();
$data['name'] = $_POST['name'];
$data['email'] = $_POST['email'];
$data['username'] = $_POST['username'];
$data['password'] = md5($_POST['password']);
$data['password2'] = md5($_POST['password2']);
$data['about'] = $_POST['about'];
$data['last_activity'] = date("Y-m-d h:i:s");
if($user->uploadAvatar){
$data['avatar'] = $_FILES['avatar']['name'];
} else {
$data['avatar'] = 'noimage.png';
}
} ?>
This is my Form:
<form role="form" enctype="multipart/form-data" method="post" action="register.php">
<div class="form-group">
<label>Name*</label>
<input type="text" class="form-control" name="name" placeholder="Enter Name"/>
</div>
<div class="form-group">
<label>Email Address*</label>
<input type="email" class="form-control" name="email" placeholder="Enter Your Email Address"/>
</div>
<div class="form-group">
<label>Choose UserName*</label>
<input type="text" class="form-control" name="username" placeholder="Create Username"/>
</div>
<div class="form-group">
<label>Password*</label>
<input type="password" class="form-control" name="password" placeholder="Enter A Password"/>
</div>
<div class="form-group">
<label>Confirm Password*</label>
<input type="password" class="form-control" name="password2" placeholder="Enter Password Again"/>
</div>
<div class="form-group">
<label>Upload Avatar</label>
<input type="file" name="avatar" />
<p class="help-block"></p>
</div>
<div class="form-group">
<label>About Me</label>
<textarea id="about" rows="6" cols="80" class="form-control" name="about" placeholder="Tell Us About Yourself (Optional)"></textarea>
</div>
<input name="register" type="submit" class="btn btn-default" value="Register" />
</form>
But now when I run the registration it hass Error
Notice: Undefined property: User::$uploadAvatar in C:\xampp\htdocs\talkingspace\register.php on line 22
any help for this Error?
You try to access uploadAvatar as if it was a property but it's a method.
So you need to change this line:
if($user->uploadAvatar){
to this:
if($user->uploadAvatar()){