I have some data in a MySQL table, and I want to use them to populate form fields, so the site's admin can edit them. This is what I have so far in modify.php, but it's not working:

<?php

    // configuration
    require("../../includes/config.php");


    // query users table to retrieve admin homepage's contents
    // $users = query("SELECT * FROM users WHERE id = ?");


    //Class import for image uploading
    //classes is the map where the class file is stored (one above the root)
    include ("../../classes/upload/upload_class.php");

    $id = $_GET["id"];
    $getuser = query("SELECT * FROM users WHERE id = '$id'");

    // associative array
    $rows = mysqli_fetch_array($getuser, MYSQLI_ASSOC);

    // if form was submitted, modify user
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {         
        if ($rows == true)
        {
        //This gets all the other information from the form
        $firstname = $_POST["firstname"];
        $lastname = $_POST["lastname"]; 
        $username = $_POST["username"]; 
        $usersex = $_POST["usersex"]; 
        $password = crypt($_POST["password"]);
        $email = $_POST["email"];
        $phone = $_POST["phone"];
        $userimage = ($_FILES["userimage"]["name"]);
        }

        // validate submission
        if (empty($_POST["firstname"]))
        {
            apologize("Provide your first name.");
        }
        if (empty($_POST["lastname"]))
        {
            apologize("Provide your last name.");
        }
        if (empty($_POST["username"]))
        {
            apologize("Provide a username.");
        }
        if (empty($_POST["usersex"]))
        {
            apologize("Select your sex.");
        }
        else if (empty($_POST["password"]))
        {
            apologize("Enter a password.");
        }
        else if (empty($_POST["confirmation"]))
        {
            apologize("Confirm your password.");
        }
        else if ($_POST["password"] != $_POST["confirmation"])
        {
            apologize("Password and confirmation do not match.");
        }
        if (empty($_POST["email"]))
        {
            apologize("Provide your email address.");
        }
        if (empty($_POST["phone"]))
        {
            apologize("Enter your phone number.");
        }

        //This is the directory where images will be saved 
        $max_size = 1024*250; // the max. size for uploading

        $my_upload = new file_upload;

        $my_upload->upload_dir = "../images/user/"; // "files" is the folder for the uploaded files (you have to create this folder)
        $my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here
        // $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
        $my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
        $my_upload->rename_file = true;

        $my_upload->the_temp_file = $_FILES['userimage']['tmp_name'];
        $my_upload->the_file = $_FILES['userimage']['name'];
        $my_upload->http_error = $_FILES['userimage']['error'];
        $my_upload->replace = "y";
        $my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename
        if ($my_upload->upload()) // new name is an additional filename information, use this to rename the uploaded file
        {

        if (!empty($_POST["username"]))
        { 
            // validate username
            $username = ($_POST["username"]);
            if (!preg_match("/^[a-zA-Z0-9]*$/", $username))
            {
                apologize("Username must contain only letters and numbers.");
            }
            if (strlen($username) < 4 || strlen($username) > 10)
            {
                apologize("Username must be from 4 to 10 characters.");
            }
            // validate email address
            $email = ($_POST["email"]);
            if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
            {
                apologize("Invalid email address.");
            }
            if ($_POST["email"] === false)
            {
                apologize("The email has already been taken.");
            }
            // Don't allow country codes to be included (assumes a leading "+") 
            if (preg_match('/^(\+)[\s]*(.*)$/',$phone))
            {
                apologize("You should not include the country code.");
            }
            // Remove hyphens - they are not part of a telephone number
            $phone = str_replace ('-', '', $phone);

            // Now check that all the characters are digits
            if (!preg_match('/^[0-9]{10,11}$/',$phone))
            {
                apologize("Phone number should be either 10 or 11 digits");
            }

            // Now check that the first digit is 0
            if (!preg_match('/^0[0-9]{9,10}$/',$phone))
            {
                apologize("The telephone number should start with a 0");
            }

            if ($_POST["phone"] === false)
            {
                apologize("The phone number is already in the database.");
            }
            // insert form input into database
            $result = query("UPDATE users (firstname, lastname, username, usersex, hash, email, phone, userimage) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            $_POST["firstname"],
            $_POST["lastname"],
            $_POST["username"],
            $_POST["usersex"],
            crypt($_POST["password"]),
            $_POST["email"],
            $_POST["phone"],
            $_FILES["userimage"]["name"], $_POST["id"]);

            // if username is in database
            if ($result === false)
            {
                apologize("Username has been taken");
            }

            // update users' DB table to reference the image's new file name
            query(sprintf("UPDATE users SET userimage = '%s'", $my_upload->file_copy));

            // find out user's ID
            $rows = query("SELECT LAST_INSERT_ID() AS id");
            $id = $rows[0]["id"];

            // redirect to portfolio
            redirect("list-users.php");
        }

        }
    }
    // render portfolio
    adminrender("modify-user_template.php", ["title" => "Admin - Modify User"]);

