dynamic SQL insert query

前端 未结 2 579
南旧
南旧 2020-12-20 07:27

hi friends i\'m creating a php page to import the data from a csv file into sql database..

here database table and number of fields are specified by user itself..

相关标签:
2条回答
  • 2020-12-20 08:06

    If I understand your question correctly, it sounds like you want to combine your inserts into one query (which is very smart performance wise). SQL allows you to insert multiple rows at once like so:

    INSERT INTO table (id, first, last) VALUES(NULL, 'Ryan', 'Silvers'),(NULL, 'Oscar', 'Smith'),(NULL, 'Jessica', 'Owens')
    

    So by using creating an array of VALUES and using implode to join them you can make one query:

    //Create rows
    foreach($rows as $row) {
        $queryRows[] = "(NULL, '".$row['first']."', '".$row['last']."')";
    }
    
    //Create query
    $query = 'INSERT INTO table (id, first, last) VALUES'.implode(',', $queryRows);
    

    Now that I understand your real question, I can give you a basic overview of what you need to do to achieve this. You need to create a form that allows a user to enter data that will be inserted into the table.

    <form method="post" action="process.php">
        <input name="field1" />
        <!-- and more -->
    </form>
    

    Then you need to write a PHP script to process the form submission and insert the data into MySQL:

    <?php
        //Check form submission and validate entries, then...
    
        $stmt = $pdo->prepare('INSERT INTO table (field1) VALUES(:field1)');
        $stmt->execute(array(':field1', $_POST['field1']));
    ?>
    
    0 讨论(0)
  • Then you need to write a PHP script to process the form submission and insert the data into MySQL:

    function insert($tablet,$datad) {

        if(empty($tablet)) { return false; }
    
        if(empty($this->CONN)){ return false; }
    
        $conn = $this->CONN;
    
        $query1 = "select * from user"; 
        $result1 = mysql_query($query1); 
        $numcolumn = mysql_num_fields($result1); 
    
        $affffd = "";
        $count = 0;
        for ( $i = 1; $i < $numcolumn; $i++ ) 
        { 
            $columnnames = mysql_field_name($result1, $i); 
            if(($numcolumn-1) == $i)
            {
                $affffd .= $columnnames;
                $data .= "'".$datad[$count]."'";
            }
            else
            {
                $affffd .= $columnnames.",";
                $data .= "'".$datad[$count]."',";
            }
            $count++;
        }
        $ins = "INSERT INTO ".$tablet."(".$affffd.")"."VALUES(".$data.")";
        mysql_query($ins);
        header('Location: index.php');
        exit;
    }
    
    0 讨论(0)
提交回复
热议问题