0

I have a PHP code that I'm struggling to figure out. Essentially I want the code to check if variables equals a certain value and if they do then I want the DB to update with NULL, if it doesn't equal the value then it will write the variable to the DB.

PHP

$noteid     = $_POST['id'];
$title      = $_POST['title'];
$content    = $_POST['content'];

if ($title == 'Type your title'){
    $title = null;
} else {
    $title = '$title';
}
if ($content == 'Type your note'){
    $content = null;
} else {
    $content = '$content';
}
$result = mysql_query("UPDATE notes SET title=$title, note=$content WHERE id='$noteid' AND uid = '$_SESSION[id]'");
3
  • What is the error you're running up against? Commented Dec 3, 2013 at 4:25
  • is your schema allowing null values? Commented Dec 3, 2013 at 4:26
  • You may consider using the placeholder attribute in your form. Commented Dec 3, 2013 at 4:28

2 Answers 2

3

I see two problems:

First is solution to what you're asking:

if it doesn't equal the value then it will write the variable to the DB.

Remove both of your else blocks because they are are not really required. You already have the $title set from the $_POST global. Secondly you are wrapping $title within single quotes, what that is going to do is make the content within single quotes literal, so $title won't get interpolated. For string interpolation you want to use double quotes, i.e. "$title" if you had to.

Your code updated after removing else blocks:

$noteid     = $_POST['id'];
$title      = $_POST['title'];
$content    = $_POST['content'];

if ($title == 'Type your title'){
    $title = null;
} 

if ($content == 'Type your note'){
    $content = null;
} 

Second problem is you are using deprecated mysql_ functions. You should consider switching to using mysqli or PDO.

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

Comments

0

change this

if ($title == 'Type your title'){
    $title = null;
} else {
    $title = '$title';
}
if ($content == 'Type your note'){
    $content = null;
} else {
    $content = '$content';
}

to

if ($title == 'Type your title'){
    $title = null;
} else {
    $title = $title;
}
if ($content == 'Type your note'){
    $content = null;
} else {
    $content = $content;
}`

or as Will Harrison said remove the else code and make it

if ($title == 'Type your title'){
        $title = null;
    } 
    if ($content == 'Type your note'){
        $content = null;
    } 
    `

1 Comment

or just take out the else.

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.