使用会话更新用户列

时间:2013-07-09 20:29:19

标签: php mysql

我的php页面上有删除选项,但我添加了删除前存档数据的选项,但同时我想用person会话用户名更新用户名。

$id=$_GET['id'];

 $sql="INSERT INTO c_archive_table(tech, eng, dr) SELECT tech, eng, dr FROM   `Com` WHERE `id`='$id'";
 $sql_user = "INSERT INTO  c_archive_table('','user','$_SESSION['username']') WHERE `id`='$id'";
 $sql_delete="DELETE FROM `Com` WHERE `id`='$id'";

所以移动归档和删除工作但是将用户会话添加到用户列不起作用。

2 个答案:

答案 0 :(得分:2)

它不会是INSERT,而是UPDATE

 $sql_user = "UPDATE c_archive_table SET 'user'='".$_SESSION['username']."' WHERE `id`='$id'";

user列替换为$_SESSION名称进入的列名

答案 1 :(得分:1)

$sql = new mysqli(MYSQL_HOST, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE);

// 1. Find the row in the existing table and get the contents
$query1 = '
SELECT
   `tech`,
   `eng`,
   `dr`
FROM `Cnom`
WHERE
   `id` = "'.$sql->real_escape_string($_GET['id']).'"
;';
   // Use real_escape_string to sanitize anything that the user could modify
$result1 = $sql->query($query1) or die ("<pre>Query failed:\n$query1</pre>");
   // die()ing with the query is always helpful for debugging
$row1 = $result1->fetch_assoc() or die ("<pre>No result returned for id {$_GET['id']}</pre>");

// 2. Insert the contents into the archive
$query2 = '
INSERT INTO `c_archive_table` (
   `user`,
   `tech`,
   `eng`,
   `dr`
)
VALUES (
   "'.$sql->real_escape_string($_SESSION['username']).'",
   "'.$sql->real_escape_string($row1['tech']).'",
   "'.$sql->real_escape_string($row1['eng']).'",
   "'.$sql->real_escape_string($row1['dr']).'"
);';
$sql->query($query2) or die ("<pre>Query failed:\n$query2</pre>");

// 3. Delete from the original table
$query3 = '
DELETE FROM `Cnom`
WHERE
   `id` = "'.$sql->real_escape_string($_GET['id']).'"
;';
$sql->query($query3) or die ("<pre>Query failed:\n$query3</pre>");

这可能是一个好的开始,基于我猜你的数据库表看起来像。

顺便说一句,我建议在诊断MySQL问题时,在这个例子中你喜欢这样做:用缩进在多行写下你的查询;并使用PHP的die (string)结构来打印产生错误的查询。然后,您可以清楚地查看查询以查看任何明显的语法错误,MySQL也可以告诉您错误发生在哪一行。您还可以将die() d查询复制并粘贴到phpMyAdmin。


更重要的是,这可能不是正确的设置。你应该拥有的是一个带有archived列的表,而不是两个带有几乎相同信息的冗余表。然后你只需将archived更改为布尔值(true),并在您尝试访问它时检查它。

例如(伪代码):

if (accessing_all_records) {
   // Access all records that aren't archived
   $query = '
SELECT
   *
FROM `Cnom`
WHERE
   `archived` = 0
;';
}

if (inserting_new_record) {
   // Create a new record and set archived to 0 by default (better yet, give it a default value)
   $query = '
INSERT INTO `Cnom` (
   `field_1`,
   ...,
   `archived`
)
VALUES (
   value_1,
   ...,
   0
);';
}

if (archiving) {
   // Update the record and set the archived value to 1
   $query = '
UPDATE `Cnom`
SET
   `archived` = 1
WHERE
   `id` = id
;';
}