0

I want to do multiple query in one statement here is my code and it's not working.

$stmt = $mysqli->prepare("UPDATE  menu SET DESCRIPTION= ('$txt1'), VISIBLE=('$ckHOME1')
where id='1';
UPDATE  menu SET DESCRIPTION= ('$txt1'), VISIBLE=('$ckHOME1') where id='1';
UPDATE  menu SET DESCRIPTION= ('$txt2'), VISIBLE=('$ckHOME2') where id='2';
UPDATE  menu SET DESCRIPTION= ('$txt3'), VISIBLE=('$ckHOME3') where id='3';
UPDATE  menu SET DESCRIPTION= ('$txt4'), VISIBLE=('$ckHOME4') where id='4';");
$stmt->execute();
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
4
  • php.net/manual/en/mysqli.multi-query.php Commented Jan 6, 2014 at 6:40
  • Why are you doing the first update twice? Commented Jan 6, 2014 at 6:45
  • And if you're using mysqli_prepare, why are you interpolating variables instead of using placeholders? Commented Jan 6, 2014 at 6:45
  • I'm wondering wtf the checks if(!mysqli_query...) are doing :D Commented Jan 6, 2014 at 6:46

2 Answers 2

4

Alternatively, you can also make it as one UPDATE statement using CASE.

UPDATE  menu 
SET     
        DESCRIPTION = CASE WHEN id = 1 THEN '$txt1'
                            WHEN id = 2 THEN '$txt2'
                            WHEN id = 3 THEN '$txt3'
                            WHEN id = 4 THEN '$txt4'
                    END,
        VISIBLE = CASE WHEN id = 1 THEN '$ckHOME1'
                            WHEN id = 2 THEN '$ckHOME2'
                            WHEN id = 3 THEN '$ckHOME3'
                            WHEN id = 4 THEN '$ckHOME4'
                    END
where   id IN (1, 2, 3, 4)
Sign up to request clarification or add additional context in comments.

Comments

3

You have to use mysqli_multi_query() to execute multiple queries in one call.

But there's no need to do multiple queries for what you're doing:

UPDATE menu 
SET description = 
        CASE id
            WHEN 1 THEN '$txt1'
            WHEN 2 THEN '$txt2'
            WHEN 3 THEN '$txt3' 
            WHEN 4 THEN '$txt4'
        END,
    visible = 
        CASE id
            WHEN 1 THEN '$ckHOME1'
            WHEN 2 THEN '$ckHOME2'
            WHEN 3 THEN '$ckHOME3' 
            WHEN 4 THEN '$ckHOME4'
        END
WHERE id IN (1, 2, 3, 4);

2 Comments

@user2990463 You call it the same way you call mysqli_query.
Thank you very much Gentlemen, it ROCKS!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.