PHP MySQL Create profile update form and show old data on it before changing/updating

I am new at using php with mysql. At my age, I doubt that I can learn how to do this so I will ask.
I want to create a profile form that will show the current settings in it then allow me to either save the old settings or change and save them. Can that be done on one form? It seems to me that it could, but I have no idea how to go about it.
Any help or demo code would be appreciated. Thank you.

I can’t really show you as how I do it involves JavaScript, but I do it all the time. What I would do is find an updated tutorial online on editing data in an HTML form to help you out. I’m 59 years old, but I have seen 75 years old who do it all the time.

I have a repository https://github.com/Strider64/brain-wave-blitz (my current one), but I have older repositories that would at least help you get the gist of it.

Thanks, I will look at it. I am 76 and a retired in the computer field after 37 years. 4 mini strokes forced my retirement. My experience is divided between teaching, programming, and repair. My languages were Basic, Machine and Assembly, C++, HTML, and PHP. I have forgotten most of it due to one of the strokes. Thanks again.

I did not find anything that would help me there. but I did find something that almost did. We have to use gmail for the email. Your mailer script came close, but did not address the fact that we do not have a mail daemon. The server is free, so we can’t ask them to pit a mail daemon on it. Do you have anything for gmail?

The code for any php should be laid out in this general order -

  1. initialization
  2. post method form processing
  3. get method business logic - get/produce data needed to display the page
  4. html document

For the activity you are trying to accomplish, after making sure that the current user is logged in in order to access the page at all, you would query at item #3 in the code to get the current user data, but only if the form has never been submitted. The way to detect if the form has never been submitted is to use a working array variable to hold a trimmed copy of the form data. You would initialize this variable to an empty array in the initialization code section. Inside the post method form processing, you would store a trimmed copy of the post form data in it. At the point of getting the current user data, if the variable is empty, you would query to get the user’s data and store it in the array variable. You would reference elements in the array variable throughout the rest of the code.

The post method form processing code would first detect if a post method form has been submitted. If it has, it would then trim all the input data at once, storing it in the array variable. You would then validate all the inputs, storing user/validation errors in an array, using the field name as the main array index. After the end of the validation logic, if there are no user/validation errors, use the submitted, trimmed, form data.

As stated in your previous thread, the UPDATE query would be a prepared query in order to prevent any sql special characters in a value from being able to break the sql query syntax, which is how sql injection is accomplished.

Since this activity could result in duplicate values for database columns that must be unique, such as the username, email address, …, you would test in the exception error handling for the UPDATE query if a unique index error (number) occurred. If it did, and there is a single column that is defined as a unique index, you know the duplicate value was in that column, and you would setup a user/validation error message (add it to the array holding the user/validation errors) letting the user know what was wrong with the data that they submitted. If there is more than one column that is defined as a unique index, you would build and execute a SELECT query to find which columns contain duplicate values, and you would setup user/validation error message(s) (add it(them) to the array holding the user/validation errors) letting the user know what was wrong with the data that they submitted. For all other query error numbers, just rethrow the exception and let php handle it.

After using the submitted form data, if there are no errors, the data was successfully updated. You would perform a redirect to the exact same url of the current page to cause a get request for that page. This will prevent the browser from trying to resubmit the form data should that page get refreshed or browsed away from and back to. To display a one-time success message, store it in a session variable, then test, display, and clear that session variable at the appropriate location in the html document.

When you output the html document, you would either test for a success message in the session variable and display it or test for user/validation errors in the array holding user/validation errors, and either display them all at once, or display them individually adjacent to the field they correspond to.

When you display or redisplay the edit/update form, you would populate the form field values, selected options, checked checkboxes, or checked radio buttons from the working array variable contents. Any value you output in a html context needs to have htmlentities() applied to it to help prevent cross site scripting.

You can achieve that with a single form! Here’s a simple walkthrough of what you want to accomplish:
Here is a simple demo

1. Database Connection

Set up a connection to your MySQL database using PHP’s mysqli extension.

2. Fetch Current Settings

Once connected, you can fetch the current settings from the database.

3. Display the Form with Current Settings

With the current settings fetched, you can populate the form fields with these values.

4. Handle Form Submission

When the form is submitted, you can update the settings in the database.

Now here is all in a single code

<?php
$host = 'localhost';
$db   = 'my_database';
$user = 'my_user';
$pass = 'my_password';
$charset = 'utf8mb4';

$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