?>

The following is the modify-user_template.php:

<a href="index.php">Home</a> | <a href="myprofile.php">My Profile</a> | <a href="list-users.php">List Users</a> | <a href="add-user.php">Add User</a> | <a href="history.php">History</a> | <a href="resetpass.php">Modify Password</a> | <a href="logout.php">Sign Out</a>



<h1>Admin - Modify User</h1>

<?php



    $id = $_GET["id"];

    $getuser = query("SELECT * FROM users WHERE id = '$id'");



    // associative array

    while ($rows = mysqli_fetch_array($getuser, MYSQLI_ASSOC))

    {



    printf('<form enctype="multipart/form-data" action="add-user.php" method="post">');

    printf('<fieldset>');

        printf('<div class="form-group">');

            printf('<input autofocus class="form-control" name=" . $rows["firstname"] . placeholder="First Name" type="text"/>');

            printf('<input type="hidden" name=" . $rows["id"] . id="id"/>');

        printf('</div>');

        printf('<div class="form-group">');

            printf('<input autofocus class="form-control" name="lastname" placeholder="Last Name" type="text"/>');

        printf('</div>');

        printf('<div class="form-group">');

            printf('<input autofocus class="form-control" name="username" placeholder="Username" type="text"/>');

        printf('</div>');

        printf('<div class="form-group">');

            printf('<select autofocus class="form-control" name="usersex" value="usersex">');

                printf('<option value="Male" selected="selected">Male</option>');

                printf('<option value="Female">Female</option>');

            printf('</select>');

        printf('</div>');

        printf('<div class="form-group">');

            printf('<input class="form-control" name="password" placeholder="Password" type="password"/>');

        printf('</div>');

        printf('<div class="form-group">');

            printf('<input class="form-control" name="confirmation" placeholder="Confirm Password" type="password"/>');

        printf('</div>');

        printf('<div class="form-group">');

            printf('<input autofocus class="form-control" name="email" placeholder="Email" type="text"/>');

        printf('</div>');

        printf('<div class="form-group">');

            printf('<input autofocus class="form-control" name="phone" placeholder="Phone" type="text"/>');

        printf('</div>');

        printf('<div class="form-group">');

            printf('<input autofocus class="form-control" name="userimage" id="fileimage" placeholder="Your Photo" type="file"/>');

        printf('</div>');

        printf('<div class="form-group">');

            printf('<button type="submit" class="btn btn-default" name="Register" value="Register">Register</button>');

        printf('</div>');

    printf('</fieldset>');

    printf('</form>');



}



?>



<div>

</div>

<br/>

Please, I need all your help. Thanks in advance.

@pritaeas,
Thanks for replying. I need the form fields to populate with data from database table named "users". But unfortunately, they're not populated when the page (modify-user.php) loads.

Check if:

$getuser = query("SELECT * FROM users WHERE id = '$id'");

is throwing an error, and $id has a proper value.

I'm aware there's an error, but I don't know how to fix it. Actually, I have another page named "list-users.php. On this page, all the users are properly listed with each user ID hyperlinked. On clicking a user's hyperlinked ID takes the admin to "modify-user.php".

Any idea how to fix the issue?

Any idea how to fix the issue?

Debug. See where your code gets, and where it does not.

