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

标签 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]:参数编号无效:未定义参数。

最佳答案

我简化了代码来说明如何创建动态 UPDATE 查询。这使用“惰性”绑定(bind)和常规占位符 ?

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

<?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 ) 

关于php - PDO:使用 foreach 和 $_POST 定义参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27702639/

相关文章:

javascript搜索框和编辑字体大小

javascript - Ajax - 为什么在 $.post() 中使用 JSON.parse(data) 和 dataType

php - 如何在 yii2 ActiveDataProvider 中使用 postgres 函数 string_agg()?

PHP DateInterval 创建瞬间(微秒或毫秒)间隔

jquery - 有什么方法可以将类添加到 JOOMLA PLUGIN

mysql 循环不工作

mysql - 最好是在 InnoDB 主键末尾插入,还是分散插入?

mysql "AND"日期时间列上的子句两次

php - 在 PHP 中调用另一个类中的一个类

PHP/PDO连接Mysql,但查询似乎没有执行