MYSQL PHP更新,其中ID =:id

时间:2018-12-28 18:48:57

标签: php mysql

编辑:我几乎已经找到了解决方案,但是我还没有找到解决方案。我设置了$statement->bindValue(':ID', $row['ID']);,但是现在我要更新数据库中的所有行,而不是所选的一行。我知道这与foreach循环有关,但是现在我只需要更新一个选定的行。

当前,我在PDO中有一个MYSQL更新查询,当我指定 $ id 时,该查询运行得很好。但是,我想修改更新查询,以便 $ id 可以是表中的任何行。目前,当我设置 $ id ='132612'时,以下查询有效:

foreach ($result as $row)
{
    $eventprofileid = ''. $row['ID'] .'';
}

if (isset($_POST['verify'])) {

    $host = '';
    $user = '';
    $pass = '';
    $database = '';

    $options = array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false
    );

    $pdo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options);

    $sql = "UPDATE `EVENT_DATA` SET `finishReason` = :finishreason WHERE ID = :ID";
    $statement = $pdo->prepare($sql);

    $id = '132612'; // -----this is what I want to change to a variable, which is whatever $eventprofileid is equal to.
    $finishreason2 = '1';

    $statement->bindValue(':ID', $row['ID']); ---edited code, problem is now this updates all rows instead of one row.
    $statement->bindValue(':finishreason', $finishreason2);

    $update = $statement->execute();

}

<form action='' method='POST'>
<input type='submit' name='verify' value='Verify' />

现在,我该如何使用相同的查询,但是我没有指定 $ id ,而是将其设置为变量?我尝试了类似以下代码的操作,但未成功。我当然知道我在那里做错了,部分原因是对PDO越来越熟悉:

 $statement->bindValue(':ID', $row['ID']); --Problem is now this updates all rows instead of one.

1 个答案:

答案 0 :(得分:0)

这可能是一个远景,但是我认为您正在尝试多次执行一次准备好的语句,每次使用不同的id。

尝试用foreach循环替换execute

... your statement is prepared successfully 
foreach ($result as $row)
{
    $statement->bindValue(':ID', $id);
    $id = $row['ID']; // this is the bound parameter which will change on each loop iteration
    $update = $statement->execute();
}