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']."'";
Related
It works if i put it like that where user_id = 3 or when i remove the where statement(WHERE user_id=".$user['user_id'].") but then all my password in the db change.
I used get method to get the userid like that
user_id=3&reset_token=xxxxxxxxx
<?php
if( isset($_GET['user_id']) && isset($_GET['reset_token']) ) {
$userid = $_GET['user_id'];
$reset_token = $_GET['reset_token'];
// Make sure user email with matching hash exist
$req = $heidisql->prepare("SELECT * FROM users WHERE user_id='$userid' AND reset_token='$reset_token' ");
$req->execute($userid, $reset_token );
$user = $req->fetch(PDO::FETCH_ASSOC);
if ($user) {
if (!preg_match ('%\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{8,30}\z%', $_POST['new_pass'])
|| $_POST['new_pass'] !== $_POST['confirm_newpass'] ) {
echo 'Your new password did not match the new confirm password or is invalid!';
exit();
}
}
} else {
$newpassword = escape_data($_POST['new_pass']);
$newpass_hash = password_hash($newpassword, PASSWORD_BCRYPT);
$sql= "UPDATE users SET "
. "password_hashcode='$newpass_hash', "
. "reset_allocated_time=NULL, "
. "reset_token=NULL "
. "WHERE user_id=".$user['user_id']." "; //<- error here
// Make sure user email with matching hash exist
$result_newpass = $heidisql->prepare($sql);
$result_newpass->execute();
echo "Your password has been reset!";
exit();
}
already try user_id = '$userid'/ $_GET['user_id']
So, how should i define the variable user_id?
Still does not work
$req = $heidisql->prepare("SELECT * FROM users WHERE user_id=':user_id' AND reset_token=':reset_token' ");
$req->execute([':user_id'=>$userid, ':reset_token'=>$reset_token]);
$sql= "UPDATE users SET password_hashcode=':password_hashcode', reset_allocated_time=NULL, reset_token=NULL WHERE user_id=:user_id";
$result_newpass = $heidisql->prepare($sql); $result_newpass->execute([':user_id'=>$userid,':password_hashcode'=>$newpass_hash, ':reset_token'=>NULL, ':reset_allocated_time'=>NULL]);
- I believe the problem may lies with the get method cause it seems that I cannot properly access the user_id/reset_token in the URL?
...localhost/example/reset_pass.php?user_id=xx&reset_token=xxxxxxxxx
I am getting undefined variable at user_id
Anyone knows if that the problem(s) cause my password validation also does not work?
Update this $sql from here:
$sql = "UPDATE users SET
password_hashcode = '$newpass_hash',
reset_allocated_time = NULL,
reset_token = NULL
WHERE user_id = '$user['user_id']'";
When using prepared statements you don't actually include the values in the statement. Instead you use placeholders, and bind the values later.
Change:
$req = $heidisql->prepare(
"SELECT * FROM users WHERE user_id='$userid'
AND reset_token='$reset_token' "
);
$req->execute($userid, $reset_token );
To:
$req = $heidisql->prepare(
"SELECT * FROM users WHERE user_id=:id
AND reset_token=:token "
);
$req->execute([':id'=>$userid, ':token'=>$reset_token]);
See the docs
Further down, you have:
$newpassword = escape_data($_POST['new_pass']);
$newpass_hash = password_hash($newpassword, PASSWORD_BCRYPT);
It's probably a bad idea to change the password (escape) before hashing it. Just hash it; the result will be safe to use. Changing it runs the risk of the user's true password not being recognized if your escape function changes in the future.
Further down you should change:
$sql= "UPDATE users SET password_hashcode='$newpass_hash',"
. "reset_allocated_time=NULL, reset_token=NULL "
. "WHERE user_id=".$user['user_id']." "; //<- error here
$result_newpass = $heidisql->prepare($sql);
$result_newpass->execute();
To:
$sql= "UPDATE users SET password_hashcode=:newpass,"
. "reset_allocated_time=NULL, reset_token=NULL "
. "WHERE user_id=:id"; //<- error here
$result_newpass = $heidisql->prepare($sql);
$result_newpass->execute([':newpass'=>$newpass_hash, ':id'=>$userid]);
I'm currently doing a Web Programming module at university and have been having trouble with some of the homework set. We are meant to insert code that updates our current mysql table with new information (gender, age, email, comment). This information needs to be inserted into the row of each persons session generated ID (currID). How do we code for the updated information to be inserted into a session-specific row?
<?php
session_start();
include('muqHeader.html');
include('commonSrc.php');
include('../shareCode/mysqlLink.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST'):
// update the mf record
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
}else{
echo "Not a valid email address";
}
if(filter_var($_POST['comment'], FILTER_SANITIZE_STRING)){
}else{
echo "Text includes invalid characters";
}
$gender = $_POST['gender'];
$age = $_POST['age'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$currID = $_SESSION['currID'];
if ($_POST['submit']){
$sql = "UPDATE muq
SET (gender='$gender', age = '$age', email = '$email', comment = '$comment')
WHERE (muqID = '$currID')";
}
if (#mysqli_query($link, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . #mysqli_error($link);
}
else:
$useTime = implode(',', $_SESSION['useTime'] );
$usedM = implode( ',', $_SESSION['usedM'] );
$tmp = array();
for($i=0; $i < count($_SESSION['freqRate']); $i++) {
$tmp[$i] = implode( '', $_SESSION['freqRate'][$i] ); // empty string as 'glue'
}
$freqRate = implode( ',', $tmp );
$dateTime = $_SESSION['dateTime'];
$taskTime = (time() - $_SESSION['startTime']) / 60; //in minutes
$sql = "INSERT INTO muq
(dateTime, taskTime, useTime, usedM, freqRate)
VALUES ('$dateTime', '$taskTime', '$useTime', '$usedM', 'freqRate')";
$link = connectDB();
#mysqli_query( $link, $sql );
$_SESSION['currID'] = #mysqli_insert_id($link);
#mysqli_close($link);
?>
Well, before answearing your question, here is some coding rules you need to respect:
1- You don't have to use more lines than what you need. This means you don't have to do an an empty "if" using 4 lines if you can do it in 2 lines.
Example:
Instead of:
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
}else{
echo "Not a valid email address";
}
You can do:
if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
echo "Not a valid email address";
Second thing, to update a row in a database, you need an ID. This the key you are going to use to tell your db engine which row you are going to update because if not "he" will not know which row "he" should update (I'm considering the db engine as a person like me and you :D )
So, you need to inject that key (account ID or whatever) in your session so that you can use later when updating your database by telling you db engine that "he" needs to update that row identified by that key.
end web developer, i was given a CMS done from another team and i have to link with my front-end. I have made some modifications, but due to my lack of php knowledge i have some issue here.
My users are able to fill up a form, where 1 text field is asking for their photo link. I want to check for if the value entered is not equal to what i want, then i will query insert a default avatar photo link to mysql to process.
code that i tried on php
// check if the variable $photo is empty, if it is, insert the default image link
if($photo = ""){
$photo="images/avatarDefault.png";
}
doesn't seem to work
<?php
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//Used to establish connection with the database
include 'dbAuthen.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Used to Validate User input
$valid = true;
//Getting Data from the POST
$username = sanitizeInput($_POST['username']);
$displayname = sanitizeInput($_POST['displayname']);
$password = sanitizeInput($_POST['password']);
//hash the password using Bcrypt - this is to prevent
//incompatibility from using PASSWORD_DEFAULT when the default PHP hashing algorithm is changed from bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
//Determining Type of the User
//if B - User is student
//if A - User is adin
if($_POST['type'] == 'true')
$type = 'B';
else
$type = 'A';
$email = sanitizeInput($_POST['email']);
$tutorGroup = sanitizeInput($_POST['tutorGroup']);
$courseID = sanitizeInput($_POST['courseID']);
$description = sanitizeInput($_POST['desc']);
$courseYear = date("Y");
$website = sanitizeInput($_POST['website']);
$skillSets = sanitizeInput($_POST['skillSets']);
$specialisation = sanitizeInput($_POST['specialisation']);
$photo = sanitizeInput($_POST['photo']);
// this is what i tried, checking if the value entered is empty, but doesn't work
if($photo = ""){
$photo="images/avatarDefault.png";
}
$resume = sanitizeInput($_POST['resume']);
//Validation for Username
$sql = "SELECT * FROM Users WHERE UserID= '$username'";
if (mysqli_num_rows(mysqli_query($con,$sql)) > 0){
echo 'User already exists! Please Change the Username!<br>';
$valid = false;
}
if($valid){
//Incomplete SQL Query
$sql = "INSERT INTO Users
VALUES ('$username','$displayname','$hashed_password','$type','$email', '$tutorGroup', ";
//Conditionally Concatenate Values
if(empty($courseID))
{
$sql = $sql . "NULL";
}
else
{
$sql = $sql . " '$courseID' ";
}
//Completed SQL Query
$sql = $sql . ", '$description', '$skillSets', '$specialisation', '$website', '$courseYear', '$photo', '$resume', DEFAULT)";
//retval from the SQL Query
if (!mysqli_query($con,$sql))
{
echo '*Error*: '. mysqli_error($con);
}
else
{
echo "*Success*: User Added!";
}
}
//if student create folder for them
if ($type == 'B')
{
//Store current reporting error
$oldErrorReporting = error_reporting();
//Remove E_WARNING from current error reporting level to prevent users from seeing code
error_reporting($oldErrorReporting ^ E_WARNING);
//Set current reporting error();
error_reporting($oldErrorReporting);
}
mysqli_close($con);
}
}
function sanitizeInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
i've tried finding a way on mysql to insert default values but it seem impossible, so i have no choice but to query insert through php.
I have the logic but i'm not sure how to implement on the php with my lack of knowledge, i was thinking of checking either
1) if the photo link does not have the word .png/.jpg, $photo != ".png"
2) if the photo link length is too low $.photo.length < 10
can someone help me look into the code and tell me what i'm doing wrong? Thanks!
A very simple way with default values could be:
$photo = isset($photo) ? $photo : 'images/avatarDefault.png' ;
How it works is that it first it asks if the photo is set, if it is, use all ready inserted value, otherwise insert your default value,
Another (very alike) method to use:
$photo = !empty($photo) ? $photo : 'images/avatarDefault.png' ;
UPDATE
To check if it contains a certain "extension" would be a simple rewrite
$photo = preg_match('#\b(.jpg|.png)\b#', $photo ) ? $photo : "images/avatarDefault.png" ;
This way it checks wether the text / image link in $photo contains the .png file type, if it doesn't it inserts your default image
First thing that I notice is to use double =
if($photo == ""){
//...
}
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>";
}
?>
I've been searching for a long time for a solution to what I feel is a very simple problem.
I have a dynamically created page with a video that has a unique id. I also have a form that a user can submit content with. I want the id of the video to be included in the submission to tableA.
This code works great only when $id = 1.
$vidq = "SELECT * FROM tutorials";
$vidresult = mysql_query($vidq);
$vidrow = mysql_fetch_array($vidresult);
//form submission
if($_POST['formname'] == "submit") {
$name = $_POST['name'];
$id = $vidrow['id'];
$errorMessage = "";
if(empty($name)) {
$errorMessage .= "<li>Please enter a valid name</li>";
}
if(empty($errorMessage)) {
$insert = "INSERT INTO tableA (videoid, name) VALUES (".$id.", ".$name.")";
mysql_query($insert);
exit();
}
}
When I change $id to = 1, it posts, but when $id to = $vidrow['id'] it doesn't post.
What am I doing wrong?
Try displaying the mysql error message by using mysql_errno/mysql_error. Eg...
if (!mysql_query($insert))
{
die('MySQL Fail (' . mysql_errno() . ') - ' . mysql_error());
}
mysql_errno() documentation - http://php.net/manual/en/function.mysql-errno.php
Have you tried to print out the contents of $id after $id = $vidrow['id'];? It might reveal why it doesn't work the way you want...
Have you thought about what might happen if a malicious (or just curious) user calls your script with ?name=%27%27%29%3b%20DROP%20TABLE%20tableA%3B?