PDO:使用foreach和$ _POST定义参数

时间:2014-12-30 09:20:51

标签: php jquery mysql pdo

我正在尝试创建一个允许用户使用PDO在sql数据库中更改其信息的页面。我是新手,我遇到了一个错误。我使用它作为来源:http://forums.devshed.com/php-faqs-stickies-167/program-basic-secure-login-system-using-php-mysql-891201.html

我不确定我是否包含太多代码。我希望有人可以指出我犯了什么错误。

<?php
require("common.php");

Common运行此代码:

<?php
$username = "";
$password = "";
$host = "";
$dbname = "";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
    die("Failed to connect to the database: " . $ex->getMessage());
}

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

header('Content-Type: text/html; charset=utf-8');
session_start();

现在我创建初始查询和参数:

//initial query and params
    $query = "
        UPDATE users
        SET
        ";
    $query_params = array();
    $query_params[':user_id'] = $_SESSION['user']['id'];

现在我想使用参数数组(字段)

来定义参数
      $params = array(info1,info2,info3);
      foreach($params as $param):
        if(!empty($_POST[$param])){
          $query_params[':$param'] = $_POST[$param];
          $query .= "$param = :$param,";
        }       
      endforeach;

然后我完成查询并运行它:

    //trim last comma
    $query = rtrim($query, ',');
    $query .= "
        WHERE
            id = :user_id
    ";

    try
    {
        // Execute the query
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch(PDOException $ex)
    {
        die("Failed to run main query: " . $ex->getMessage() . "\n" . $query );
    }

这是我使用的HTML(带jquery):

<form method="post" action="edit_account.php" data-ajax="false">

<div class="ui-field-contain">
    <p>Gebruikersnaam: <b><?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?></b></p>
    <label for="email">E-mail:</label>
    <input autocomplete="off" type="text" name="email" id="email" value="<?php echo htmlentities($_SESSION['user']['email'], ENT_QUOTES, 'UTF-8'); ?>">
    <label for="password">Wachtwoord:</label>
    <input autocomplete="off" type="password" name="password" id="password" placeholder="(alleen als je deze wijzigt)">
  </div>

  <div class="ui-field-contain">
    <label for="info1">info1:</label>
    <input type="text" name="info1" id="info1" placeholder="<?php echo htmlentities($_SESSION['user']['info1'], ENT_QUOTES, 'UTF-8'); ?>">
  </div>

  <div class="ui-field-contain">
    <label for="info2">info2:</label>
    <textarea type="text" name="info2" id="info2" placeholder="<?php echo htmlentities($_SESSION['user']['info2'], ENT_QUOTES, 'UTF-8'); ?>"></textarea>
    <label for="info3">info3:</label>
    <input type="text" name="info3" id="info3" placeholder="<?php echo htmlentities($_SESSION['user']['info3'], ENT_QUOTES, 'UTF-8'); ?>">
    <label for="info4">info4:</label>
    <input type="text" name="info4" id="info4" placeholder="<?php echo htmlentities($_SESSION['user']['info4'], ENT_QUOTES, 'UTF-8'); ?>">
  </div>
</form>

我收到此错误:SQLSTATE [HY093]:参数号无效:参数未定义。

1 个答案:

答案 0 :(得分:0)

我简化了代码以说明如何创建动态UPDATE查询。这使用&#34;懒惰&#34;绑定和常规占位符?

文本输入设置为值的常规数组(即非关联)。

<?php
if(isset($_POST['submit'])){
    if (isset($_POST["info"]) && !empty($_POST["user_id"])) {
        $query = "UPDATE `users` SET ";
        $query_params = array();
        $i =1;
        foreach ($_POST['info'] as $value) {
            // push array with each valid info entry ...
            if ($value) {
                $query .= "`info".$i. "` = ?,"; 
                array_push($query_params,$value);
            }
            $i++;
        }
        $query = rtrim($query, ',');//remove trailing ,
        //  
        $query .= " WHERE `id` = ?"; 
        array_push($query_params,$_POST['user_id']);
        //Show query and parameter array Remove after testing
        echo $query;    
        echo "<br>";
        print_r($query_params);
        // Execute the query
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
}
?>
<form method="POST" action="#">
<input type="text" name="info[]" id="info" value=""> 
<input type="text" name="info[]" id="info"  value="">
<input type="text" name="info[]" id="info"  value="">
<input type="text" name="info[]" id="info" value="">
<input type="text" name="user_id" id="user_id" value="">
<input type="submit" name="submit" value="Submit">

典型结果

UPDATE `users` SET `info1` = ?,`info2` = ? WHERE `id` = ?
Array ( [0] => john [1] => smith [2] => johnsmith )