我是PHP MYSQL初学者!尝试获取行的id(主键)值并更新其在数据库中的相应值。我的搜索结果正在完善,我被重定向到我的更新表单页面,我想在其中显示获取的结果,以便我可以编辑结果并更新值。
我的PHP
<?php
require_once 'db_alternate2.php';
session_start();
try{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
if( isset($_GET['edit']) )
{
$id = $_GET['edit'];
$res= "SELECT * FROM staff_db WHERE staff_id='$id'";
$r = $conn->query($res);
$r->setFetchMode(PDO::FETCH_ASSOC);
}
if( isset($_POST['new_staf_id']) && isset($_POST['new_staf_name']) && isset($_POST['new_staf_acc']) && isset($_POST['new_staf_bnkaddrs']) )
{
$staf_id = $_POST['new_staf_id'];
$staf_name = $_POST['new_staf_name'];
$staf_acc = $_POST['new_staf_acc'];
$staf_bnkaddrs = $_POST['new_staf_bnkaddrs'];
$sql = $conn->prepare("UPDATE staff_db SET staff_id='$staf_id' staff_name='$staf_name' staff_acc='$staf_acc' staff_bnkaddrs='$staf_bnkaddrs' WHERE sl_no ='$id'");
$sql->execute();
$result1 = $sql->fetch(PDO::FETCH_ASSOC);
echo "<meta http-equiv='refresh' content='0;url=staff_update.php'>";
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?> .
我的HTML
<form class="" style="right:10px !important;" action="staff_db.php" method="post">
<div class="main-left" style="width:38% !important; margin-left:100px;">
<p>Staff ID:</p> <input type="text" name="staf_id" value="______"/>
<p>Name:</p> <input type="text" name="staf_name" value="______"/>
</div>
<div class="main-right" style="width:38% !important; margin-right:100px;">
<p>Account no:</p> <input type="text" name="staf_acc" value="______"/>
<p>Bank Address:</p> <input type="text" name="staf_bnkaddrs" value="______"/>
</div>
<div class="bottom-centre" style="padding-top:50px; ">
<input class="submit" type="submit" value="Update"/>
</div>
</form>
我知道这是一个简单的问题,但请指导我!如何在表单的值=&#34; ______&#34; 内显示PDO获取的结果。
提前致谢!
答案 0 :(得分:1)
您的代码中只需进行少量修改
if( isset($_GET['edit']) )
{
$id = $_GET['edit'];
$res= "SELECT * FROM staff_db WHERE staff_id='$id'";
$r = $conn->query($res);
$r->setFetchMode(PDO::FETCH_ASSOC);
$result = $r->fetch();
}
&#13;
并且您的表单中很少修改以放置值
<input type="text" name="staf_name" value=<?php echo $result["staff_name"]; ?>/>
&#13;