假设我已将多个表中的值提取到表单,并希望更改一个或多个输入,即。电话号码或地址。
所以这是我的选择查询:
SELECT c.*, u.username
FROM client c
JOIN users u ON u.id = c.credid
WHERE credid = :id
考虑到上面的链接问题(和答案),我如何为已更改的值进行准备更新查询? 我的表是InnoDB。
编辑:我需要将用户名表和用户表的所有其他内容放入用户表。 (clients表字段credid是用户表主键id的外键)
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<?php
echo 'Username: <input type="text" name="1" value="' . $getuserinfo['username'] . '" /><br>';
echo 'Client: <input type="text" name="2" value="' . $getuserinfo['company'] . '" /><br>';
echo 'Address: <input type="text" name="3" value="' . $getuserinfo['address1'] . '" /><br>';
echo 'Address 2: <input type="text" name="4" value="' . $getuserinfo['address2'] . '" /><br>';
echo 'ZIP: <input type="text" name="5" value="' . $getuserinfo['zip'] . '" /><br>';
echo 'City: <input type="text" name="6" value="' . $getuserinfo['city'] . '" /><br>';
echo 'Country: <input type="text" name="7" value="' . $getuserinfo['country'] . '" /><br>';
echo 'E-mail: <input type="text" name="8" value="' . $getuserinfo['email'] . '" /><br>';
echo 'Phone number: <input type="text" name="9" value="' . $getuserinfo['phone'] . '" /><br>';
?>
<input type="submit" name="submit" value="Save " /><br>
</form>
编辑: 我想构建一个像这样的SQL。
UPDATE c.(name, address, zip, email, phone, etc.),u.username
VALUES (:1, :2, :3, :etc)
FROM client c
JOIN users u ON u.id = c.credid
WHERE credid = :id
这附近有吗? 或者可能是这样的:
UPDATE users,client
SET users.username = :username,
client.value1 = :value1,
client.value2 = :value2,
etc...
WHERE client.credid=users.id
答案 0 :(得分:0)
您需要做的就是将输入重命名为表格列的名称,例如。
foreach ($getuserinfo as $key => $val) {
echo ucfist($key).': <input type="text" name="'.$key.'" value="' . $val . '" /><br>';
}
上面的内容不会为您提供准确的标签,但很容易添加if语句来改变它。
在您最初获取信息后,将其添加到会话数组以检查是否有任何更改
$_SESSION = $getuserinfo;
然后在回发表单后(请记住,除了检查$_SESSION
中是否已存在索引之外,这不包含任何验证)
if ($_POST['username'] != $_SESSION['user_edit_info']['username']) {
//run validation and query to update username
}
$posted = $_POST;
unset($posted['username']);
$sql_array = array();
$params = array();
foreach ($posted as $key => $val) {
//This should prevent extra fields being posted
if (isset($_SESSION['user_edit_info'][$key]) && $_SESSION['user_edit_info'][$key] != $val) {
$sql_array[] = "$key=:$key";
$params[$key] = $val;
}
}
if (!empty($sql_array)) {
$params['id'] = $_SESSION['user_id']; //or whatever you set it to in your session
//I don't know exactly how you're running your PDOs but below should at least show
//what you need to do
('UPDATE client SET '.implode(',', $sql_array).' WHERE credid=:id', $params);
}
//finally you don't need this anymore so just unset it
unset($_SESSION['user_edit_info']);
希望这有帮助!