0

I'm trying to give a default value if the user submit an empty value like [{"photourl":""}] using php and mysql query. I'm not really familiar with backend so i'm not sure my code is correct or not.

<?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;
}
?>

Then i tried the API using postman, the body looks like this [{ "huffid":"newuser", "dob":"121212", "gender":"male", "country":"singapore", "city":"singapore", "photourl": "" }] From the frontend, if the user doesn't give any photo the photourl will empty just like what i sent using postman. The photourl in database column also emoty. Can anyone help, please?

1 Answer 1

2

You need to assign the default value before you put it into $query. Statements execute in order, you can't refer to a value until after you assign it.

<?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;
}
?>

You should also learn to use prepared queries rather than substituting strings into SQL.

Sign up to request clarification or add additional context in comments.

1 Comment

For proper coding better you put if(empty(trim($dt[0]["photourl"]==""))) to replace if($dt[0]["photourl"]=="") because sometimes user keyin spacebar..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.