How do I debug? I haven't done that before.

How do I debug? I haven't done that before.

you can either use netbeans, eclicpse IDE's or PHP designer. Load your script and run debug.

Sorry, but I'm developing with an appliance, which is installed inside a virtual machine. My best bet would be if I can get help here.

can you at least give us which appliance you are currently using, so that we can let you know if debugging is possible? I know about 11 appliances and I don't know which one you are currently running in your development environment. There are virtualboximages, lampstack, OTRS appliance, ops view, open filer, and others.

There's always the old debugging style, where you put echo's all over your script to monitor flow and variables.

@veedeoo,
I'm using our company's custom-made appliance installed inside VMWare Player.

@pritaeas,
Your idea seems to help figure out the problem. Using printf, I noticed that selecting any user's ID prints out 0, regardless of whether I select modify-user.php?id=1 or modify-user.php?id=2. I guess getting the script to associate the selected ID with its curresponding user's row in the database would be key to solving the issue.

The following is how I queried the database to select a particular user's row:

$user = query("SELECT * FROM users WHERE id = ?");

Any idea on a better way to fix the bug?

The following is how I queried the database

How is the selected user's id attached to your query? Shouldn't that be a parameter in your query method? Is the right id passed?

Honestly, I don't know how to pass a user's ID as a parameter to the query. Can you help, please?

I've unsuccessfully tried a couple of things like this:

$id = $_GET["id"];
$user = query("SELECT * FROM users WHERE id = '$id'");

That prints out:

 Array ( [id] => 5 )

The printed number (5) corresponds to the exact user's ID I selected.

The query:

$id = $_GET["id"];
$user = query("SELECT * FROM users WHERE id = '$id'");

