PHP advanced form update with intuitive variables and photos

Discussion in 'Web Programming' started by Poxs, Jul 19, 2016.

PHP advanced form update with intuitive variables and photos
  1. Unread #1 - Jul 19, 2016 at 1:26 PM
  2. Poxs
    Joined:
    Jul 4, 2013
    Posts:
    277
    Referrals:
    1
    Sythe Gold:
    19
    Two Factor Authentication User

    Poxs Forum Addict
    $5 USD Donor New

    PHP advanced form update with intuitive variables and photos

    Some code we recently developed, feel free to use and implement into your own websites.

    This code allows you to modify information, drop downs, and text fields all within the same page without having to refresh, make multiple pages, etc.

    This code was developed by James Wesley Productions, if you need any help understanding our code feel free to ask.

    To use this code I'm asuming you already have basic knowledge in html and php coding
    Feel free to ask if you need any help.

    Very intuitive to use.

    This is the file structure I recommend setting up in your directory while using it.


    (document_root)/login/admin/
    (document_root)/images/uploaded/(name of your destination folder/
    (document_root)/login/admin/creds/


    File naming:
    -files under
    --(document_root)/login/admin/
    ---(name)modify.php
    ---(name)modify_query.php
    ---(name)modify_photos.php

    File naming:
    -files under
    --(document_root)/login/admin/creds *this is where you're going to define your connection to the database
    ---sqlcreds(name).php




    CODE:
    (name)modify.php
    NOTE: this is your name html page, define a form to submit the information.

    Implement this form into your page, assign option values and tables according to the fields in your database:
    ***FIELD NAMES WITHIN THE FORM I POSTED ARE EXAMPLE, NAME IT ACCORDING TO YOUR DATABASE FIELDS****


    HTML:
    <form action="/login/admin/(name)modify.php" method="post" enctype="multipart/form-data">
    <fieldset>
    
    
    
    <input type="text" name="id" id="id" placeholder="Enter an existing ID *">
    
    
    <select id="type" name="type">01
    
    
      <option value="type">Type</option>
      <option value="name">Name</option>
      <option value="featured">Featured</option>
      <option value="desc_short">Short description</option>
      <option value="desc_long">Long Description</option>
      <option value="tours_qty">Quantity of tours</option>
      <option value="duration">Duration</option>
      <option value="included">Included</option>
      <option value="bring">Bring</option>
      <option value="paypal">Paypal button link</option>
      <option value="shop">Shop button link</option>
      <option value="photo1">Photo #1</option>
      <option value="photo2">Photo #2</option>
      <option value="photo3">Photo #3</option>
      <option value="photo4">Photo #4</option>
    </select>
    <?php include('./(name)modify_query.php'); ?>
    
    
    <input type="submit" value="Get current value" name = "update_retrieve"/>
    
    
    <input type="submit" value="Set new value" name = "update_replace"/>
    </form>




    (name)modify_query.php



    PHP:
    <?php
        $record_id 
    = @$_POST['id'];
        
    $field = @$_POST['type'];

        if(
    $record_id && $field) {
            if(!
    ctype_digit($record_id)) {
                echo 
    "ID must be a number.<br/>\n";
                return;
            }
       
            echo 
    "\n<script type='text/javascript'>\n"
                
    "$('#id').val('" $record_id "');\n"
                
    "$('#type').val('" $field "');\n"
                
    "</script>\n";
       
            include 
    './creds/sqlcreds(name).php';
       
            
    $sql_conn mysqli_connect('localhost'$sql_u$sql_p$sql_db);
            if(!
    $sql_conn) {
                echo 
    "MySQL connection failed: " mysqli_connect_error();
                return;
            }
       
            if(
    substr($field05) == 'photo') {
                include(
    './(name)modify_photo.php');
                
    mysqli_close($sql_conn);
                return;
            }
       
            if(@
    $_POST['update_retrieve']) {
                
    $sql_query 'SELECT ' $field ' FROM table_name WHERE id = '
                    
    mysqli_escape_string($sql_conn$record_id);
           
                
    $sql_result mysqli_query($sql_conn$sql_query);
                if(!
    $sql_result) {
                    echo 
    'SQL query failed: ' mysqli_error($sql_conn);
                    return;
                }
           
                
    $field_value mysqli_fetch_assoc($sql_result)[$field];
           
                if(
    $field_value) {

                if(
    $field_value) {  //assign all enum fields
                    
    echo 'Current value: <i>' ucfirst($field_value) . "</i><br/><br/>\n";
                    switch(
    $field) {
                        case 
    'type':
                            
    $select_items = array('budget''economy''standard',
                                
    'luxury''other');
                            break;
                        case 
    'featured':
                            
    $select_items = array('no''yes');
                            break;
                        case 
    'tours_qty':
                            
    $select_items = array();
                            for(
    $i=1$i <= 9$i++) {
                                
    array_push($select_items$i);
                            }
                            break;
                    }
                    if(@
    $select_items) {
                        echo 
    'New value: <select name="new_value" id="new_value">' "\n";
                        for(
    $i=0$i count($select_items); $i++) {
                            echo 
    '<option value="' $select_items[$i] . '">'
                                
    ucfirst($select_items[$i]) . "</option>\n";
                        }
                        echo 
    "</select>\n";
                    } else echo 
    '<textarea name="new_value" id="new_value" '
                        
    'placeholder="New value *"></textarea>' "\n";
                } else echo 
    "This ID does not exist.<br/><br/>\n";
            } elseif(@
    $_POST['update_replace']) {
                
    $field_value = @$_POST['new_value'];
                if(!
    $field_value) {
                    if(!
    $record_idwrongID();
                    else echo 
    "New value is empty. Get the current value first.<br/><br/>\n";
                    return;
                }
           
                
    $sql_query 'UPDATE table_name SET ' mysqli_escape_string($sql_conn$field)
                    . 
    " = '" mysqli_escape_string($sql_conn$field_value) . "' WHERE id = "
                    
    mysqli_escape_string($sql_conn$record_id);
           
                
    $sql_result mysqli_query($sql_conn$sql_query);
                if(!
    $sql_result) {
                    echo 
    'SQL query failed: ' mysqli_error($sql_conn);
                    return;
                }
           
                switch(
    $field) {   //asign all fields with long text
                    
    case 'desc_short'$field_cn 'Short description'; break;
                    case 
    'desc_long'$field_cn 'Long description'; break;
                    case 
    'tours_qty'$field_cn 'Quantity of tours'; break;
                    default: 
    $field_cn ucfirst($field);
                }
                echo 
    '<b>' $field_cn "</b> updated successfully.<br/><br/>\n";
            }

            
    mysqli_close($sql_conn);
        } elseif((!
    $record_id) && (@$_POST['update_retrieve'] || @$_POST['update_replace'])) {
            echo 
    "The <b>ID</b> field is empty.<br/><br/>\n";
        }
    ?>




    (name)modify_photo.php


    PHP:
    <?php
        
    if(@$_POST['update_retrieve']) {
            
    $sql_query 'SELECT id FROM table_name WHERE id = '
                
    mysqli_escape_string($sql_conn$record_id);
       
            if(!
    mysqli_num_rows(mysqli_query($sql_conn$sql_query))) {
                echo 
    "This ID does not exist.<br/><br/>\n";
                return;
            }
       
            
    $photo_n substr($field5);
       
            
    $sql_query 'SELECT ' mysqli_escape_string($sql_conn$field)
                . 
    '_url, title' mysqli_escape_string($sql_conn$photo_n)
                . 
    ' FROM table_name WHERE id = '
                
    mysqli_escape_string($sql_conn$record_id);
       
            
    $sql_result mysqli_query($sql_conn$sql_query);
       
            
    $url_value mysqli_fetch_assoc($sql_result)['photo' $photo_n '_url'];
       
            
    mysqli_data_seek($sql_result0);
            
    $photo_title mysqli_fetch_assoc($sql_result)['title' $photo_n];
       
            echo 
    'Current file: <i>' basename($url_value) . "</i><br/>\n"
                
    '<input type="file" name="' $field '" id="' $field '"/>'
                
    "<br/><br/>\n"
                
    'Current title: <i>' $photo_title "</i><br/>\n"
                
    '<input type="text" name="title' $photo_n
                
    '" placeholder="New title *"/>' "<br/><br/>\n";
        }
        elseif(@
    $_POST['update_replace']) {
            
    $photo_new_name = @$_FILES[$field]['name'];
            if(!
    $photo_new_name) {
                echo 
    "No file uploaded.<br/><br/>\n";
                return;
            }
       
            
    $photo_n substr($field5);
       
            
    $photo_title = @$_POST['title' $photo_n];
            if(!
    $photo_title) {
                echo 
    "New title missing.<br/><br/>\n";
                return;
            }
       
            
    $img_dir '/images/uploaded/photodirectory'//replace photodirectory with the name of your desired photo folder
            
    $max_w 400;
            
    $max_h 300;
       
            do 
    $upload_path $img_dir '/'
                
    str_replace(array('/''.'), '',
                    
    mb_substr(pathinfo($photo_new_namePATHINFO_FILENAME), 015)
                ) . 
    '_' substr(md5(rand()), 06) . '.jpg';
            while(
    file_exists($_SERVER['DOCUMENT_ROOT'] . $upload_path));
       
            
    $photo_tmp $_FILES[$field]['tmp_name'];
            if(!
    $photo_tmp) {
                echo 
    'Failed to upload <i>' $photo_new_name "</i>.<br/>\n"
                    
    "Please check the file size.<br/><br/>\n";
                return;
            }
       
            list(
    $photo_new_w$photo_new_h) = getimagesize($photo_tmp);
            if(!
    $photo_new_w) {
                echo 
    'File <i>' $photo_new_name
                    
    "</i> is not a supported image.<br/><br/>\n";
                return;
            }
       
            
    $photo_new_ratio $photo_new_w $photo_new_h;
       
            if(
    $max_w $max_h $photo_new_ratio) {
                
    $photo_w $max_h $photo_new_ratio;
                
    $photo_h $max_h;
            } else {
                
    $photo_h $max_w $photo_new_ratio;
                
    $photo_w $max_w;
            }
       
            
    $photo_reso imagecreatetruecolor($photo_w$photo_h);
       
            
    $photo_new_ext pathinfo($photo_new_namePATHINFO_EXTENSION);
            switch(
    $photo_new_ext) {
                case 
    'jpeg':
                case 
    'jpg':
                    
    $photo_new_reso imagecreatefromjpeg($photo_tmp); break;
                case 
    'png'$photo_new_reso imagecreatefrompng($photo_tmp); break;
                case 
    'gif'$photo_new_reso imagecreatefromgif($photo_tmp); break;
                case 
    'bmp'$photo_new_reso imagecreatefrombmp($photo_tmp); break;
                default:
                    echo 
    'Unrecognized extension (<i>' $photo_new_ext
                        
    "</i><br/><br/>\n";
                    return;
            }
       
            
    $photo_ok imagecopyresampled(
                
    $photo_reso$photo_new_reso0000,
                
    $photo_w$photo_h$photo_new_w$photo_new_h
            
    );
            if(!
    $photo_ok) {
                echo 
    'Failed to resample <i>' $photo_new_name
                    
    "</i>.<br/><br/>\n";
                return;
            }
       
            if(!
    imagejpeg($photo_reso$_SERVER['DOCUMENT_ROOT'] . $upload_path)) {
                echo 
    "Failed to save converted image.<br/><br/>\n";
                return;
            }
       
            
    $sql_query 'SELECT ' mysqli_escape_string($sql_conn$field)
                . 
    '_url FROM table_name WHERE id = '
                
    mysqli_escape_string($sql_conn$record_id);
       
            
    $photo_old_url mysqli_fetch_assoc(
                    
    mysqli_query($sql_conn$sql_query)
                )[
    'photo' $photo_n '_url'];
            if(
    $photo_old_urlunlink($_SERVER['DOCUMENT_ROOT'] . $photo_old_url);
       
            
    $sql_query 'UPDATE table_name SET '
                
    mysqli_escape_string($sql_conn$field '_url')
                . 
    " = '" mysqli_escape_string($sql_conn$upload_path)
                . 
    "', title" mysqli_escape_string($sql_conn$photo_n) . " = '"
                
    mysqli_escape_string($sql_conn$photo_title)
                . 
    "' WHERE id = " mysqli_escape_string($sql_conn$record_id);
       
            
    $sql_result mysqli_query($sql_conn$sql_query);
            if(!
    $sql_result) {
                echo 
    'SQL query failed: ' mysqli_error($sql_conn);
                return;
            }
       
            if(
    $photo_old_url) {
                echo 
    'Successfully replaced photo #' $photo_n ' with <i>'
                    
    $photo_new_name "</i>.<br/><br/>\n";
            } else {
                echo 
    'Successfully added <i>' $photo_new_name '</i> as photo #'
                    
    $photo_n ".<br/><br/>\n";
            }
        }
    ?>


    sqlcreds(name).php


    PHP:
    <?php
        $sql_u 
    'user';
        
    $sql_p 'password';
        
    $sql_db 'databasename';
        
    $sql_table 'tablename';
    ?>
     
    Last edited: Jul 19, 2016
  3. Unread #2 - Jul 19, 2016 at 1:28 PM
  4. Poxs
    Joined:
    Jul 4, 2013
    Posts:
    277
    Referrals:
    1
    Sythe Gold:
    19
    Two Factor Authentication User

    Poxs Forum Addict
    $5 USD Donor New

    PHP advanced form update with intuitive variables and photos

    All 4 of these files are requiered for this to work.

    the main html page must be a .php
    I recommend naming it (name)modify.php


    any places where table_name is mentioned should be the name of your table.
     
  5. Unread #3 - Jul 19, 2016 at 1:35 PM
  6. Poxs
    Joined:
    Jul 4, 2013
    Posts:
    277
    Referrals:
    1
    Sythe Gold:
    19
    Two Factor Authentication User

    Poxs Forum Addict
    $5 USD Donor New

    PHP advanced form update with intuitive variables and photos

    Examples of this working:

    Ignore the icons, i just put something together to show the example


    Main view
    [​IMG]


    Selected an id and got the current value of that field on an enum type:
    [​IMG]

    Text type:
    [​IMG]

    image type: (name generated by uploaded image collects the 15 first digits of the file name, and adds 5 random characters to the name, you'll never have an issue with file overwriting, and when an image is replaced using the modify the old picture is deleted)
    [​IMG]


    Example changing the current value:
    [​IMG]
     
    Last edited: Jul 19, 2016
  7. Unread #4 - Jul 20, 2016 at 9:31 PM
  8. Sythe
    Joined:
    Apr 21, 2005
    Posts:
    8,071
    Referrals:
    465
    Sythe Gold:
    5,271
    Discord Unique ID:
    742989175824842802
    Discord Username:
    Sythe
    Dolan Duck Dolan Trump Supporting Business ???
    Poképedia
    Clefairy Jigglypuff
    Who did this to my freakin' car!
    Hell yeah boooi
    Tier 3 Prizebox Toast Wallet User
    I'm LAAAAAAAME Rust Player Mewtwo Mew Live Free or Die Poké Prizebox (42) Dat Boi

    Sythe Join our discord

    test

    Administrator Village Drunk

    PHP advanced form update with intuitive variables and photos

    mysqli_escape_string is not secure unless you set and adhere to a charset on the connection

    strongly advise using prepared statements instead
     
    ^ Poxs likes this.
  9. Unread #5 - Jul 20, 2016 at 10:07 PM
  10. Poxs
    Joined:
    Jul 4, 2013
    Posts:
    277
    Referrals:
    1
    Sythe Gold:
    19
    Two Factor Authentication User

    Poxs Forum Addict
    $5 USD Donor New

    PHP advanced form update with intuitive variables and photos

    I'll pass this on to my coder, thank you for pointing this out.
     
  11. Unread #6 - Jul 20, 2016 at 10:31 PM
  12. Sythe
    Joined:
    Apr 21, 2005
    Posts:
    8,071
    Referrals:
    465
    Sythe Gold:
    5,271
    Discord Unique ID:
    742989175824842802
    Discord Username:
    Sythe
    Dolan Duck Dolan Trump Supporting Business ???
    Poképedia
    Clefairy Jigglypuff
    Who did this to my freakin' car!
    Hell yeah boooi
    Tier 3 Prizebox Toast Wallet User
    I'm LAAAAAAAME Rust Player Mewtwo Mew Live Free or Die Poké Prizebox (42) Dat Boi

    Sythe Join our discord

    test

    Administrator Village Drunk

    PHP advanced form update with intuitive variables and photos

    Also if you're going to release code for others, you should include your db schema and setup instructions. Just a tip :)
     
    ^ Poxs likes this.
  13. Unread #7 - Jul 20, 2016 at 11:42 PM
  14. Poxs
    Joined:
    Jul 4, 2013
    Posts:
    277
    Referrals:
    1
    Sythe Gold:
    19
    Two Factor Authentication User

    Poxs Forum Addict
    $5 USD Donor New

    PHP advanced form update with intuitive variables and photos

    db schematic not necesary, the fields I entered are simply an example.

    The values shown in the example are simply for example purposes.
    All that needs to be done is define the table name on the credentials file, and replace the sections table_name on the .php files with your table name.

    Field values are assigned in the modify_query.php file under each case as shown on this section:
    PHP:
    if($field_value) {  //assign all enum fields
                    
    echo 'Current value: <i>' ucfirst($field_value) . "</i><br/><br/>\n";
                    switch(
    $field) {
                        case 
    'type':
                            
    $select_items = array('budget''economy''standard',
                                
    'luxury''other');
                            break;
                        case 
    'featured':
                            
    $select_items = array('no''yes');
                            break;
                        case 
    'tours_qty':
                            
    $select_items = array();
                            for(
    $i=1$i <= 9$i++) {
                                
    array_push($select_items$i);
                            }
                            break;
                    }

    One thing I did not point out, that I will also clarify in the changelog:
    As mentioned the above section is for an enum field. The case 'field_name' is the name of the field. and the $select_items=array(option1,option2) is the values within the enum.

    I'll make a change log that simplifies the process of implementing the code, some time tomorrow. Reading over it is quite hard to understand. I really appreciate the feedback.
     
    Last edited: Jul 20, 2016
  15. Unread #8 - Jul 21, 2017 at 6:09 PM
  16. Viral_
    Joined:
    Jul 21, 2017
    Posts:
    2,483
    Referrals:
    1
    Sythe Gold:
    3,211
    Discord Unique ID:
    827322595988865025

    Viral_ Grand Master

    PHP advanced form update with intuitive variables and photos

    Personally I would put all your stuff in functions then out put the data as a variable not a echo.
     
< Looking for a web developer | Seeking Help On App Programming >

Users viewing this thread
1 guest


 
 
Adblock breaks this site