我想做的是更新 mysql 行(在本例中,仅用户名),就像 phpMyAdmin 处理它的方式(单击输入字段,更改值,按 Enter )。
据我所知,我的代码没有错误。提交后我也没有看到任何 php 错误。
这是主页的代码:
// Here, I select the rows I need to be displayed first.
<?php $q="SELECT gebruikersnaam,wachtwoord,id FROM login WHERE rollen !=1 AND rollen !=2" ; $stmt=$ conn->prepare( $q ); $stmt->execute(); ?> // Table to show the rows
<div id="box">
<!-- Table -->
<center>
<table>
<thead>
<tr>
<th style='color:#e20363;'>ID
<br>
</th>
<th>Gebruikersnaam
<br>
</th>
<th>Wachtwoord
<br>
</th>
<th>Actie
<br>
</th>
</tr>
</thead>
<tbody>
</div>
<?php while($row=$ stmt->fetch()){ $id=$row['id']; echo "
<tr>"; echo "
<td style='color:#e20363; text-align:center;'>{$row['id']}</td>"; // Here, I made the input field show the mysql row and made a form to submit when I press enter echo "
<form action='update.php' method='post'>"; echo "
<td>
<input type='text' value='{$row[' gebruikersnaam ']}' name='gebruikersnaam'>
</td>"; echo "</form>"; echo "
<td style='text-align:center; padding:10px;'>
<input type='text' value='{$row[' wachtwoord ']}' name='password'>
</td>"; echo '
<center>
<td>
<a href="delete.php?id='.$row['id'].'">
<img id="remove_user" src="images/remove.png" width="60px" style="padding:13px;">
</a>
</td>
</center>'; echo "</tr>"; } ?>
</tbody>
</table>
用户单击提交后,update.php 尝试处理更新查询。 这是我的 update.php 代码:
<?php
if(isset($_POST['username'])){
$host = 'localhost';
$user = 'root';
$pass = 'root';
$database = 'users';
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $pass);
$sql = "UPDATE `login` SET `gebruikersnaam` = :username";
//Prepare our UPDATE SQL statement.
$statement = $pdo-> prepare($sql);
//Bind our value to the parameter :id.
$statement->bindValue(':username', $_POST['username']);
//Execute our UPDATE statement.
$update = $statement->execute();
if($update){
header('Location: account_verwijderen.php');
}
};
?>
一切似乎都运行良好。但是当我尝试更新查询(按 Enter )时,它确实将我发送到 update.php ,但似乎没有执行任何操作,因为我到主页的重定向代码不起作用。
我在这里做错了什么?
最佳答案
您的问题可能是您正在绑定(bind)“:用户名”,但应该绑定(bind)“用户名” - 您不需要在绑定(bind)语句中使用冒号。
您也应该定义绑定(bind)的日期类型:
bindValue('id', $id, PDO::PARAM_INT);
尝试在 if (success) { 位之后添加一个 else 来触发 die(PDOStatement->errorInfo());
,您将看到 SQL 语法中的任何错误。在上线之前将其删除或添加到文件日志记录中。
还有
更新查询中没有“where”语句,因此它需要:
UPDATE `login` SET `gebruikersnaam` = :username where id = :id;
这意味着您还需要从 POST 中捕获登录 ID。如果没有它,查询将更新表中的所有记录。
关于php - 更新 mysql 行无法正常工作(PDO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34175306/