Sorry, I posted MySQL select query, instead of the query function. Here it is and it works well:

    function query(/* $sql [, ... ] */)

    {

        // SQL statement

        $sql = func_get_arg(0);



        // parameters, if any

        $parameters = array_slice(func_get_args(), 1);



        // try to connect to database

        static $handle;

        if (!isset($handle))

        {

            try

            {

                // connect to database

                $handle = new PDO("mysql:dbname=" . DB_NAME . ";host=" . DB_SERVER, DB_USERNAME, DB_PASSWORD);



                // ensure that PDO::prepare returns false when passed invalid SQL

                $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 

            }

            catch (Exception $e)

            {

                // trigger (big, orange) error

                trigger_error($e->getMessage(), E_USER_ERROR);

                exit;

            }

        }

I strongly believe the query function works like magic. My only problem here is aoto-populating form fields with database table data, so I can edit them.

If that is all there is, then it will never work. The query is never executed.

That's very surprising. before I've used that exact same function in another script to auto-populate a form input and edit it. The only difference was that in the previous case, I logged in as a regular user and was able to auto-populate my account and edit it. But in this case, I log in as the site's admin and I need to be able to auto-populate any user's account I select its ID and edit it.

Here is my functions.php inside which is the query function:

<?php



    /**

     * functions.php

     *

     * Ovi Charity

     *

     * Helper functions.

     */



    require_once("constants.php");



    /**

     * Apologizes to user with message.

     */

    function apologize($message)

    {

        render("apology.php", ["message" => $message]);

        exit;

    }



    /**

     * Apologizes to admin with message.

     */

    function adminapologize($message)

    {

        adminrender("apology.php", ["message" => $message]);

        exit;

    }



    /**

     * Facilitates debugging by dumping contents of variable

     * to browser.

     */

    function dump($variable)

    {

        require("../templates/dump.php");

        exit;

    }



    /**

     * Logs out current user, if any.  Based on Example #1 at

     * http://us.php.net/manual/en/function.session-destroy.php.

     */

    function logout()

    {

        // unset any session variables

        $_SESSION = [];



        // expire cookie

        if (!empty($_COOKIE[session_name()]))

        {

            setcookie(session_name(), "", time() - 42000);

        }



        // destroy session

        session_destroy();

    }



    /**

     * Executes SQL statement, possibly with parameters, returning

     * an array of all rows in result set or false on (non-fatal) error.

     */

    function query(/* $sql [, ... ] */)

    {

        // SQL statement

        $sql = func_get_arg(0);



        // parameters, if any

        $parameters = array_slice(func_get_args(), 1);



        // try to connect to database

        static $handle;

        if (!isset($handle))

        {

            try

            {

                // connect to database

                $handle = new PDO("mysql:dbname=" . DB_NAME . ";host=" . DB_SERVER, DB_USERNAME, DB_PASSWORD);



                // ensure that PDO::prepare returns false when passed invalid SQL

                $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 

            }

            catch (Exception $e)

            {

                // trigger (big, orange) error

                trigger_error($e->getMessage(), E_USER_ERROR);

                exit;

            }

        }



        // prepare SQL statement

        $statement = $handle->prepare($sql);

        if ($statement === false)

        {

            // trigger (big, orange) error

            trigger_error($handle->errorInfo()[2], E_USER_ERROR);

            exit;

        }



        // execute SQL statement

        $results = $statement->execute($parameters);



        // return result set's rows, if any

        if ($results !== false)

        {

            return $statement->fetchAll(PDO::FETCH_ASSOC);

        }

        else

        {

            return false;

        }

    }



    /**

     * Redirects user to destination, which can be

     * a URL or a relative path on the local host.

     *

     * Because this function outputs an HTTP header, it

     * must be called before caller outputs any HTML.

     */

    function redirect($destination)

    {

        // handle URL

        if (preg_match("/^https?:\/\//", $destination))

        {

            header("Location: " . $destination);

        }



        // handle absolute path

        else if (preg_match("/^\//", $destination))

        {

            $protocol = (isset($_SERVER["HTTPS"])) ? "https" : "http";

            $host = $_SERVER["HTTP_HOST"];

            header("Location: $protocol://$host$destination");

        }



        // handle relative path

        else

        {

            // adapted from http://www.php.net/header

            $protocol = (isset($_SERVER["HTTPS"])) ? "https" : "http";

            $host = $_SERVER["HTTP_HOST"];

            $path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\");

            header("Location: $protocol://$host$path/$destination");

        }



        // exit immediately since we're redirecting anyway

        exit;

    }



    /**

     * Renders template, passing in values.

     */

    function render($template, $values = [])

    {

        // if template exists, render it

        if (file_exists("../templates/$template"))

        {

            // extract variables into local scope

            extract($values);



            // render header

            require("../templates/header.php");



            // render template

            require("../templates/$template");



            // render footer

            require("../templates/footer.php");

        }



        // else err

        else

        {

            trigger_error("Invalid template: $template", E_USER_ERROR);

        }

    }



    /**

     * Renders admin template, passing in values.

     */

    function adminrender($template, $values = [])

    {

        // if template exists, render it

        if (file_exists("templates/$template"))

        {

            // extract variables into local scope

            extract($values);



            // render header

            require("templates/header.php");



            // render template

            require("templates/$template");



            // render footer

            require("templates/footer.php");

        }



        // else err

        else

        {

            trigger_error("Invalid template: $template", E_USER_ERROR);

        }

    }



?>

Ah. You didn't copy everything the first time... Anyway, should the query fail, then no error is triggered, it just returns false. So, start with checking that false is actually returned by your query.

I tried the following code, but the page simply went blank:

    if ($users = query("SELECT * FROM users WHERE id = '$id'") !== true)
    {
        return false;
    }
    else
        {
            print_r($_GET);
        }

I still haven't solved the issue. Can anyone help?

The data I want to display as the input values are firstname, lastname, username, usersex, password, email, phone and userimage. These are data of any registered user already in the database.

There is a web page called list-user.php that correctly lists all the registered users and their associated data in corresponding rows. And in each user's row, the user's ID is hyperlinked with this:

printf("<td class='listusers'><a href='modify-user.php?id=%d'>Modify</a></td>", $row['id']);

Clicking the "Modify" link of any ID on list-users.php takes the admin to modify-user.php. I want the selected user's data to auto-populate form inputs on modify-user.php, so the admin can edit them. But unfortunately, the form inputs are empty.

Any idea how to solve the issue?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.