$userId = 1; // Assuming a user with ID = 1. Replace this as needed.

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["update"])) {
    $name = $_POST["name"];
    $email = $_POST["email"];

    $query = "UPDATE profiles SET name = ?, email = ? WHERE user_id = ?";
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param('ssi', $name, $email, $userId);
    $stmt->execute();
}

$query = "SELECT * FROM profiles WHERE user_id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $userId);
$stmt->execute();

$result = $stmt->get_result();
$currentSettings = $result->fetch_assoc();
?>

<form method="post">
    Name: <input type="text" name="name" value="<?= $currentSettings['name'] ?>"><br>
    Email: <input type="email" name="email" value="<?= $currentSettings['email'] ?>"><br>
    <input type="submit" name="update" value="Update">
</form>

You can expand upon this basic structure to include more fields, more validation, error handling, and other enhancements. Remember to keep security in mind, especially when dealing with user input and database operations. Using prepared statements, as shown in the examples, helps protect against SQL injection attacks.

Good Luck.

Why mysqli and not PDO? I haven’t done much with mysqli, but it seems that there are additional steps involved in using it compared to PDO. Compare your mysqli:

$query = "SELECT * FROM profiles WHERE user_id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $userId);
$stmt->execute();
$result = $stmt->get_result();
$currentSettings = $result->fetch_assoc();

with the same in PDO:

$query = "SELECT * FROM profiles WHERE user_id = ?";
$stmt = $PDO->prepare($query);
$stmt->execute([$userId]);
$currentSettings = $stmt->fetch(PDO::FETCH_ASSOC);

Thanks, I’ll try it.

I am getting the following error:
Warning : Undefined variable $mysqli in /home/ka3pmw/public_html/temp/register/profile.php on line 11

Fatal error : Uncaught Error: Call to a member function prepare() on null in /home/ka3pmw/public_html/temp/register/profile.php:11 Stack trace: #0 {main} thrown in /home/ka3pmw/public_html/temp/register/profile.php on line 11

Have you successfully connected to the database, and did you call your database connection $mysqli or something else? Are you using the mysqli code that @anon321 provided, or the PDO code that I provided? If none of that helps, perhaps you could post your code so someone can see what the issue is.

I am now getting:
Warning : Undefined variable $PDO in /home/ka3pmw/public_html/temp/register/profile.php on line 24

Fatal error : Uncaught Error: Call to a member function prepare() on null in /home/ka3pmw/public_html/temp/register/profile.php:24 Stack trace: #0 {main} thrown in /home/ka3pmw/public_html/temp/register/profile.php on line 24

Here is my code:

<?php require_once('Connections/connections.php'); ?>
<?php
  // Start the session<br />
  session_start();
  $name = $_SESSION['name'];
  $mysqli = new mysqli($hostname_connections, $username_connections, $password_connections, $database_connections);
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}
  ?>

<?php

$query = "SELECT * FROM users WHERE username = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $name);
$stmt->execute();
$result = $stmt->get_result();
$currentSettings = $result->fetch_assoc();
 ?>

<?php
$query = "SELECT * FROM users WHERE name = ?";
$stmt = $PDO->prepare($query);
$stmt->execute([$userId]);
$currentSettings = $stmt->fetch(PDO::FETCH_ASSOC);
 ?>
<!DOCTYPE html>
<div class="container">
    <h1>Profile Page</h1>
    <div class="card">
        <div class="card-body">
            <div id="error-msg" class="alert alert-danger" role="alert"></div>
            <form id="profile-form"  method="post" name="login-form">
                <div class="mb-3">
                    <label for="name">Name</label>
                    <input id="name" class="form-control" name="name" type="name" placeholder="Enter name"></div>
                <div class="mb-3">
                    <label for="age">Age</label>
                    <input id="age" class="form-control" name="age" type="age" placeholder="age">
                </div>
                <div class="mb-3">
                    <label for="contact">Contact</label>
                    <input id="contact" class="form-control" name="contact" type="contact" placeholder="contact">
                </div>
                <button id="update" class="btn btn-primary" type="submit">update</button>
            </form>
        </div>
    </div>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="/js/profile.js"></script>

You seem to be running the query twice, once in mysqli and once in PDO. As you’re connecting to the database using mysqli, there’s no point adding in the PDO code as well. If you wanted to switch to using PDO instead of mysqli, then the database connection you make is different.

(Edited as I hadn’t read the code properly before my initial reply, sorry).

I fixed that. Now it is not updating the record in users.

OK, if you want to post the current code for that someone will help figure out why not.

Thanks, it is fixed. I forgot to post that.

Drummin is helping me.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.