简体   繁体   English

需要帮助使用PDO插入MySQL数据库表

[英]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. 由于某种原因,我收到错误消息:查询失败:SQLSTATE [HY093]:无效的参数编号:参数未定义。

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. 我通过回显foreach循环的输出而遇到麻烦,并且它始终返回四个项目,我不确定未定义哪个参数。 I have also played around with including the field names in the $sql string as well as not including them. 我还尝试过在$ sql字符串中包括字段名称,以及不包括它们。 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. 在这里,您将所有列添加到SQL语句中,但是稍后您仅添加提交表单时发送的值。 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. 然后只绑定:id:value1 ,使MySQL对:value2应该是什么感到困惑。

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

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