Donald
Donald

Reputation: 21

PHP MySQL making the values as a null

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]'");

Upvotes: 0

Views: 52

Answers (2)

vee
vee

Reputation: 38645

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.

Upvotes: 3

Let me see
Let me see

Reputation: 5094

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

Upvotes: 0

Related Questions