【问题标题】:dynamic SQL insert query动态 SQL 插入查询
【发布时间】:2016-09-20 14:48:13
【问题描述】:

嗨朋友们,我正在创建一个 php 页面来将数据从 csv 文件导入到 sql 数据库中。..

这里的数据库表和字段数由用户自己指定..

如果用户指定了 4 个字段,则使用 for 循环创建它,如下所示..

<?php
include('connect.php');
$name = $_POST['table_name'];
//echo $name;

$create_tab = "CREATE TABLE $name(id varchar(15) PRIMARY KEY)";




if(mysql_query($create_tab,$con))
            {
                echo "Table <b><i>$name</i></b> created successfully... <br/> <br/>Add columns...";
            }
            else {
                die('Error1'.mysql_error());
            }



$field = $_POST['number_of_fields'];
//echo $name.$field;
echo '<form id="form1" name="form1" method="post" action="update-table.php">';
echo "<p>
          <label for='tablename'></label>
          <input type='hidden' name='tablename' id='tablename' value='$name' size='5'/>
        </p>";

echo "<p>
          <label for='fields'></label>
          <input type='hidden' name='fields' id='fields' value='$field' size='5'/>
        </p>";
echo '<table border="1" cellpadding="5" cellspacing="5">';
for ( $i = 1; $i <= $field; $i ++) {
    echo '<tr>';
    echo '<td>';
    echo "<p>
          $i
        </p>";
        echo'</td>';

    echo '<td>';
    echo "<p>
          <label for='textfield$i'></label>
          <input type='text' name='field$i' id='textfield$i' />
        </p>";
        echo'</td>';
            echo '<td>';
            echo "
            <select name='select$i' id='select$i'>
                    <option value='varchar(200)'>varchar</option>
                    <option value='int'>int</option>
                    <option value='float'>float</option>
                                        <option value='date'>date</option>
                  </select>";
                echo '</td>';
                                echo '</tr>';


    }
            echo '</table>';
?>
        <p>File Location :
          <input type="text" name="fileField" id="fileField" />
      </p>
<br/>
<INPUT type="image" name="search" src="images/alter.gif" border="0" height="75" width=120">

</form>

然后按如下方式创建和更改表..

 <?php
    include('connect.php');
$field = $_POST[fields]; 
$name = $_POST[tablename];    

for ( $i = 1; $i <= $field; $i++) {
//getting field names
  $varname = ($txtfield . $i);
    $$varname = $_POST[field.$i]; 
  // echo $$varname;
   $fi = $$varname;

//getting field types
  $selname = ($selfield . $i);
    $$selname = $_POST[select.$i]; 
     $dt = $$varname;

$sql = "ALTER TABLE $name ADD $fi $dt";

if(mysql_query($sql,$con))
            {
                echo "Field <b><i>$fi</i></b> added successfully...<br/>";
            }
            else {
                die('Error1'.mysql_error());
            }

    }


?>

如上数据库表和字段被装箱...

我得到了使用静态变量插入数据的概念如下..

<?php
// data import
include('connect.php');


$field = $_POST['fileField']; //file directory

echo "<br/><br/>Import file path: ";
echo $field;

 $file = $field; 

$lines = file($file);
$firstLine = $lines[0];

foreach ($lines as $line_num => $line) {
    if($line_num==0) { continue; } //escape the header column
    $arr = explode(",",$line);
    $column1= $arr[0];
    $column2= $arr[1];
// ' escape character
    if (strpos($column2, "'") == FALSE)
{
    $column21 = $column2;
}
else{
$column21 = str_replace ("'", "\'", $column2);
}
        $column3= $arr[2];
            $column4= $arr[3];

//print data from csv
echo "<table border='1' width='800' cellpadding='5' cellspacing='2'>";
echo "<tr>";
echo "<td width='8'>";
echo $column1;
echo "</td>";
echo "<td width='100'>";
echo $column21;
echo "</td>";
echo "<td width='5'>";
echo $column3;
echo "</td>";
echo "<td width='5'>";
echo $column4;
echo "</td>";
echo "</tr>";
echo "</table>";

     $import="INSERT into $name (id,name,year1,year2) values(

     '$column1','$column21','$column3','$column4')";
     mysql_query($import) or die(mysql_error());

}

?>

现在,我的问题是我怎样才能使这个插入语句动态,因为它从表创建和更改查询中的 for 循环获得的数据在插入查询中动态创建字段名称和值???

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    如果我正确理解您的问题,听起来您想将插入组合到一个查询中(这在性能方面非常聪明)。 SQL 允许您一次插入多行,如下所示:

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

    因此,通过创建一个 VALUES 数组并使用 implode 将它们连接起来,您可以进行一个查询:

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

    既然我理解了你真正的问题,我可以给你一个基本的概述,说明你需要做些什么来实现这个目标。您需要创建一个表单,允许用户输入将插入到表中的数据。

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

    然后你需要编写一个PHP脚本来处理表单提交并将数据插入到MySQL中:

    <?php
        //Check form submission and validate entries, then...
    
        $stmt = $pdo->prepare('INSERT INTO table (field1) VALUES(:field1)');
        $stmt->execute(array(':field1', $_POST['field1']));
    ?>
    

    【讨论】:

    • 谢谢.. 但我的问题是.. 我可以将查询中的值作为插入表(动态值)值(动态值);其中动态值就像 field1, field2... 使用 for 循环获得的??
    • 哦,我想我现在明白你的问题了。您仍然应该真正考虑组合所有插入查询。我将更新一个指向可能对您的实际问题有所帮助的页面的链接。
    【解决方案2】:

    然后你需要编写一个PHP脚本来处理表单提交并将数据插入到MySQL中:

    函数插入($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); 
    
        $addd = "";
        $count = 0;
        for ( $i = 1; $i < $numcolumn; $i++ ) 
        { 
            $columnnames = mysql_field_name($result1, $i); 
            if(($numcolumn-1) == $i)
            {
                $addd .= $columnnames;
                $data .= "'".$datad[$count]."'";
            }
            else
            {
                $addd .= $columnnames.",";
                $data .= "'".$datad[$count]."',";
            }
            $count++;
        }
        $ins = "INSERT INTO ".$tablet."(".$addd.")"."VALUES(".$data.")";
        mysql_query($ins);
        header('Location: index.php');
        exit;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-13
      • 2023-01-14
      • 2021-12-20
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      相关资源
      最近更新 更多