PHP Mysql,如果用户提交为空,则指定默认值

时间:2018-06-12 01:36:58

标签: php mysql

如果用户使用php和mysql查询提交类似[{"photourl":""}]的空值,我试图提供默认值。我对后端并不熟悉,所以我不确定我的代码是否正确。



<?php
function profile_put($dt) 
{
	$query="update personal set fullname='".$dt[0]["name"]."', dob='".$dt[0]["dob"]."', 
	gender='".$dt[0]["gender"]."', country='".$dt[0]["country"]."', city='".$dt[0]["city"]."', photourl='".$dt[0]["photourl"]."',
	lastupdate='15 minutes', about='', website='' 
	where huffid='".$dt[0]["huffid"]."';";

	if($dt[0]["photourl"]=="")
		{
			$dt[0]["photourl"]='https://i.imgur.com/KbHbcqV.png';
		}

	return $query;
}
?>
&#13;
&#13;
&#13;

然后我尝试使用邮递员的API,身体看起来像这样 [{ "huffid":"newuser", "dob":"121212", "gender":"male", "country":"singapore", "city":"singapore", "photourl": "" }] 从前端开始,如果用户没有提供任何照片,photourl将会像我使用邮递员发送的那样清空。数据库列中的photourl也是情绪化的。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您需要在之前将默认值分配到$query。语句按顺序执行,在分配之前,您无法引用值。

<?php
function profile_put($dt) 
{
    if($dt[0]["photourl"]=="")
    {
        $dt[0]["photourl"]='https://i.imgur.com/KbHbcqV.png';
    }

    $query="update personal set fullname='".$dt[0]["name"]."', dob='".$dt[0]["dob"]."', 
    gender='".$dt[0]["gender"]."', country='".$dt[0]["country"]."', city='".$dt[0]["city"]."', photourl='".$dt[0]["photourl"]."',
    lastupdate='15 minutes', about='', website='' 
    where huffid='".$dt[0]["huffid"]."';";

    return $query;
}
?>

您还应该学会使用准备好的查询,而不是将字符串替换为SQL。