从数组更新mysql表(HTML表单输入)

时间:2013-09-10 14:10:43

标签: php mysql

我正在尝试从多个表单字段(文本字段和文本区域)更新mysql表的一行(= ID)。该表如下所示:

ID | Col 1 | Col 2 | Col 3 ... | Col 50

如果我使用像这样的$ _Post []变量

,一切正常
$Name = $_POST['Name'];
$Name2 = $_POST['Name2'];  
$sql= "UPDATE Bilder SET Name = '$Name', Name2 = '$Name2' WHERE id = '$ID'"; 


<form id="InsertData" action="insert-dataset.php" method="post"> 
  <input type="hidden" name="ID" id="ID" value="'.$row->id.'" /> 
  <input type="text" name="Name" value="'.$row->Name.'" /><br />
  <input type="text" name="Name2" value="'.$row->Name.'" /><br />  
  <input type="submit" name="submit" value="Daten eintragen" class="sendbutton" /> 
</form> 

由于我有数百个字段,我宁愿使用这样的数组:

<input type="text" name="Name[]" value="'.$row->Name.'" />

我找到了更新一列所有单元格的工作示例。但我必须为一个ID更新所有列。

任何帮助将不胜感激。提前谢谢!

这是最终结果:

$col_result = mysql_query("SHOW COLUMNS FROM Bilder");
$row_result = mysql_query(sprintf("SELECT * FROM Bilder WHERE id = %s", $ID));
if(!$col_result) {
    echo 'Konnte Anfrage nicht ausführen: ' . mysql_error();
    exit;
}
if ( !empty($_POST) ) { 
    $aDataSet = array(); 
    while( list( $field, $value ) = each( $_POST )) { 
    $aDataSet[] = $field . "='" . $value . "'";
    } 
$update_sql = "UPDATE Bilder SET " . implode( ',', $aDataSet ); 
$update_sql .= sprintf("WHERE id = '$ID'");
$result = mysql_query($update_sql, $connection); 
if(!$result)  
 {  
 die('');  
 }  
 echo '';  
}   
mysql_close($connection)
?> 

更新查询将仅包含具有相应输入字段的列(输入名称=列名称)。由于我有数百个输入字段,因此我可以使用相同的代码将它们分布在多个页面上进行更新查询。

谢谢大家的帮助。

3 个答案:

答案 0 :(得分:0)

可能是这样的:

$str = '';
$id = 0;
foreach($_POST['Name'] as $value)
{
    $id ++;
    $str .= ($str == '' ? '' : ', ').'Name'.$id.' = \''.addslashes($value).'\'';
}
$sql= "UPDATE Bilder SET ".$str." WHERE id = '$ID'";

注意:在此示例中,您的sql字段是Name1,Name2,Name3 ......

注意2:在sql查询中粘贴变量时,应始终至少使用addslashes方法,以保护自己免受黑客攻击。

答案 1 :(得分:0)

这是一些想法。

注意:未经测试

<?php
// Get all of the field names
$col_result = mysql_query("SHOW COLUMNS FROM Bilder");

// make sure we could get the colnames from mysql
if(!$col_result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

// Handle a POST
if(!empty($_POST)){
    // start preparing the update statement
    $update_sql = "UPDATE Bilder SET ";
    if(mysql_num_rows($col_result) > 0) {
        // make a key = value statement for each column in the table
        while($colrow = mysql_fetch_assoc($col_result)) {
            // prepare the key = value statement
            $update_sql .= sprintf(" %s = %s, ", $colrow["Field"], mysql_real_escape_string($_POST[$colrow["Field"]]));
        }
    }
    // BTW this is going to have a extra "," in it use substr to clear it
    $update_sql = substr_replace($update_sql ,"", -2);

    // finish off by limiting this statement to only one row
    $update_sql .= sprintf(" WHERE id = %s", mysql_real_escape_string($_POST["id"]));

    // ACTUALLY RUN THIS STATEMENT
}

if(!$row_result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

//准备sql来获取我们正在处理的当前行 $ row_result = mysql_query(sprintf(“SELECT * FROM Bilder WHERE id =%s”,$ id));

// Get the row item that you are currently working on
$row = mysql_fetch_row($row_result);

// output all the formfields for the above row
if(mysql_num_rows($col_result) > 0) {
    // Go through all of the columns and output the colname from $colrow and the value from $row
    while ($colrow = mysql_fetch_assoc($col_result)) {
        // The HTML (don't be daunted by that variable-variable http://php.net/manual/en/language.variables.variable.php)
        echo '<input type="text" name="' . $colrow["Field"] . '" value="' . $row->{$colrow["Field"]} . '" /><br />';
    }
}
?>

答案 2 :(得分:0)

好的,我使用了preg_replace。这可能不是最佳做法。代码看起来像这样,工作得很好:

// Handle a POST
if(!empty($_POST)){
    // start preparing the update statement
    $update_sql = "UPDATE Bilder SET ";
    if(mysql_num_rows($col_result) > 0) {
        // make a key = value statement for each column in the table
        while($colrow = mysql_fetch_assoc($col_result)) {
            // prepare the key = value statement
        $update_sql .= sprintf("%s = '%s',", $colrow["Field"], mysql_real_escape_string($_POST[$colrow["Field"]]));
        }

    }
// BTW this is going to have a extra "," in it use substr to clear it

// finish off by limiting this statement to only one row
$update_sql .= sprintf("WHERE id = '$ID'");
$update_sql = preg_replace("/,WHERE/", "WHERE", $update_sql);

当然,存在安全问题。我会解决这个问题。但是,这并不重要,因为此应用程序仅供个人使用。它不公开。