2

Here's my table:

id | name  | check
------------------
1  | Paul  | no
2  | Bob   | no
3  | Tom   | no

id is an INT, name and check TEXT.

Here's the script:

<?php
include("database.php");

$dbc= new dbClass();
$query = $dbc->dbRunSql("select * from names order by name");

while ($result = mysql_fetch_array($query)){ ?>
  <form method="POST" action="">
  <input type="checkbox" name="names[]" value="yes"/><?php echo $result['name'];
} ?>

<br>
<input name="submit" type="submit" />
</form> <?php

if(isset($_POST["submit"])){
  foreach ($_POST['names'] as $entry){
    $dbc= new dbClass();
    $query = $dbc->dbRunSql("update `names` set `check`='$entry';");
  }
}
?>

This script works but updates all the rows, not the ones I check.

I have 2 questions:

1) What should I change to make it work correctly? (updating the ones that I check)
2) The ones that I don't check, how to update them in the "check" column as "no"

I hope you could understand what I meant.

Thanks in advance.

1
  • 1
    As a side note, store 'check' as a binary figure: 0 for 'not checked' and 1 for 'checked'. Saves you a little DB space. Commented Oct 2, 2011 at 22:25

1 Answer 1

3

You should do a WHERE clause in your query. What you currently have updates every row because MySQL doesn't know what to update. This is a fix for that problem:

$query = $dbc->dbRunSql("update `names` set `check`='$entry' WHERE id='$id';");

$id needs to be defined by you correctly, with something like this:

<input type="checkbox" name="names[<?php echo $result['id']; ?>" value="yes"/>

and then in your foreach loop:

foreach ($_POST['names'] as $id => $entry){
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! That did the trick. Just one edit for future readers, you missed a bracket in "names[<?php echo $result['id']; ?>". Thanks again!

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.