php查询用于更新具有相同会话id的表

41zrol4v  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(343)

我曾经 session_id 作为mydb.com中的id列,还有一个名为sections的列添加了整个 xml . 这个 xml 包含节名称和用户在其中花费的时间量。我想为相同的会话ID更新“节”列。我该怎么做?现在它为每个记录添加一个新行。这是我的php代码

  1. $id=$_SESSION["id"];
  2. $totaltime=$_POST['total'];
  3. $HomeTime=$_POST['home'];
  4. $ProductTime=$_POST['products'];
  5. $ProcessTime=$_POST['process'];
  6. $DevTime=$_POST['dev'];
  7. $ContactTime=$_POST['contact'];
  8. $xmlObject = <<<XML
  9. <?xml version="1.0" encoding="UTF-8"?>
  10. <item>
  11. <section>
  12. <name>Home</name>
  13. <time>$HomeTime</time>
  14. </section>
  15. <section>
  16. <name>Product</name>
  17. <time>$ProductTime</time>
  18. </section>
  19. <section>
  20. <name>Process</name>
  21. <time>$ProcessTime</time>
  22. </section>
  23. <section>
  24. <name>Development</name>
  25. <time>$DevTime</time>
  26. </section>
  27. <section>
  28. <name>Contact</name>
  29. <time>$ContactTime</time>
  30. </section>
  31. </item>
  32. XML;
  33. $sql = "INSERT INTO user_time (ID, Sections) VALUES ('$id', '$xmlObject')";
  34. if ($conn->query($sql) === TRUE) {
  35. echo "New record created successfully";
  36. } else {
  37. echo "Error: " . $sql . "<br>" . $conn->error;
  38. }
i34xakig

i34xakig1#

首先使用会话id从数据库中获取现有的xml数据,并将其存储到变量中 $xmlFromDB 并继续执行以下步骤。否则插入db。

  1. if(session id exisits in db){
  2. //Fetch the table row or corresponding session id.
  3. //Extract times from XML using this code.
  4. $arr = [];
  5. $times = new SimpleXMLElement($xmlFromDB);
  6. foreach($times->section as $sec){
  7. $arr[$sec->name.""] = $sec->time;
  8. }
  9. extract($arr);
  10. //This will add previous value to new value.
  11. $HomeTime += $Home;
  12. $ProductTime += $Product;
  13. $ProcessTime += $Process;
  14. $DevTime += $Development;
  15. $ContactTime += $Contact;
  16. }
  17. //Now generate xml using your method.
  18. $xmlObject = <<<XML
  19. <?xml version="1.0" encoding="UTF-8"?>
  20. <item>
  21. <section>
  22. <name>Home</name>
  23. <time>$HomeTime</time>
  24. </section>
  25. <section>
  26. <name>Product</name>
  27. <time>$ProductTime</time>
  28. </section>
  29. <section>
  30. <name>Process</name>
  31. <time>$ProcessTime</time>
  32. </section>
  33. <section>
  34. <name>Development</name>
  35. <time>$DevTime</time>
  36. </section>
  37. <section>
  38. <name>Contact</name>
  39. <time>$ContactTime</time>
  40. </section>
  41. </item>
  42. XML;
  43. if(session id exists){
  44. //Then update the same row using the UPDATE query.
  45. $sql = "UPDATE user_time SET Sections = '$xmlObject' where = '$id'";
  46. }else{
  47. $sql = "INSERT INTO user_time (ID, Sections) VALUES ('$id', '$xmlObject')";
  48. }
  49. if ($conn->query($sql) === TRUE) {
  50. echo "New record created successfully";
  51. } else {
  52. echo "Error: " . $sql . "<br>" . $conn->error;
  53. }
展开查看全部

相关问题