creating a dynamic php insert into mysql function?

后端 未结 1 1499
名媛妹妹
名媛妹妹 2021-01-28 23:13

i have a post with a LOT of variables, and I was wondering if there was some way of inserting the information into mysql dynamically, rather than typing it all out manually, as

相关标签:
1条回答
  • 2021-01-29 00:10

    This is what we use to do a similar thing (inserting into a table we have no control over, and which has no API access)

    Using the DESCRIBE query ensures only columns that exist are inserted.

    $db = new DB();
    $sql = 'DESCRIBE `table`';
    $result = $db->query($sql);
    $row = array();
    $query = array();
    
    while ($row = $result->fetchRow())
    {
        if (array_key_exists($row['field'], $form_data))
            if (is_null($form_data[$row['field']]))
                $query[$row['field']] = 'NULL';
            else
                $query[$row['field']] = $db->quote($form_data[$row['field']]);
    }
    
    $keys = array_keys($query);
    
    foreach ($keys as &$key)
        $key = $db->quoteIdentifier($key);
    
    unset($key);
    
    $vals = array_values($query);
    
    $sql = 'INSERT INTO `table` '
         . '(' . implode(', ', $keys) . ') '
         . 'VALUES(' . implode(', ', $vals) . ')';
    

    edit: DB() is our wrapper around MDB2.

    And of course this allows them to fill in the entire row. If you have restricted columns (auto-increment ids and such), you'll have to filter those out of the form data...

    0 讨论(0)
提交回复
热议问题