我正在尝试创建一个更新PHP函数,它正在工作,但是我遇到了一些问题,我收到了来自表单的用户名电子邮件和密码,但是如果用户将其中一个或两个留空,我想更新只有一个不是空白的,例如“ pass”,但是当我这样做时,其他2个字段在数据库中都更新为空或为空白,我的代码有什么错误?
<?php
session_start();
$id = $_SESSION['user_id'];
$email = $_POST['emailAlter'];
$nome = $_POST['nameAlter'];
$pass = $_POST['passAlter'];
$con = mysqli_connect("localhost", "root", "", "smarttime");
$query = mysqli_query($con,"UPDATE users SET use_name = '$nome', use_email = '$email', use_pass = '$pass' WHERE use_id = '$id'");
$test = mysqli_query($con,"SELECT * from users");
$row = mysqli_fetch_array($test);
if (!$con) {
die('Erro de Acesso à BD' . mysqli_connect_error());
}
if(!isset($email) || trim($email) == '')
{
$email = mysqli_query($con,"SELECT use_email from users where use_id ='$id");
$query = mysqli_query($con,"UPDATE users SET use_name = '$nome', use_email = '$email', use_pass = '$pass' WHERE use_id = '$id'");
}
if(!isset($nome) || trim($nome) == '')
{
$nome = mysqli_query($con,"SELECT use_name from users where use_id ='$id");
$query = mysqli_query($con,"UPDATE users SET use_name = '$nome', use_email = '$email', use_pass = '$pass' WHERE use_id = '$id'");
}
if(!isset($pass) || trim($pass) == '')
{
$nome = mysqli_query($con,"SELECT use_pass from users where use_id ='$id");
$query = mysqli_query($con,"UPDATE users SET use_name = '$nome', use_email = '$email', use_pass = '$pass' WHERE use_id = '$id'");
}
$query;
header('Location: logged.php');
exit();
?>
答案 0 :(得分:2)
如果我假设用户ID始终存在并且有效,那么您可以构建如下查询:
globals()[name]
因此,查询取决于输入的存在。
答案 1 :(得分:0)
事情是先更新然后检查条件。更新之前必须检查所有变量
<?php
session_start();
$id = $_SESSION['user_id'];
$email = $_POST['emailAlter'];
$nome = $_POST['nameAlter'];
$pass = $_POST['passAlter'];
$con = mysqli_connect("localhost", "root", "", "smarttime");
$query = "UPDATE users SET ";
if (!$con) {
die('Erro de Acesso à BD' . mysqli_connect_error());
}
if(isset($email) && trim($email) != '')
{
$query .= "use_email = '$email' ";
}
if(isset($nome) && trim($nome) != '')
{
$query .= "use_name = '$nome' ";
}
if(isset($pass) && trim($pass) != '')
{
$query .= "use_pass = '$pass' ";
}
mysqli_query($con,$query." WHERE use_id = '$id'");;
header('Location: logged.php');
exit();
?>