-2

I would like to update a record in the database but only one at a time. Currently, when i click submit all other values is null and will be deleted from the database. How do i make it so the other values are maintained?

The only work around i can think of is to make each field a separate process in itself but that seems unefficient

This is the processing file:

<?php
session_start();

$host="localhost";
$user="root";
$password="";
$db="portal";

$data=mysqli_connect($host,$user,$password,$db);
$currentuser = $_SESSION["username"];

if($data===false)
{
    die("connection error");
}

if(isset($_POST['submit']))
{
    $username=$_POST['username'];
    $password=$_POST['password'];
    $name=$_POST['name'];
    $phonenum=$_POST['phonenum'];
    $address=$_POST['address'];
    $email=$_POST['email'];

    $sql="UPDATE user SET username='$username', password='$password', name='$name', phonenum='$phonenum', address='$address', email='$email' WHERE username = '$currentuser'";
    $result=mysqli_query($data,$sql);
}
?>

<!doctype html>
<html>

<head>
<title>User Updated!</title>
    
<!--Icons-->
<script src="https://kit.fontawesome.com/5669020dd7.js" crossorigin="anonymous"></script>
<!--Font-->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@300;400;600&display=swap" rel="stylesheet">
<!--For navbar-->
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<style>
body {
    background-image:url('bg5.png');
    background-color:#9ec6e4;
    background-size: 100% auto;
    font-family: 'Source Sans Pro', sans-serif;
}

.main {
  margin-left: 220px; /* Same as the width of the sidenav */
  padding: 0px 10px;
}

.bgbox {
    position: absolute;
    z-index: -1;
}

.container {
  border-radius: 5px;
  background-color: #fffdd0;
  padding: 20px;
}

h1 {
    font-family: 'Source Sans Pro', sans-serif;
    font-size: 50px;
}

.padding {
    margin-left: 50px;
}

/*button*/
.button {
    background-color: #d1b7a0;
    border-radius: 8px;
    font-family: 'Source Sans Pro', sans-serif;
    color: black;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    padding: 5px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 8px;
    cursor: pointer;
}
    
.button:hover {
    background-color: #5f4f47;
    color: #d1b7a0;
}
/*button*/

</style>
</head>

<body>
<!--navbar-->
<div id="usernav">
</div>
<script>
$(function(){
  $("#usernav").load("usernav.html");
});
</script>
<!--navbar-->

<div class="main">
<br>
    <a>Welcome, </a><?php echo $_SESSION["username"] ?><a>!</a>
</div>
<br>
<div class="bgbox">
    <img src="box.png" style="opacity:0.6; width: 100%;">
</div>

<div class="main">
    <br><br>
    <div class="container">
        <h1>User Updated!</h1>
        <div class="padding">
            <?php echo "<b>Username:</b> $username<br/><br/>";
            echo "<b>Name:</b> $name<br/><br/>";
            echo "<b>Phone Number:</b> $phonenum<br/><br/>";
            echo "<b>Office Address:</b> $address<br/><br/>";
            echo "<b>Email:</b> $email";?>
        </div>
    </div>
</div>

</body>
</html>

This is my html:

<?php
session_start();

$host="localhost";
$user="root";
$password="";
$db="portal";

$data=mysqli_connect($host,$user,$password,$db);
$currentuser = $_SESSION["username"];

if($data===false)
{
    die("connection error");
}

if(isset($_POST['submit']))
{
    $username=$_POST['username'];
    $password=$_POST['password'];
    $name=$_POST['name'];
    $phonenum=$_POST['phonenum'];
    $address=$_POST['address'];
    $email=$_POST['email'];

    $sql="UPDATE user SET username='$username', password='$password', name='$name', phonenum='$phonenum', address='$address', email='$email' WHERE username = '$currentuser'";
    $result=mysqli_query($data,$sql);
}
?>

<!doctype html>
<html>

<head>
<title>User Updated!</title>
    
<!--Icons-->
<script src="https://kit.fontawesome.com/5669020dd7.js" crossorigin="anonymous"></script>
<!--Font-->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@300;400;600&display=swap" rel="stylesheet">
<!--For navbar-->
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<style>
body {
    background-image:url('bg5.png');
    background-color:#9ec6e4;
    background-size: 100% auto;
    font-family: 'Source Sans Pro', sans-serif;
}

.main {
  margin-left: 220px; /* Same as the width of the sidenav */
  padding: 0px 10px;
}

.bgbox {
    position: absolute;
    z-index: -1;
}

.container {
  border-radius: 5px;
  background-color: #fffdd0;
  padding: 20px;
}

h1 {
    font-family: 'Source Sans Pro', sans-serif;
    font-size: 50px;
}

.padding {
    margin-left: 50px;
}

/*button*/
.button {
    background-color: #d1b7a0;
    border-radius: 8px;
    font-family: 'Source Sans Pro', sans-serif;
    color: black;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    padding: 5px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 8px;
    cursor: pointer;
}
    
.button:hover {
    background-color: #5f4f47;
    color: #d1b7a0;
}
/*button*/

</style>
</head>

<body>
<!--navbar-->
<div id="usernav">
</div>
<script>
$(function(){
  $("#usernav").load("usernav.html");
});
</script>
<!--navbar-->

<div class="main">
<br>
    <a>Welcome, </a><?php echo $_SESSION["username"] ?><a>!</a>
</div>
<br>
<div class="bgbox">
    <img src="box.png" style="opacity:0.6; width: 100%;">
</div>

