简体   繁体   中英

PHP : INSERT PDO Query array as binding value

How to use PDO Query array with Bindvalue in this way? I get error

$productadd_query_array = array(
        "query" => "INSERT INTO vn_product (title) VALUES (:title)",
        "query_variables" => "bindValue(':title', '1')"
    );

$product_add = vn_db_query_select( $productadd_query_array );

Function vn_db_query_select:

function vn_db_query_select($array = null){

        if ( is_null( $array ) || !defined( 'MYSQL_USER' ) || !defined( 'MYSQL_PASSWORD' ) || !defined( 'MYSQL_HOST' ) || !defined( 'MYSQL_DATABASE' ) ) {
            return false;
        }

        if ( !isset( $array["query"] ) || is_null( $array["query"] ) || strlen( $array["query"] ) < 11 ) {
            return false;
        }

        $pdo = new PDO(
            "mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE.";charset=utf8", // DSN
            MYSQL_USER, // Username
            MYSQL_PASSWORD // Password
            //$pdoOptions // Options
        );

        $userInfo = $pdo->prepare($array["query"]); 

        if ( is_array( $array["query_variables"] ) ) {
            foreach ($array["query_variables"] as $var_name => $var_value) {
                $userInfo->bindValue(":".$var_name, $var_value);
            }
        }

        $userInfo->execute();
        $user = $userInfo->fetchAll();

        $pdo = null;

        return $user;
    }

If you look at the code for query_variables here:

if ( is_array( $array["query_variables"] ) ) {
      foreach ($array["query_variables"] as $var_name => $var_value) {
           $userInfo->bindValue(":".$var_name, $var_value);
    }
}

It's expecting an array of keys=>values. So you need to pass it in like this:

"query_variables" => ['title'=> '1']

Or for older versions of PHP:

"query_variables" => array('title'=>'1')

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