php - 用于更新具有相同 session_id 的表的 PHP 查询
问题描述
我session_id
在我的数据库中用作 ID 列。还有一个名为 Sections 的列添加了整个xml
. xml
包含部分名称和用户在那里花费的时间。我想更新相同 session_ids 的 Sections 列。我怎样才能做到这一点?现在它为每条记录添加一个新行。这是我的php代码
$id=$_SESSION["id"];
$totaltime=$_POST['total'];
$HomeTime=$_POST['home'];
$ProductTime=$_POST['products'];
$ProcessTime=$_POST['process'];
$DevTime=$_POST['dev'];
$ContactTime=$_POST['contact'];
$xmlObject = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<item>
<section>
<name>Home</name>
<time>$HomeTime</time>
</section>
<section>
<name>Product</name>
<time>$ProductTime</time>
</section>
<section>
<name>Process</name>
<time>$ProcessTime</time>
</section>
<section>
<name>Development</name>
<time>$DevTime</time>
</section>
<section>
<name>Contact</name>
<time>$ContactTime</time>
</section>
</item>
XML;
$sql = "INSERT INTO user_time (ID, Sections) VALUES ('$id', '$xmlObject')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
解决方案
首先使用它存在的会话ID从db中获取现有的XML数据,然后存储到变量$xmlFromDB
并继续执行以下步骤。否则插入到数据库。
if(session id exisits in db){
//Fetch the table row or corresponding session id.
//Extract times from XML using this code.
$arr = [];
$times = new SimpleXMLElement($xmlFromDB);
foreach($times->section as $sec){
$arr[$sec->name.""] = $sec->time;
}
extract($arr);
//This will add previous value to new value.
$HomeTime += $Home;
$ProductTime += $Product;
$ProcessTime += $Process;
$DevTime += $Development;
$ContactTime += $Contact;
}
//Now generate xml using your method.
$xmlObject = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<item>
<section>
<name>Home</name>
<time>$HomeTime</time>
</section>
<section>
<name>Product</name>
<time>$ProductTime</time>
</section>
<section>
<name>Process</name>
<time>$ProcessTime</time>
</section>
<section>
<name>Development</name>
<time>$DevTime</time>
</section>
<section>
<name>Contact</name>
<time>$ContactTime</time>
</section>
</item>
XML;
if(session id exists){
//Then update the same row using the UPDATE query.
$sql = "UPDATE user_time SET Sections = '$xmlObject' where = '$id'";
}else{
$sql = "INSERT INTO user_time (ID, Sections) VALUES ('$id', '$xmlObject')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
推荐阅读
- python - py2exe 不工作 - 闪烁控制台并关闭
- python - 带有旋转/缩放/剪切/平移提取的 3D 点云配准(知道对应关系)
- javascript - 如何使用双向数据绑定将一个文本替换为另一个文本?
- python - 为什么我的 val_loss 下降但我的 val_accuracy 停滞不前
- ruby-on-rails - 在 kubernetes 中运行 rails + postgres:连接被拒绝
- flutter - 如何在 Firestore 查询中使用 DocumentReference
- c# - 获取程序要连接的 IP 地址
- .net - 如何在 docker 中安装 .net 框架?
- sql - PostgreSQL:用 CASE 加入倒数
- isabelle - 如何在 Isabelle 中建立会话。(法新社的一个例子)