<div class="main">
    <br><br>
    <div class="container">
        <h1>User Updated!</h1>
        <div class="padding">
            <?php echo "<b>Username:</b> $username<br/><br/>";
            echo "<b>Name:</b> $name<br/><br/>";
            echo "<b>Phone Number:</b> $phonenum<br/><br/>";
            echo "<b>Office Address:</b> $address<br/><br/>";
            echo "<b>Email:</b> $email";?>
        </div>
    </div>
</div>

</body>
</html>
  • 2
    Beware that you're wide open to SQL injection by manually concatenating `$_POST` data into your query. See https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 for suggestions to prevent this. Can you clarify what the problem is? Your query already has `WHERE username = x`, so it should only be updating user `x`. Can you confirm what the value of `$currentuser` is before the query is run? It also looks like you pasted the same HTML file twice in your question. – WOUNDEDStevenJones Jan 04 '22 at 17:37
  • If you're submitting an array of values (``), then `$_POST['username']` should return an array by default, and you can iterate over that to make a query for each user submitted. See https://stackoverflow.com/questions/21750478/retrieve-post-array-values for more info. – WOUNDEDStevenJones Jan 04 '22 at 17:40
  • when i update name, it updates the correct user, but all the other fields (email, password, etc) are blank because the field is empty as i only want to update name. i am looking for a way to be able to update only the field that the user entered. – Nina Naushad Jan 04 '22 at 17:40
  • 1
    Then by all means, remove the other fields from the `UPDATE` statement, and only update what you actually want to update. ;) – Markus AO Jan 04 '22 at 17:41
  • ah, then you can dynamically build your query with conditionals or you can change your query to be something like `SET phonenum = IFNULL($phonenum, phonenum)` so it will either set the new value, of if that's null it will use the existing `phonenum` value in the query. – WOUNDEDStevenJones Jan 04 '22 at 17:42
  • @MarkusAO but i want the user to be able to update any field – Nina Naushad Jan 04 '22 at 17:43
  • Either preload all the fields of the form with what is currently in the DB, or submit each one individually with an if statement looking for it the field is empty or not. – John Jan 04 '22 at 17:44
  • @WOUNDEDStevenJones if i do it dynamically, i have to separate the query individually right? – Nina Naushad Jan 04 '22 at 17:45
  • @John how do i preload the fields? i cant seem to find resources on it. can i use the 'value' tag and print the data from the database? – Nina Naushad Jan 04 '22 at 17:47
  • This should get you started: `$query = "SELECT id, username, password, name, ect... FROM YOURTABLESNAME WHERE username = $currentuser "; ` – John Jan 04 '22 at 17:52
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Jan 04 '22 at 20:50

1 Answers1

0

One way to do this is by building the query dynamically by checking the fields that you want to update before adding them to the query. This is untested, but should be the gist of what you're trying to do. It adds the various SET x = y values to an array (and separately, the parameterized values to avoid SQL injection).

<?php

if (isset($_POST['submit']))
{
    $username=$_POST['username'];
    $password=$_POST['password'];
    $name=$_POST['name'];
    $phonenum=$_POST['phonenum'];
    $address=$_POST['address'];
    $email=$_POST['email'];
}

// placeholder arrays while we determine which fields/values to update
$set = [];
$parameters = [];

// do we need to update address?
// note: check if it's set and if it's truthy so we don't submit empty strings (unless you want the user to be able to submit blank data?)
if (isset($address) && $address) {
    $set[] = ' address = ? ';
    $parameters[] = $address;
}

// do we need to update name?
if (isset($name) && $name) {
    $set[] = ' name = ? ';
    $parameters[] = $name;
}

// do we need to update phonenum?
if (isset($phonenum) && $phonenum) {
    $set[] = ' phonenum = ? ';
    $parameters[] = $phonenum;
}

// as long as we have some values to update, run the query
if (count($set) > 0) {
    // build the SQL query
    $sql = "UPDATE user SET ".implode(', ', $set).' WHERE username = ?';
    $parameters[] = $currentuser;

    //run the parameterized query
    $stmt = $pdo->prepare($sql);
    $stmt->execute($parameters);
}

Another method would be to first query the current user's data and use that to pre-populate the input fields, and then your query can always update every field. You'll likely want to build in some extra functionality/validation for the password field (confirm password? Special characters or length requirements?), but again this is the basic idea of how to do it:

<?php
    if(isset($_POST['submit'])) {
        $username=$_POST['username'];
        $password=$_POST['password'];
        $name=$_POST['name'];
        $phonenum=$_POST['phonenum'];
        $address=$_POST['address'];
        $email=$_POST['email'];

        $sql="UPDATE user SET username='$username', password='$password', name='$name', phonenum='$phonenum', address='$address', email='$email' WHERE username = '$currentuser'";
        $result=mysqli_query($data,$sql);
    } else {
        $stmt = $pdo->prepare("SELECT username, phonenum, name, address, email FROM user WHERE username = ?");
        $stmt->execute([$currentuser]);
        // https://www.php.net/manual/en/pdostatement.fetchall.php
        $result = $sth->fetchAll(PDO::FETCH_ASSOC);
    }
?>

<form>
    <input name="username" type="text" value="<?= $result['username']; ?>" />
    <input name="phonenum" type="tel" value="<?= $result['phonenum']; ?>" />
    <input name="name" type="text" value="<?= $result['name']; ?>" />
    <input name="address" type="text" value="<?= $result['address']; ?>" />
    <input name="email" type="email" value="<?= $result['email']; ?>" />
</form>
WOUNDEDStevenJones
  • 5,150
  • 6
  • 41
  • 53