我正在尝试编辑数据(存储在数据库中)。这是display.php。首先它显示来自DB的数据(如果没有数据则为空白字段)。然后编辑按钮以编辑数据库。
<html>
<body>
<?php
if(!isset($_POST['edit_pro']))
{
?>
//get data from DB and display in table.
<form>
<input type="submit" name= "edit" value="edit">
</form>
<?php
}
else
{
?>
<form name="edit_DB" action="edit.php">
//edit ...2 <select> fields and 1 text field.
//submit button
</form>
<?php
}
?>
在edit.php中 我只是更新数据库。但是如果我只想改变1个字段呢(问题是所有字段都得到更新)。这是edit.php
<?php
include_once 'db_connect.php';
$db_con = dbConnect("dbname");
$uid = $_SESSION['uid'];
if(isset($_POST['edit']))
{
$c = $_POST['c'];
$s = $_POST['list'];
$t = $_POST['nm'];
$a = $_POST['a'];
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c,$s,$t,$uid));
header("Location:display.php");
}
?>
答案 0 :(得分:1)
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
此查询表示:
所以,你的查询一次更新了3个字段,没关系,因为它应该做什么
如果您想更改此逻辑,只更新一些您需要更改查询和参数的字段,例如,如果您只想更改c
使用:
$sql = "UPDATE `user` SET `c` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c, $uid)); // this array binds values to question marks, so count should be the same, we have 2 ? - we must use 2 variables
表示c AND t:
$sql = "UPDATE `user` SET `c` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute();
如果您不确切知道有多少参数,则需要动态查询构建,例如:
$arr = array();
$sqlA = array();
if (isset($_POST['c']) && $_POST['c']) {
$arr[] = $_POST['c'];
$sqlA[] = '`c`=?';
}
if (isset($_POST['s']) && $_POST['s']) {
$arr[] = $_POST['s'];
$sqlA[] = '`s`=?';
}
if (isset($_POST['t']) && $_POST['t']) {
$arr[] = $_POST['t'];
$sqlA[] = '`t`=?';
}
if (count($arr)) {
$sql = 'UPDATE `user` SET '.implode($sqlA, ',').' where u_id = ?';
$arr[] = $uid;
$q = $db_con->prepare($sql);
$q->execute($arr);
}
答案 1 :(得分:0)
这意味着请求的WHERE子句不起作用。检查是否在变量$ t中传递引号,以便在WHERE子句
之前关闭$ sql