简体   繁体   中英

Form post array to class.php and PDO insert function in db.php

I was wondering if you could help me with a problem when submitting a form to POST values and using a PDO Insert function to enter values into database. Once someone can help me find the issue I will be able to use code over again in form areas. I have checked my $conn PDO statement and it is connected correctly to database just I can not insert the data from form.

My coding layout: Form located in cust_form.php, names of form fields are as in database with the exception of an autoID generated upon insertion. Class.php is used to take POST values and to send to Insert function located in db.php.

db.php

<?php
//dbdt database class
if(!class_exists('dbdt')){
    class dbdt {

        //Connect and select database

        function connect() {
            try {
                require_once('config.php');
                    $conn = new PDO('mysql:host=localhost;dbname=displaytrends', $DB_USER, $DB_PASS);
                    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                } catch(PDOException $e) {
                    echo 'ERROR: ' . $e->getMessage();
                }
        }

        //Connect to above
        function __construct() {
            $this->connect();
        }


        //Insert data into database

        function insert($conn, $table, $fields, $values) {
            try{
                $fields = implode(", ", $fields);
                $values = implode(", ", $values);

                $insert = "INSERT INTO $table (autoID, $fields) VALUES ('', $values)";
                $query = $handler->prepare($insert);
                $query->execute();
            } catch(PDOException $e) {
                    echo 'ERROR: ' . $e->getMessage();
                }   
        }

    }
}

$dbdt = new dbdt;
?>

class.php

<?php
if(!class_exists('cust_form')){
    class cust_form {

/*
CUSTOMER FORM = cust_form.php
*/

    function cust_upd_cre_del(){

        if ( isset( $_POST['cust_upd'] ) ) {
                $int_custID=$_POST['int_custID'];
                $cust_company=$_POST['cust_company'];
                $cust_address=$_POST['cust_address'];
                $cust_postcode=$_POST['cust_postcode'];
                $cust_contact_1=$_POST['cust_contact_1'];
                $cust_contact_2=$_POST['cust_contact_2'];
                $cust_tel=$_POST['cust_tel'];
                $cust_mob=$_POST['cust_mob'];
                $cust_DDI=$_POST['cust_DDI'];
                $cust_email=$_POST['cust_email'];
                $cust_notes=$_POST['cust_notes'];
            require_once('db.php');
            $table = 'customers';
            $fields = array(
            'int_custID', 
            'cust_company', 
            'cust_address', 
            'cust_postcode', 
            'cust_contact_1', 
            'cust_contact_2', 
            'cust_tel', 
            'cust_mob', 
            'cust_DDI',
            'cust_email',
            'cust_notes'
            );
            $values = array (
                'int_custID' => $int_custID, 
                'cust_company' => $cust_company, 
                'cust_address' => $cust_address, 
                'cust_postcode' => $cust_postcode, 
                'cust_contact_1' => $cust_contact_1, 
                'cust_contact_2' => $cust_contact_2, 
                'cust_tel' => $cust_tel, 
                'cust_mob' => $cust_mob, 
                'cust_DDI' => $cust_DDI,
                'cust_email' => $cust_email,
                'cust_notes' => $cust_notes
            );
        $insert = $dbdt->insert($conn, $table, $fields, $values);

        if ( $insert == TRUE ) {
                    }
                } else {
                    die('Your form was not submitted.');
                }
        }
    }
}
$cust_form = new cust_form;
?>

cust_form.php

<!doctype html>
<?php
    require_once('load.php');
?>
<html>
<head>
<meta charset="UTF-8">
<title>Customer Form</title>
</head>

<body>
        <form action="" method="POST" name="cust_details_form" id="cust_details_form">   
           <label>Account No:</label>
           <input type="text" name="int_custID" id="int_custID" />
           <label>Company:</label>
           <input type="text" name="cust_company" id="cust_company"/>
            <label>Address:</label>
            <textarea type="text" rows=5 name="cust_address" id="cust_address"></textarea>
            <label>Postcode:</label>
            <input type="text" name="cust_postcode" id="cust_postcode"/>
            <label>Contact 1:</label>
            <input type="text" name="cust_contact_1" id="cust_contact_1"/>
            <label>Contact 2:</label>
            <input type="text" name="cust_contact_2"  id="cust_contact_2"/>
            <label>Telephone:</label>
            <input type="text" name="cust_tel" id="cust_tel"/>
            <label>Mobile:</label>
            <input type="text" name="cust_mob" id="cust_mob"/>
            <label>DDI:</label>
            <input type="text" name="cust_DDI" id="cust_DDI"/>
            <label>Email:</label>
            <input type="email" name="cust_email" id="cust_email"/>
            <label>Notes:</label>
            <textarea type="text" rows=5 colums=1 name="cust_notes" id="cust_notes"></textarea>

           <input type="submit" name="cust_upd" id="cust_upd" value="Update">
           <input type="submit" name="cust_del" id="cust_del" value="Delete">
        </form>
</body>
</html>

load.php contains require_once db.php, class.php & config.php (contains username and password). This file is okay.

Thanks for any help you may be able to give!

EDITTED Thanks for all your help! Here is the working code for anyone who needs it!

function ins_upd($table, $values) {
            try{
                include('config.php');
                $conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', $DB_USER, $DB_PASS);
                $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                //Strip $_POST array to fields with values  
                $values=array_filter($values);
                //Take array keys from array
                $field_keys=array_keys($values);
                //Implode for insert fields
                $ins_fields=implode(",", $field_keys);
                //Implode for insert value fields (values will binded later)
                $value_fields=":" . implode(", :", $field_keys);
                //Create update fields for each array create value = 'value = :value'.
                $update_fields=array_keys($values);
                foreach($update_fields as &$val){
                    $val=$val." = :".$val;
                }
                $update_fields=implode(", ", $update_fields);
                //SQL Query
                $insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
                $query = $conn->prepare($insert);
                //Bind each value based on value coming in.
                foreach ($values as $key => &$value) {
                    switch(gettype($value)) {
                        case 'integer':
                        case 'double':
                        $query->bindParam(':' . $key, $value, PDO::PARAM_INT);
                        break;
                        default:
                        $query->bindParam(':' . $key, $value, PDO::PARAM_STR);
                    }
                }
                $query->execute();
            } catch(PDOException $e) {
                echo 'ERROR: ' . $e->getMessage();
            }   
        }

You don't need to send "fields" parameters because if that array is in a different order than "values" your code won't work. Use the array keys from "values":

//Insert data into database

function insert($conn, $table, $values) {
    try {
        $keys = array_keys($values);
        $fields = implode(", ", $keys);
        $values = ":" . implode(", :", $keys);
        $insert = "INSERT INTO $table ($fields) VALUES ($values)";
        $query = $handler->prepare($insert);
        foreach ($values as $key => &$value) {
            switch(gettype($value)) {
            case 'integer':
            case 'double':
                $query->bindParam(':' . $key, $value, PDO::PARAM_INT);
                break;
            default:
                $query->bindParam(':' . $key, $value, PDO::PARAM_STR);
            }
        }
        $query->execute();
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
}

Hope it helps. I couldn't test it without complete code.

PS: Avoid using prepare to execute SQL statements without using bindParam because you must to quote strings but not integers or floating point numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM