简体   繁体   English

在class.php和db.php中的PDO插入函数中形成表单数组

[英]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. 我想知道在将表单提交给POST值并使用PDO插入函数将值输入数据库时​​是否可以帮助我解决问题。 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. 我已经检查了我的$ conn PDO语句,它正确连接到数据库,只是我无法从表单中插入数据。

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. 我的编码布局:表单位于cust_form.php中,表单字段的名称与数据库中的相同,但插入时生成的autoID除外。 Class.php is used to take POST values and to send to Insert function located in db.php. Class.php用于获取POST值并将其发送到位于db.php中的Insert函数。

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 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 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). load.php包含require_once db.php,class.php和config.php(包含用户名和密码)。 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. PS:避免在不使用bindParam的情况下使用准备执行SQL语句,因为您必须引号而不是整数或浮点数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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