I can't see the problem here. I enter data in my input cells and after submit it only refresh a page and do not post anything in the MySQL. I'm doing this by watching online tutorial which is old, so maybe there are some old methods, that could be a problem.
<?php
include "../db/connect.php";
if (isset($_POST['pavadinimas'])) {
$pavadinimas = mysqli_real_escape_string($con, $_POST['pavadinimas']);
$kaina = mysqli_real_escape_string($con, $_POST['kaina']);
$info = mysqli_real_escape_string($con, $_POST['info']);
$gamintojas = mysqli_real_escape_string($con, $_POST['gamintojas']);
$gamintojas = mysqli_real_escape_string($con, $_POST['atmintis']);
$tipas = mysqli_real_escape_string($con, $_POST['tipas']);
$kiekis = mysqli_real_escape_string($con, $_POST['kiekis']);
// See if that product name is an identical match to another product in the system
$sql = mysqli_query($con, "SELECT id FROM prekes WHERE pavadinimas='$pavadinimas' LIMIT 1");
$productMatch = mysqli_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo '<script type="text/javascript">alert("KLAIDA! Bandėte įkelti prekę, kurios pavadinimas jau yra įrašytas duomenų bazėje.");</script>';
exit();
}
// Add this product into the database now
$sql = mysqli_query($con, "INSERT INTO prekes (pavadinimas, kaina, info, gamintojas, atmintis, tipas, kiekis, laikas)
VALUES('$pavadinimas','$kaina','$info','$gamintojas','$atmintis','$tipas','$kiekis',now())") or die (mysqli_error($con));
$pid = mysqli_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: itemList.php");
exit();
}
?>
There was just a dumb mistake. In html SUBMIT button name was set to 'button', not submit, so it didn't post it to the database.
and this
if (isset($_POST['pavadinimas']))
should have been this
if (isset($_POST['submit']))
Related
I'm in need of some help with my PHP query. I'm essentially giving users the opportunity to update their own details once they have logged in. The form:
<div class="grid-2">
<p><b>UPDATE MY DETAILS</b></p>
<form action ="includes/update.inc.php" method ="post">
<label>S.Name</label>
<input name="update-surname" type="text" placeholder="Enter new surname...">
<label>Address</label>
<input name="update-houseno" type="text" placeholder="Enter house no' or name...">
<input name="update-ln1" type="text" placeholder="1st Line of Address...">
<input name="update-town" type="text" placeholder="Town...">
<input name="update-county" type="text" placeholder="County...">
<input name="update-postcode" type="text" placeholder="Postcode...">
<label>Contact Number</label>
<input name="update-number" type="text" placeholder="Contact Number...">
<label>Email</label>
<input name="update-email" type="text" placeholder="Email...">
<input type="submit" name="update-details" value="Update">
</form>
</div>
My php code which I have currently, if the user doesn't enter anything in the box, it updates the database with a blank input (which I don't want to happen), if there's no input I don't want that field in the table touched.
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$surname = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$query = "UPDATE `tblMember` SET `fldSName` = '$surname', `fldTelNum` = '$number', `fld1stLnAddress` = '$houseno', `fld2ndLnAddress` = '$ln1', `fld3rdLnAddress` = '$town', `fldCounty` = '$county', `fldPostcode` = '$postcode', `fldEmailAddress` = '$email' WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query) or die ("error");
}
?>
Once the php form is loaded, the web page disappears and doesn't stay on the current webpage their on either.
So 2 things needed, help with the correct query and help with the page going blank and not staying on the webpage.
Please note that I know this is vulnerable to injection attack I'm just trying to get it physically working before I attempt to get my head around how I do prepared statements.
Thanks!
You need to check if data input field is non-empty/valid.
Steps to avoid blank fields update:
1) Take an empty array
2) Check if every posted variable is valid, if it valid append it to array.
3) Check if the array is not empty.
4) If its not empty, fire SQL.
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$ln1 = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$update = [];
if (! empty($surname)) {
$update['fldSName'] = "fldSName = '".$surname ."'";
}
if (! empty($number)) {
$update['fldTelNum'] = "fldTelNum='".$number ."'";
}
if (! empty($houseno)) {
$update['fld1stLnAddress'] = "fld1stLnAddress='".$houseno ."'";
}
if (! empty($ln1)) {
$update['fld2ndLnAddress'] = "fld2ndLnAddress='".$ln1 ."'";
}
if (! empty($town)) {
$update['fld3rdLnAddress'] = "fld3rdLnAddress='".$town ."'";
}
if (! empty($county)) {
$update['fldCounty'] = "fldCounty='".$county ."'";
}
if (! empty($postcode)) {
$update['fldPostcode'] = "fldPostcode='".$postcode ."'";
}
if (! empty($email)) {
$update['fldEmailAddress'] = "fldEmailAddress='".$email ."'";
}
if (! empty($update)) {
$query = "UPDATE `tblMember` SET ";
$query .= implode(', ', $update);
$query .= " WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query) or die ("error");
}
}
?>
NOTE:
fldMemberID seems to be hard-coded.
For first concern you can edit your query as
UPDATE tblMember
SET fldSName = IF('$surname' = '', fldSName, '$surname'),
fldTelNum = IF('$number' = '', fldTelNum, '$number'),
fld1stLnAddress = IF('$houseno' = '', fld1stLnAddress, '$houseno'),
fld2ndLnAddress = IF('$ln1' = '', fld2ndLnAddress, '$ln1'),
fld3rdLnAddress = IF('$town' = '', fld3rdLnAddress, '$town'),
fldCounty = IF('$county' = '', fldCounty, '$county'),
fldPostcode = IF('$postcode' = '', fldPostcode, '$postcode'),
fldEmailAddress = IF('$email' = '', fldEmailAddress, '$email'),
WHERE
`tblMember`.`fldMemberID` = 1
For Second concern you have to remove die() and redirect to after-login.php as
$conn->query($query);
header("Location: ../after-login.php");
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$surname = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$query = "UPDATE `tblMember` SET ";
(!empty($surname))?: $query .= "`fldSName` = '$surname',";
(!empty($houseno))?: $query .= "`fldTelNum` = '$houseno',";
(!empty($ln1))?: $query .= "`fld1stLnAddress` = '$ln1',";
(!empty($town))?: $query .= "`fld2ndLnAddress` = '$town',";
(!empty($county))?: $query .= "`fld3rdLnAddress` = '$county',";
(!empty($postcode))?: $query .= "`fldCounty` = '$postcode',";
(!empty($email))?: $query .= "`fldPostcode` = '$email',";
(!empty($number))?: $query .= "`fldEmailAddress` = '$number'";
$query .= " WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query);
header("Location: ../after-login.php"); //make sure of the path
}
Basically you are checking your input values and like that you build your query by concatenating the query blocks.
At the end added the header to redirect you to the page you want.
this is my code updating data. How is it possible to use old image if no image is selected?
its a profile page when someone updates his profile but don't select the image for update then old image should be remained there..
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
if(isset($name)){
move_uploaded_file($temp_name,$location.$name);
}
else
{
echo $user_img;
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>
First, you need to fetch the existing user details from the database and check if the user already has a profile picture.
Next, if the user has uploaded a new image, then you can delete the old profile picture using unlink() function. If the user has not uploaded a new picture, you can retain the old picture.
See the code below.
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
//Fetch user details
$query = "SELECT User_Pic FROM user WHERE Id=" . $update_id;
$result = mysqli_query($con, $query);
$row = false;
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
}
if (isset($_FILES['user_img'])) { //User uploaded new image
if ($row) {
unlink($location . $row['User_Pic']); //Delete old pic
}
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
move_uploaded_file($temp_name,$location.$name);
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
} else { //User did not upload image
if ($row) {
echo $location . $row['User_Pic']; //Echo current image path
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username' where Id='$update_id'";
}
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>
Please note that the code shown here does not change the filename when storing the files on the server. This will cause problems when two person upload pictures with same filename. You need to implement an appropriate solution for that.
This code runs when a user hits a delete button on my form. I am trying to copy a file, $picfile, from "/pics/" to "/pics/deletedrecordpics/" and then delete the orginal. Finally, delete the record from the database. Deleting the record from the databse works, but copying the file and deleting the original does nothing. There are no errors in the error log, so I am really confused as to why this code isn't running as I think it should.
if ($allowdelete==true && $thepassword == $password)
{
//delete record that delete was set to by button
//$sql = ("DELETE FROM $table WHERE id=$id");
$sql = ("select picfile,title,author from $table where id=$delete");
$file=mysql_query($sql);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
if (file_exists("/pics".$picfile)){
copy("/pics/".$picfile,"/pics/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink("/pics/".$picfile);
echo $available = "image is available.";
$sql = ("DELETE FROM $table WHERE id=$delete");
$result = mysql_query($sql);
if ($result){
echo "Your Picture has been removed from our system.";
Die($available);
}
else{
echo "There was an error in removing your picture.";
$Delete = "";
Die();
}
}
else{
echo $available = "image is not available.";
}
}
The weird part is a have almost the same code in a delete button on my control panel located in "/adminpanel" and it works perfectly. The code for that is the same except I use $id instead $delete and "../" before all the "pics/" because it's in the adminpanel folder. The permissions are right and the folder exists because the code works with that page. And I know $delete is getting set because the record gets deleted from the database. I know picfile, author and title are getting set because I appended them to the print statement and they were all right. Really confused. Any ideas?
Here is the code for the working page
q = ("select picfile,title,author from $table where id=$id");
$file=mysql_query($q);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
copy("../pics/".$picfile,"../pics/deletedrecordpics/".$author." - ".$title." - ".$picfile);
unlink("../pics/".$picfile);
$file=mysql_query($q);
$q = ("DELETE FROM $table WHERE id=$id");
$file=mysql_query($q);
why is this line repeated twice $file=mysql_query($q); ?
Try this
$file_path = $_SERVER["DOCUMENT_ROOT"]."/pics/";
if (file_exists($file_path.$picfile))
{
copy($file_path.$picfile, $file_path."/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink($file_path.$picfile);
}
else
{
echo "File not found!!!!!!!!";
}
I want to update my data in mysql.
But, if i want update (ex. firstname), photo_profile will lost.
<?php
include 'function_page_user.php';
if(($_FILES['photo_profile']) and ($_POST['firstname']) and ($_POST['lastname']) and ($_POST['password']))
{
session_start();
include 'connect.php';
$foldername="assets/img/user/";
$firstname = mysql_real_escape_string($_POST["firstname"]);
$lastname = mysql_real_escape_string($_POST["lastname"]);
$pwd = mysql_real_escape_string($_POST["password"]);
if((!empty($firstname) and !empty($lastname) and !empty($pwd)) and($_FILES['photo_profile']))
{
$image = $foldername . basename ($_FILES['photo_profile'] ['name']);
mysql_query ("update user set firstname = '".$firstname."' , lastname = '".$lastname."' , password = '".$pwd."' , photo_profile='".$image."' where id_user ='".$_SESSION['id']."'");
move_uploaded_file($_FILES['photo_profile']['tmp_name'], $image);
echo "<script>alert ('File Succes To edit');</script>";
$page="formubahuser.php";
echo redirectPage($page);
}
else echo "variabel empty";
}
else
echo ("your data is not complete<a href=formubahuser.php>Fill it again</a>");
?>
You have a number of major problems in your code. Before you continue, you need to read about the following topics:
1) The php mysql_ functions have been deprecated. That means the functions will be removed in future versions of php. You should use pdo or mysqli instead
2) When you store passwords in your database, they should always, always, always be encrypted.
Regarding your question, I think you are asking how to change the metadata (such as a firstname) without unsetting the photo url. Try something like this:
$updatequery = "UPDATE user SET firstname = '".$firstname."' , lastname = '".$lastname."' , password = '".$pwd."'";
if( $_FILES['photo_profile'])
{
$image = $foldername . basename ($_FILES['photo_profile'] ['name']);
$updatequery .= ", photo_profile='".$image."'";
}
$updatequery .= " where id_user ='".$_SESSION['id']."'";
I have a simple question,
I have a login and workspace area.
After the user logs in It shows the username of the logged in user at workplace as what I wanted. Now my problem is when user finish filling form available in his workspace the form is then stored in database also i need the username that is coming from session also get stored to the database.
here is code that is storing username and maintaining session after user reach at workspace after login:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/MainProject/connect/auth.php');
session_start();
?>
The final version of the updated insert file :
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
// session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>
In the logging in process, you must store your username in a session
$_SESSION['username'] = $username;
in the process of saving the form, you can call session_start(); and get the session using
$tobeinserted = $_SESSION['username'];
I believe
Remove comment in session start.
Use this.
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
//$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>