Copy row but with new id

后端 未结 6 1017
有刺的猬
有刺的猬 2020-12-07 22:36

I have a table \"test\" with an auto incremented id and an arbitrary number of columns.

I want to make a copy of a row in this table with all columns th

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 23:06

    THIS WORKS FOR DUPLICATING ONE ROW ONLY

    • Select your ONE row from your table
    • Fetch all associative
    • unset the ID row (Unique Index key)
    • Implode the array[0] keys into the column names
    • Implode the array[0] values into the column values
    • Run the query

    The code:

     $qrystr = "SELECT * FROM mytablename  WHERE id= " . $rowid;
     $qryresult = $this->connection->query($qrystr);
     $result = $qryresult->fetchAll(PDO::FETCH_ASSOC);
     unset($result[0]['id']); //Remove ID from array
     $qrystr = " INSERT INTO mytablename";
     $qrystr .= " ( " .implode(", ",array_keys($result[0])).") ";
     $qrystr .= " VALUES ('".implode("', '",array_values($result[0])). "')";
     $result = $this->connection->query($qrystr);
     return $result;
    

    Of course you should use PDO:bindparam and check your variables against attack, etc but gives the example

    additional info

    If you have a problem with handling NULL values, you can use following codes so that imploding names and values only for whose value is not NULL.

    foreach ($result[0] as $index => $value) {
        if ($value === null) unset($result[0][$index]);
    }
    

提交回复
热议问题