I am trying to have an Edit page that fetch the data selected by user and display them in a form. I manage to display the data from database and allow user to edit the data in the form. But my UPDATE query won't work in php. I tried echo the query and run it manual in xampp, it turns out to be ok and it was able to update manual in xampp but not in php. Can anyone help me with the codes? many thanks
this is my php coding
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_POST['btn-update']))
{
$ProdCode = mysql_real_escape_string($_POST['productCode']);
$ProdType = mysql_real_escape_string($_POST['productType']);
$ProdDes = mysql_real_escape_string($_POST['product_description']);
$ProdCol = mysql_real_escape_string($_POST['productColour']);
$ProdPrice = floatval($_POST['productPrice']);
$XSsize = mysql_real_escape_string($_POST['XSquantity']);
$Ssize = mysql_real_escape_string($_POST['Squantity']);
$Msize = mysql_real_escape_string($_POST['Mquantity']);
$Lsize = mysql_real_escape_string($_POST['Lquantity']);
$XLsize = mysql_real_escape_string($_POST['XLquantity']);
$XXLsize = mysql_real_escape_string($_POST['XXLquantity']);
if(isset($_FILES['productImg'])){
$file_name = $_FILES['productImg']['name'];
$file_size = $_FILES['productImg']['size'];
$file_tmp = $_FILES['productImg']['tmp_name'];
$file_type = $_FILES['productImg']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['productImg']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors="Please choose JPEG/PNG file.";
$errorTrigger =true;
}
if($file_size > 2097152) {
$errors='File size must be excately 2 MB';
$errorTrigger =true;
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
} }
$query = "UPDATE product SET product_code='$ProdCode', product_type='$ProdType' ,description='$ProdDes' ,colour='$ProdCol',price= '$ProdPrice',size_xs='$XSsize',size_s='$Ssize',size_m='$Msize',size_l='$Lsize',size_xl='$XLsize',size_xxl='$XXLsize' WHERE product_code='%". $ProdCode ."%'";
echo $query;
if(mysql_query($query))
{
echo "<script>
alert('Product Updated');
</script>";
}
else
{
echo mysql_error();
?>
<script>alert('Error while updating');</script>
<?php
}
}
?>
Related
I want a logged in user to add a profile picture. No errors are shown, the picture is just not added to the folder where it should be.
I know I have to use prepared statements, I will. I just want to sort this problem out first.
When the user has not changed the profile pic, the default picture displays perfectly. The file profile pic just wont upload to the folder.
This is the page where you change the picture.
<?php
session_start();
include_once 'dbh.php';
<html>
<body>
<?php
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if ($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".jpg'>";
}
else {
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$row['username']."</p>";
echo "</div>";
}
}
}
else {
echo "There are no users!";
}
if (isset($_SESSION['id'])) {
echo "You are logged in!";
echo '<form action="includes/upload.inc.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" name="submit">UPLOAD FILE</button>
</form>';
}
else {
echo "You are not logged in!";
}
?>
This is the php page for the upload
<?php
session_start();
include_once 'dbh.php';
$id = $_SESSION['id'];
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileType = $file['type'];
$fileTempName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png", "pdf");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 500000) {
//I now need to create a unique ID which we use to replace the name
of the uploaded file, before inserting it into our rootfolder
//If I don't do this, we might end up overwriting the file if we
upload a file later with the same name
//Here I use the user ID of the user to create the first part of the
image name
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
$result = mysqli_query($conn, $sql);
header("Location: index.php?uploadsuccess");
}
else {
echo "Your file is too big!";
}
}
else {
echo "There was an error uploading your file, try again!";
}
}
else {
echo "You cannot upload files of this type!";
}
}
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
I suspect logical issue near your below update query:
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
Your logic will run fine for only those users who already having corresponding record in profileimg table. But UPDATE query will do nothing for new user.
So, you will have to first check whether there is a record in profileimg for particular user. If no record then run INSERT query, if record exists then run UPDATE query..
I have a page in which user can update their posts.
I need to update the database with different query(for different Conditions).
But every time I run update using this code, image filename changes automatically (even if I have a condition). Am I doing something wrong?
if(empty($up_image)){
$up_image = $image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$up_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
$path1 = "img/$up_image";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path1)){
copy($path1, "../$path1");
}
}
else{
$error = "Unable to Update Post";
}
}
if(!empty($up_image)){
$up_image = preg_replace('/\s+/','',$up_image);
$image_size = $_FILES['image']['size'];
$allowed_img_ext = array("jpg", "jpeg", "png", "bmp");
$ext = pathinfo($up_image, PATHINFO_EXTENSION);
$trimed_img_name = pathinfo($up_image, PATHINFO_FILENAME);
if(in_array($ext, $allowed_img_ext))//check valid file extension
{
if($image_size < 2097152) {
$ren_image = substr($trimed_img_name,0,3)."".substr($title,0,11)."_".date("mj")."_".date("Y")."_".date("His").".".$ext;
$path = "img/".$ren_image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$ren_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
}
else{
$img_error = "Please Upload the Image File Size Less than 2 MB";
}
}
else{
$img_error = "Invalid Image File";
}
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path)){
copy($path, "../$path");
}
}
else{
$error = "Unable to Update Post";
}
} //End
So I removed $up_image = $image; and image = $up_image section from first query now it is working. Thanks for your comment
I have been having an issue with my code, specifically with the move_uploaded_file. I changed the folder I keep the images in's permissions to 777 to make sure it wasn't a problem with the permissions. I also read a php manual on how to use move_uploaded_file of w3schools.com. I have run out of ideas on how to upload my image to a folder using php. Please help.
Here is the portion of the code with the move_uploeaded_file:
<?php
if (#$_GET['action'] == "ci"){
echo "<form action='account.php?action=ci' method='POST' enctype='multipart/form-data'><br />
Available file extention: <stong>.PNG .JPG .JPEG</stong><br /><br />
<input type='file' name='image' /><br />
<input type='submit' name='change_pic' value='Change' /><br />
</form>";
if (isset($_POST['change_pic'])) {
$errors = array();
$allowed_e = array('png', 'jpg', 'jpeg');
$file_name = $_FILES['image']['name'];
$file_e = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$file_s = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
if(in_array($file_e, $allowed_e) === false) {
$errors[] = 'This file extension is not allowed.';
}
if ($file_s > 2097152) {
$errors[] = 'File size must be under 2MB';
}
if (empty($errors)) {
move_uploaded_file($file_tmp, '../images/'.$file_name);
$image_up = '../images/'.$file_name;
$check = mysqli_query($connect, "SELECT * FROM users WHERE usename='".#$_SESSION['username']."'");
$rows = mysqli_num_rows($check);
while($row = mysqli_fetch_assoc($check)) {
$db_image = $row['profile_pic'];
}
if($query = mysqli_query($connect, "UPDATE users SET profile_pic = '".$image_up."' WHERE username='".$_SESSION['username']."'"))
echo "You have successfuly changed your profile picture!";
} else {
foreach($errors as $error) {
echo $error, '<br />';
}
}
}
}
?>
Here's the last chunk of the code, slightly rewritten. move_uploaded_file returns a boolean, so we can test if it's true or false by setting up a variable $result:
if (empty($errors)) {
$image_up = 'images/'.$file_name;
$result = move_uploaded_file($file_tmp, $image_up);
if($result){
//this line had a typo usename -> username
//Also, you should change this over to using parameters and binding values ASAP. This leaves you open to hacking.
$check = mysqli_query($connect, "SELECT * FROM users WHERE username='".#$_SESSION['username']."'");
$rows = mysqli_num_rows($check);
while($row = mysqli_fetch_assoc($check)) {
$db_image = $row['profile_pic'];
}
$q = "UPDATE users SET profile_pic = '".$image_up."' WHERE username='".$_SESSION['username']."'";
if($query = mysqli_query($connect, $q)){
echo "You have successfuly changed your profile picture!";
}
} else {
echo "Upload failed.";
}
} else {
foreach($errors as $error) {
echo $error, '<br />';
}
}
}
}
I have a simple form for submitting some data into the MySQL DB. On local machine works just fine, but inside a Wordpress page template doesn't work anymore, without getting me any error. The form is inside a page "sitename.com/upload" and i get redirected after submit to the same page (as shown in the link bar), but with 404 page content. I tried without get_header();and get_footer();tags because I thought it may conflict with some variables from wp, but I got the same result.
Here is the code:
<?php function renderForm($name, $price, $error)
{
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
***** LONG HTML FORM IS HERE *****
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string($connection, htmlspecialchars($_POST['name']));
$price = mysqli_real_escape_string($connection, htmlspecialchars($_POST['price']));
$shortdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['shortdesc']));
$longdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['longdesc']));
$current_version = mysqli_real_escape_string($connection, htmlspecialchars($_POST['current-version']));
$content_rating = $_POST['contentrating'];
if(isset($_POST['category'])) {
$category = implode(",", $_POST['category']);
} else {
$category = "";
}
if(isset($_POST['platform'])) {
$platform = implode(",", $_POST['platform']);
} else {
$platform = "";
}
if(isset($_POST['devices'])) {
$devices = implode(",", $_POST['devices']);
} else {
$devices = "";
}
if(isset($_POST['gamemodes'])) {
$gamemodes = implode(",", $_POST['gamemodes']);
} else {
$gamemodes = "";
}
//FILE UPLOAD
$images = array();
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name =$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="uploads/images";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==true){
move_uploaded_file($file_tmp,"uploads/images/".$file_name);
}else{ //rename the file if another one exist
$file_name = time()."-".$file_name;
$new_dir="uploads/images/".$file_name;
rename($file_tmp,$new_dir) ;
}
$images[] = $file_name;
}else{
print_r($errors);
}
}
if(empty($error)){
$imglinks = implode(" | ", $images);
}
}
//FILE UPLOAD END
// check to make sure both fields are entered
if ($name == '' || $price == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($name, $price, $error);
}
else
{
$sql = "INSERT INTO vr_submitted_apps ". "(name, price, shortdesc, longdesc, crtvers, rating, category, platform, devices, gamemodes, images, dtime) ". "VALUES('$name','$price','$shortdesc','$longdesc','$current_version','$content_rating','$category','$platform','$devices','$gamemodes', '$imglinks', NOW())";
// save the data to the database
mysqli_query( $connection, $sql )
or die(mysql_error());
$itemId = mysqli_insert_id($connection);
setcookie("last-inserted-id", $itemId, time() + (86400 * 3), "/"); // 86400 = 1 day
// once saved, redirect back to the view page
header("Location: uploader.html");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
Problem solved: Wordpress has something important internal reserved for "name" parameter.
I want image rename before upload and after renamed image name should be inserted into database with PHP. I am using following code to upload image and insert some other data into database. Please help me out to rename image because I'm beginner with PHP.
<?php
if(isset($_POST['submit'])) {
$post_image = $_FILES['post_image']['name'];
$post_image_tmp = $_FILES['post_image']['tmp_name'];
$post_content = $_POST['post_content'];
if ($post_image=='' OR $post_content=='') {
echo "<script>alert('Fiil In All Fields')</script>";
} else {
move_uploaded_file($post_image_tmp, "../post_imgs/$post_image");
$insert_post ="INSERT INTO posts(post_image,post_content)values('$post_image','$post_content')";
$run_post= mysql_query($insert_post);
echo "<script>alert('Post has been Published Now...')</script>";
echo "<script>window.open('index.php?insert_post=insert','_self')</script>";
}
}
?>
$tmp_file = $_FILES['uploadedfile']['tmp_name'];
$ext = pathinfo($_FILES["uploadedfile"]["name"], PATHINFO_EXTENSION);
$rand = md5(uniqid().rand());
$post_image = $rand.".".$ext;
move_uploaded_file($tmp_file,"../post_imgs/".$post_image);
Try this..
<?php
if(isset($_POST['submit'])) {
$post_image = $_FILES['post_image']['name'];
$post_image_tmp = $_FILES['post_image']['tmp_name'];
$post_content = $_POST['post_content'];
if ($post_image=='' OR $post_content=='') {
echo "<script>alert('Fiil In All Fields')</script>";
} else {
$newname="image".$post_image;
$path='../post_imgs/';
$pathAndName = $path.$newname;
$moveResult = move_uploaded_file($post_image_tmp, $pathAndName);//move to folder
$insert_post ="INSERT INTO posts(post_image,post_content)values('$newname','$post_content')";
$run_post= mysql_query($insert_post);
echo "<script>alert('Post has been Published Now...')</script>";
echo "<script>window.open('index.php?insert_post=insert','_self')</script>";
}
}
?>