Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    Sep 2008
    Location
    Mexabet.biz
    Posts
    89
    Thanks
    12
    Thanked 0 Times in 0 Posts

    How do I auto-populate form inputs with data in a MySQL table?

    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. But unfortunately, the form fields are not auto-populated, as desired. As follows is the modify-user.php:
    PHP Code:
    <?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"];
        
    $user query("SELECT * FROM users WHERE id = '$id'");
        
        
    // 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) < || 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"]);

    ?>
    As follows is the modify-user_template.php, which modify-user.php calls:
    Code:
    <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"];
    	$user = query("SELECT * FROM users WHERE id = '$id'");
    
    	
    
    	print_r($_GET);
    
    	
    
        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=" . $user["firstname"] . placeholder="First Name" type="text"/>');
    
                printf('<input type="hidden" name=" . $user["id"] . id="id"/>');
    
             printf('</div>');
    
            printf('<div class="form-group">');
    
                printf('<input autofocus class="form-control" name=" . $user["lastname"] . placeholder="Last Name" type="text"/>');
    
            printf('</div>');
    
            printf('<div class="form-group">');
    
                printf('<input autofocus class="form-control" name=" . $user["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/>
    Here is the functions.php that includes "query" function:
    PHP Code:
    <?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_SERVERDB_USERNAMEDB_PASSWORD);



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

                    
    $handle->setAttribute(PDO::ATTR_EMULATE_PREPARESfalse); 

                }

                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);

            }

        }



    ?>

  • #2
    Senior Coder
    Join Date
    Sep 2010
    Posts
    2,446
    Thanks
    17
    Thanked 273 Times in 273 Posts
    As part of the printf input statements you have to add, value="$variable" , where $variable is the appropriate value from the database. Then the correct entry should appear.
    Welcome to http://www.myphotowizard.net

    where you can edit images, make a photo calendar, add text to images, and do much more.


    When you know what you're doing it's called Engineering, when you don't know, it's called Research and Development. And you can always charge more for Research and Development.

  • #3
    New Coder
    Join Date
    Sep 2008
    Location
    Mexabet.biz
    Posts
    89
    Thanks
    12
    Thanked 0 Times in 0 Posts
    @DrDOS,
    Thanks for your reply. But how do I go about it precisely, bearing in mind the code I posted above. I'm not yet well experienced in PHP.

  • #4
    Senior Coder
    Join Date
    Sep 2010
    Posts
    2,446
    Thanks
    17
    Thanked 273 Times in 273 Posts
    I really can't tell you better than I have, since I don't know which items from the database you want to appear as input values, and for what inputs. Just try it for one input till you get it right, and you'll know.
    Welcome to http://www.myphotowizard.net

    where you can edit images, make a photo calendar, add text to images, and do much more.


    When you know what you're doing it's called Engineering, when you don't know, it's called Research and Development. And you can always charge more for Research and Development.

  • #5
    New Coder
    Join Date
    Sep 2008
    Location
    Mexabet.biz
    Posts
    89
    Thanks
    12
    Thanked 0 Times in 0 Posts
    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:
    PHP Code:
    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?


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •