[英]Updating a form entry in php/mysql with checkboxes?
我如何允许用户提交表单,例如在“重新提交”时更新其条目
12345678910(唯一ID),提交了带有选择的表格,
12345678910,使用新选择重新提交
负责“自动”更新此类表单条目的功能是什么?
我知道我可以检查该条目是否存在,但是如果存在则如何更新它,如果不存在则如何将其插入新行中...
function checkstudentid($studentid)
{
$con = connectvar();
mysql_select_db("database1", $con);
$result = mysql_query(
"SELECT * FROM table WHERE studentid='$studentid' LIMIT 1");
if(mysql_fetch_array($result) !== false)
....
// I want to add the entry here since it doesn't exist...with checkboxes
// else , I want to update if it already exists
}
现在我也不完全肯定上面的代码是否可以工作...但是这是我的入门知识,如果有其他方法或者我使用的方法“错误”,我将不胜感激...或者如果我正在尝试的事情是可能的(我的工作方式)...
笔记
如果我使用不赞成使用的方法与数据库进行交互,则可能只是这样做:
<?php
function checkstudentid($studentid) {
$con = connectvar();
mysql_select_db("database1", $con);
$result = mysql_query(
"SELECT * FROM table WHERE studentid='$studentid' LIMIT 1");
$query = '';
if (mysql_num_rows($result) > 0) {
$query = "UPDATE table SET column1='$value_one', column2='$value_two' WHERE studentid='$studentid'";
} else {
$query = "INSERT INTO table VALUES('$new_id', '$value_one', '$value_two')";
}
if (mysql_query($query)) {
return true;
} else {
return false;
}
}
?>
但是话又说回来,我将使用PDO与数据库进行交互。
这是一个简单的PDO示例(您只需编写函数以返回连接):
<?php
function checkstudentid($studentid) {
$update = false;
$dbh = formPDOConnection();
$query = "SELECT studentid FROM table WHERE studentid=:id";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':id', $studentid, PDO::PARAM_STR);
if ($stmt->execute()) {
if ($stmt->rowCount()) {
$update = true;
}
} else {
return 'failure to execute query';
}
// if we just need to update
if ($update) {
$update = "UPDATE table SET value1=:v1,
value2=:v2 WHERE studentid=:id";
$stmt = $dbh->prepare($update);
$stmt->bindValue(':id', $studentid, PDO::PARAM_STR);
$stmt->bindValue(':v1', $value_one, PDO::PARAM_STR);
$stmt->bindValue(':v2', $value_two, PDO::PARAM_STR);
} else {
$insert = "INSERT INTO table VALUES(:id,:v1,v2)";
$stmt = $dbh->prepare($insert);
$stmt->bindValue(':id', $new_id, PDO::PARAM_STR);
$stmt->bindValue(':v1', $value_one, PDO::PARAM_STR);
$stmt->bindValue(':v2', $value_two, PDO::PARAM_STR);
}
return $stmt->execute();
}
?>
避免头痛,并停止使用mysql_ *
您可以在mysql代码上使用INSERT... ON DUPLICATE KEY UPDATE...
来代替PHP中的逻辑。
这是一个示例:
INSERT INTO `category` (`id`, `name`) VALUES (12, 'color')
ON DUPLICATE KEY UPDATE `name` = 'color';
参考: http : //dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.