0

This is in a php webpage

I have a link coming in as www.example.com/add_new.php?code=1234[]&code=4321[]&code=4263[]&attend=1 I need to update the database for code mark attend as attend="1" I can get it to work if I just have one. But when I have more than one can I loop this to edit all values?

$codes = $_GET['code'];
foreach ($codes as $code) {
$sql = "UPDATE guests SET attend='$isattend' WHERE code=$add";
}

what is the correct syntax for this?

Right Now it only applies the last on code=4263[] and marks 4263 as attend=1 but I need foreach

Thanks.

Sammy7
  • 364
  • 6
  • 21
  • why don't you try it? right after you read http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php Otherwise, enjoy having your server pwn3d. – Marc B Nov 19 '15 at 19:54
  • Why not create a string that you have concatenated from the $_GET['code']? That way you don't have to keep accessing the DB – michaelp Nov 19 '15 at 19:57

2 Answers2

2

With query string like ?code=1234&code=4321&code=4263&attend=1 your code value will be 4263. Cause previous value is overwritten by the following. For passing several codes in a query string you should use []:

?code[]=1234&code[]=4321&code[]=4263&attend=1

Then in $_GET['code'] you will have an array:

$codes = $_GET['code'];
// also you can check if $codes is array with `is_array` function
foreach ($codes as $code) {
    // do some database related stuff
    $sql = "UPDATE guests SET attend='$isattend' WHERE code=$add";
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
2

You're on the right track. If you have an array of items that you want to update, you would loop over them and execute an update query. There's a lot of things in your response that makes me think you should take a step back and review the basics.

First, a foreach loop looks something like this:

    foreach ($items as $item) {
        //do something
    }

Next, you really really don't want to write SQL queries like you're doing. It's a bad idea because people can take advantage of your code and attack you via SQL Injection

To prevent this, you can use a library that comes with PHP called PDO: http://php.net/manual/en/book.pdo.php

You will use something called a prepared statement that will let you design an SQL query and then inject values into it, and it helps prevent all of the scary injection attacks. For example, yours might look like

$stmt = $pdo->prepare("UPDATE guests SET attend=:attend WHERE code=:code");
$stmt->bindParam(':attend', $attend);
$stmt->bindParam(':code', $code);
$stmt->execute();

I'll leave it up to you to figure out how to implement this advice. Good luck!