scareware
scareware

Reputation: 23

PHP multiple if statements only doing last statement

I know similar questions have been asked a lot, and I have searched through and am unable to find an answer that fixes the problem I am having.

I have a form with multiple textareas that updates a mysql entry, and I would like PHP to make sure there is something in the textarea before updating the entry. This works when I only have one entry being updated, but when I do more than one at a time only the last one is updated. I tried using else if, and in that case only the first one is updated. How can I make it update all entries where text has been entered?

In my code the form input name matches the column name.

$value = $_POST['titleLeft'];
$value2 = $_POST['textLeft'];
$value3 = $_POST['imgName'];
$value4 = $_POST['titleRight'];
$value5 = $_POST['textRight'];

if (strlen($value) > 0){
    $sql = "UPDATE classesSpecial SET titleLeft = '$value' WHERE id = '1'";
}

if (strlen($value2) > 0){
    $sql = "UPDATE classesSpecial SET textLeft = '$value2' WHERE id = '1'";
}

if (strlen($value3) > 0){
$sql = "UPDATE classesSpecial SET imgName = '$value3' WHERE id = '1'";
}

if (strlen($value4) > 0){
    $sql = "UPDATE classesSpecial SET titleRight = '$value4' WHERE id = '1'";
}

if (strlen($value5) > 0){
    $sql = "UPDATE classesSpecial SET textRight = '$value5' WHERE id = '1'";
}

Upvotes: 2

Views: 71

Answers (3)

Mave
Mave

Reputation: 2516

It's because you keep on overwriting $sql. One solution would be to do this for each post request:

if((strlen($value) > 0) {
  $sql[] = "UPDATE classesSpecial SET titleLeft = '$value' WHERE id = 1";
}

$sql[] means you're adding values to an array, which you can later use to process all requests. Then, at the end of your script, you'll do this for executing your SQL:

foreach($sql as $query) {
  mysqli_query($db, $query)or die(mysqli_error($db));
}

Upvotes: 2

Manashvi Birla
Manashvi Birla

Reputation: 2843

You are using the same variable $sql everytime,

$value = $_POST['titleLeft'];
$value2 = $_POST['textLeft'];
$value3 = $_POST['imgName'];
$value4 = $_POST['titleRight'];
$value5 = $_POST['textRight'];

if (strlen($value) > 0){
    $sql1 = "UPDATE classesSpecial SET titleLeft = '$value' WHERE id = '1'";
}

if (strlen($value2) > 0){
    $sql2 = "UPDATE classesSpecial SET textLeft = '$value2' WHERE id = '1'";
}

if (strlen($value3) > 0){
$sql3 = "UPDATE classesSpecial SET imgName = '$value3' WHERE id = '1'";
}

if (strlen($value4) > 0){
    $sql4 = "UPDATE classesSpecial SET titleRight = '$value4' WHERE id = '1'";
}

if (strlen($value5) > 0){
    $sql5 = "UPDATE classesSpecial SET textRight = '$value5' WHERE id = '1'";
}

Upvotes: 2

Mangled
Mangled

Reputation: 329

You're overwriting the sql query with each if. you should also execute the command in the if statement.

Upvotes: 0

Related Questions