php – update database table with button-ThrowExceptions

Exception or error:

I’m trying to update my databse with a button to set the visibility from 0 to 1. There isn’t any syntax error but for some reason it doesn’t change the database value. My database example: (visibility is tinyint with default 0 value)

 id-   name-   visibility
---------------------------
1   -   John    -    1
---------------------------
2   -   Ben     -    1
---------------------------
3   -   Terry   -    0
---------------------------

and my php code:

<?php
$sql = "SELECT id, name, image, description, address, phone, phone2, email, job, visibility FROM cards";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));          
while( $record = mysqli_fetch_assoc($resultset) ) {
?>
<div class="col-md-4" <?php if ($record['visibility'] == 1) echo " style='display: none';"; ?>>I want this to be hidden here</div>

<button type="button" class="btn btn-success" name="update">Accept</button>
<?php

if(isset($_POST['update'])){
$allowed = mysqli_query($conn," UPDATE cards SET visibility = '1' WHERE id = '$id' ");
}
?>
//html stuff here
 <?php }
      ?> 
How to solve:

You have to wrap your button into a <form> and set its type to submit. Furthermore you need to pass the records id with it. Try this example:

<?php

$sql = "SELECT id, name, image, description, address, phone, phone2, email, job, visibility FROM cards";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));          
while( $record = mysqli_fetch_assoc($resultset) ) { ?>

  <div class="col-md-4" <?php if ($record['visibility'] == 1) echo " style='display: none';"; ?>>

    Record name: <?php echo $record['name']; ?>
    <form action="" method="POST">
      <input value="<?php echo $record['id']; ?>" name="id">
      <button type="submit" class="btn btn-success" name="update">Set visibile</button>
    </form>

  </div>

<?php } ?> 

<?php
if(isset($_POST['update'])){
  $id = $_POST['id'];
  $allowed = mysqli_query($conn," UPDATE cards SET visibility = '1' WHERE id = '$id' ");
}
?>

If you get this to work, you should search about prepared statements.

Leave a Reply

Your email address will not be published. Required fields are marked *