简体   繁体   中英

Need help inserting into MySQL database table using PDO

The database table only contains the four fields that the query is attempting to insert into. For some reason I get the error: Query failed: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined.

I have troubleshot by echoing the output of the foreach loops and it always returns four items, I'm not sure what parameter isn't defined. I have also played around with including the field names in the $sql string as well as not including them. Same results either way. Please help if you can.

<?php
class DB {
        private $_conn;

        public function openDB() {
                $dsn = "mysql:host=localhost;dbname=news";
                $username = "root";
                $password = "password";

                try {
                        $this->_conn = new PDO( $dsn, $username, $password );
                        $this->_conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                } catch ( PDOException $e ) {
                        echo "Connection failed: " . $e->getMessage();
                }
        }

        public function closeDB() {
                $this->_conn = null;
        }

        public function selectData( $myQuery ) {
                $rows = $this->_conn->query( $myQuery );

                foreach ( $rows as $row ) {
                        echo "Index: " . $row['id'] . "<br />";
                        echo "Title: " . $row['title'] . "<br />";
                }
        }

        public function insertData( $tableName ) {

                $q = $this->_conn->prepare("DESCRIBE " . $tableName);
                $q->execute();
                $getFields = $q->fetchAll(PDO::FETCH_COLUMN);

                $dbFieldCount = count( $getFields );
                $implodedFields = implode( ", :", $getFields );

                //$sql = "INSERT INTO " . $tableName . " ( " . implode( ", ", $getFields ) . " ) VALUES ( :" . $implodedFields . " )";
                $sql = "INSERT INTO " . $tableName . " VALUES ( :" . $implodedFields . " )";
                echo "$sql<br />";

                try {
                        $insert = $this->_conn->prepare( $sql );

                        foreach ( $getFields as $dbKey => $dbValue ) {
                                foreach( $_POST as $formKey => $formValue ) {
                                        if ( $dbValue == 'id' ) {
                                                $insert->bindValue( '\":' . $dbValue . '\"', null, PDO::PARAM_INT );
                                                echo "$dbValue<br />";
                                                break;
                                        } else if ( is_int( $formValue ) && $dbValue == $formKey ) {
                                                $insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_INT );
                                                echo "$formValue<br />";
                                                break;
                                        } else if ( is_string( $formValue ) && $dbValue == $formKey ) {
                                                $insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_STR );
                                                echo "$formValue<br />";
                                                break;
                                        }
                                }
                        }

                        $insert->execute();
                } catch ( PDOException $e ) {
                        echo "Query failed: " . $e->getMessage();
                }
        }

}
?>
<!DOCTYPE html>
<html>
        <head>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                <title></title>
        </head>
        <body>
                <?php

                if ($_POST) {
                        $conn = new DB();
                        $conn->openDB();
                        $conn->insertData( 'login' );
                        $conn->closeDB();
                }

                ?>

                <form action="#" method="POST" name="register">
                        <label for="username">Username</label><br />
                        <input type="text" id="username" name="username"><br />
                        <label for="password">Password</label><br />
                        <input type="password" id="password" name="password"><br />
                        <label for="email">Email Address</label><br />
                        <input type="text" id="email" name="email"><br />
                        <input type="submit" value="Submit" />
                </form>

        </body>
</html>
$sql = "INSERT INTO " . $tableName . " VALUES ( :" . $implodedFields . " )";

Here you're adding all columns into your SQL statement, but later you only add values that are sent when the form is submitted. It's possible that you have columns in your database that aren't in the form, so you're coming up with a statement like:

INSERT INTO someTable VALUES (:id, :value1, :value2)

And then you only bind :id and :value1 , leaving MySQL confused about what :value2 is supposed to be.

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