0

我目前正在尝试为我的网站上的用户个人资料制作更新页面,并且。如果用户更新了他们的所有信息,下面的代码可以正常工作,但是如果他们遗漏了一个字段,它会在表中插入一条空白记录。

如果用户将字段留空,目前为了解决这个问题,我将空白字段替换为$_SESSION['user']['field']它只是重新插入当前数据。

这是我现在的php

<?php
session_start();
if($_SESSION['uname']) {
$logged_in=true;
} else {
$logged_in=false;
}
include_once("../connection/conn.php");

if(isset($_POST['update'])) {

if($_POST['firstname']){ $firstname = $_POST['firstname']; }
else { $firstname = $_SESSION['uname']['firstname']; }

if($_POST['lastname']){ $lastname = $_POST['lastname']; }
else { $lastname = $_SESSION['uname']['lastname']; }

if($_POST['email']){ $email= $_POST['email']; }
else { $email = $_SESSION['uname']['email']; }

$id = $_SESSION['uname']['id'];

$query = "UPDATE users SET firstname=?, lastname=?, email=? WHERE id=? ";

$results = $condb->prepare($query);

$results->execute(array($firstname, $lastname,$email,$id));

if($results) {
echo "updated";
}
}

?>
4

2 回答 2

2
UPDATE `tablename`
SET `field` = IF(? <> '', ?, `field`)
WHERE ...

这将检查空条目的工作替换为 MySQL,并且字段使用其先前的值而不是空值。您需要将该值传递给execute()两次才能使其正常工作。它与您所做的基本相同,但无需将值存储在您的 PHP 会话中。

使用这种方法,您的更新代码将如下所示:

/*
  This block is no longer necessary
if($_POST['firstname']){ $firstname = $_POST['firstname']; }
else { $firstname = $_SESSION['uname']['firstname']; }

if($_POST['lastname']){ $lastname = $_POST['lastname']; }
else { $lastname = $_SESSION['uname']['lastname']; }

if($_POST['email']){ $email= $_POST['email']; }
else { $email = $_SESSION['uname']['email']; }
*/

$query = "
  UPDATE `users`
  SET
    `firstname` = IF(? <> '', ?, `firstname`),
    `lastname` = IF(? <> '', ?, `lastname`),
    `email` = IF(? <> '', ?, `email`)
  WHERE `id` = ?
";

$results = $condb->prepare($query);

$results->execute(array(
  $_POST['firstname'], $_POST['firstname'],
  $_POST['lastname'], $_POST['lastname'],
  $_POST['email'], $_POST['email'],
  $_SESSION['uname']['id']
));

您现有的代码会阻止用户0自己输入一个单曲,而这不会 - 您可能还想为此添加一个检查。

于 2012-08-01T06:52:31.333 回答
0

您必须提供字段验证

if($firstname!="" && $lastname!="" && $email!=""){

  $query = "UPDATE users SET firstname=?, lastname=?, email=? WHERE id=? ";
  $results = $condb->prepare($query);
  $results->execute(array($firstname, $lastname,$email,$id));
  if($results) {
   echo "updated";
  }
}
else{
  echo "Fill all the fields!";
}
于 2012-08-01T06:41:08.147 回答