• Log in or sign up for an account here: https://www.sythe.org/login

PHP advanced form update with intuitive variables and photos

Poxs

Forum Addict

$5 USD Donor New
Joined
Jul 4, 2013
Sythe Gold
19
Messages
277
Location
Costa Rica
Two Factor Authentication User
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($field, 0, 5) == '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_id) wrongID();
                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($field, 5);
   
        $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_result, 0);
        $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($field, 5);
   
        $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_name, PATHINFO_FILENAME), 0, 15)
            ) . '_' . substr(md5(rand()), 0, 6) . '.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_name, PATHINFO_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_reso, 0, 0, 0, 0,
            $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_url) unlink($_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:
Two Factor Authentication User
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.
 
Two Factor Authentication User
Examples of this working:

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


Main view
221678b55d995336285816ee2ec77a5f.png


Selected an id and got the current value of that field on an enum type:
a34d8494b92c9d7e98f4290067e66128.png

Text type:
e9db9ffa16bfe47d2206a64058a3b929.png

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)
b516f39d27bc4a63b6b022632c301047.png


Example changing the current value:
0cef8b35ed52f1f75909cedcdd9907f2.png
 
Last edited:
Clefairy
Supporting Business
Discord Voice
Jigglypuff
Hell yeah boooi
Poképedia
Who did this to my freakin' car!
Dat Boi
Dolan Duck
Dolan Trump
I'm LAAAAAAAME
Live Free or Die
Mew
Mewtwo
Poké Prizebox
Rust Player
Sythe Awards 2016 Winner
Sythe Awards 2017 Winner
Sythe Awards 2019 Winner
Tier 3 Prizebox
Toast Wallet User
mysqli_escape_string is not secure unless you set and adhere to a charset on the connection

strongly advise using prepared statements instead
 
Two Factor Authentication User
mysqli_escape_string is not secure unless you set and adhere to a charset on the connection

strongly advise using prepared statements instead

I'll pass this on to my coder, thank you for pointing this out.
 
Two Factor Authentication User
Also if you're going to release code for others, you should include your db schema and setup instructions. Just a tip :)

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:
Personally I would put all your stuff in functions then out put the data as a variable not a echo.
 
Runescape Gamblingrunescape gambling
Back
Top