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

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

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

m3eecexj1#

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

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;
}

相关问题