2012-01-09 114 views
0

我有一个表单,用户可以更改他已经在数据库中的个人信息。 什么是最好的解决方案,只更新数据库字段被更改,而不是所有可用的表单选项。PHP更新用户信息

如果您有更好的建议,而不是将所有内容放在一个表格中,请告诉。

+1

你使用任何一种框架? – cmbuckley 2012-01-09 12:13:33

+0

在wamp服务器上的PHP/MYSQL,没有框架,在记事本中编写代码。 – 2012-01-09 12:14:19

+2

唯一真正的傻瓜证明方法是在新数据提交后,在服务器端验证/比较新数据与原始数据。这意味着你必须在'UPDATE'之前再次选择''',或者在某种会话中存储原始'SELECT'的结果。 – DaveRandom 2012-01-09 12:16:38

回答

2

更新整个用户记录,不考虑哪些字段发生了变化,哪些字段没有发生变化。

一次更新所有字段的时间和内存效率大致与查询哪些字段已更改相同。其实,你只是浪费你的时间逐一检查字段,看看哪些更新。所以在更新之前进行这种检查是没有意义的。

1

提交更新表单后,您应该通过触发选择查询where id = xyz然后检查if($_POST['textboxname'] == $row['colname'])来检查值,如果发现有任何更改,则添加到更新查询其他明智地跳过该值。

如果你已经在这里写你的代码,那么这可能很容易理解你。

2

假设MySQL和你不介意使用会话,这里是一个办法做到这一点:

<?php 

    // Start the session 
    session_start(); 

    // The name of the table in the database 
    $table = 'table_name'; 
    // The primary key of the record we are dealing with 
    $id = 1; 
    // The name of the column that holds the primary key 
    $pkCol = 'id'; 

    // Connect to database somewhere here and store it in $conn 

    if (!empty($_POST['update'])) { 

    // Update the record 

    // Compare values from $_POST with values from $_SESSION and build an array of data that has changed 
    $changes = array(); 
    foreach ($_SESSION['original_data'] as $colName => $value) { 
     if ($_POST[$colName] != $value) { 
     $changes[] = "$colName = '".mysqli_real_escape_string($conn, $_POST[$colName])."'"; 
     } 
    } 

    // Build the query 
    $query = "UPDATE $table SET ".implode(', ', $changes)." WHERE $pkCol = {$_SESSION['record_id']}"; 

    // Do the query 
    if (!mysqli_query($conn, $query)) exit("Unable to update record in database"); 

    } 

    // generate the form 

    // Get original data from DB and store it in the session 
    $query = "SELECT * FROM $table WHERE $pkCol = $id"; 
    if (!$result = mysqli_query($conn, $query)) exit("Unable to get record from database"); 
    $_SESSION['original_data'] = mysqli_fetch_assoc($result); 
    $_SESSION['record_id'] = $id; 

    // Echo start of HTML page 
    echo "<html> 

    <head> 
    <title>Record update example</title> 
    </head> 

    <body> 
    <form method='post' action=''> 
     <input type='hidden' name='update' value='1' /> 
"; 

    // Generate inputs from data 
    foreach ($_SESSION['original_data'] as $colName => $value) { 
    if ($colName != $pkCol) { 
     $colName = htmlspecialchars($colName); 
     $value = htmlspecialchars($value); 
     echo "  $colName: <input type='text' name='$colName' value='$value' /><br />\n"; 
    } 
    } 

    // Close off HTML 
    echo " </form>\n </body>\n</html>"; 
1

你可以做侯赛因提出什么(+1,顺便说一句),或者你可以标记以某种方式更改项目,并且您可以将项目映射到您的ID。