Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update database data with submit button

I want to update a database with new data so that when you put your text in a text-box and then click the submit button, the data will be sent to the database, with a specific id. All I want to send is brightness, with the code below. When I write something like this, and I run it, I receive a 403 error: Access forbidden. How can I fix this?

<?php
   function updater($value,$id){
// Create connection
   $conn = new mysqli( 'localhost' , 'user_name' , '' , 'data_base_name' );
// Check connection
   if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
   }
   $sql = "UPDATE table_name SET name=$value WHERE id=$id";
   if ($conn->query($sql) === TRUE) {
       echo "Record updated successfully";
   } else {
       echo "Error updating record: " . $conn->error;
   }
//$conn->close();
}
?>

<!DOCTYPE html>
<html>
<header>
</header>
<body>
    <form action="<?php updater($_POST['name'],1); ?>" method="post" style="height:50px;width:50px;">
        <input type="text" name="name" /><br><br>
        <input type="submit" /><br/>
    </form>
</body>
</html>
like image 477
Soroosh Noorzad Avatar asked Apr 20 '15 23:04

Soroosh Noorzad


1 Answers

You need to put the URL inside the action attribute that does the form processing, not the function:

action="<?php updater($_POST['name'],1); ?>"  // not this
action="<?php echo $_SERVER['PHP_SELF']; ?>" // path to this page

If this is on the same page, you can just omit it or use $_SERVER['PHP_SELF'], then catch the form submission. Inside that process, then invoke your custom function.

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $value = $_POST['name'];
    $id = 1;

    updater($value, $id);
}

An easy fix would be just to quote the string inside it:

$sql = "UPDATE table_name SET name='$value' WHERE id=$id";

But this is open to SQL injection, another way to do safer queries is to prepare them:

function updater($value,$id) {
    // Create connection
   $conn = new mysqli( 'localhost' , 'user_name' , '' , 'data_base_name' );
    // Check connection
   if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
   }
   $sql = "UPDATE table_name SET name = ? WHERE id= ?";
   $update = $conn->prepare($sql);
   $update->bind_param('si', $value, $id);
   $update->execute();
   if ($update->affected_rows > 0) {
       echo "Record updated successfully";
   } else {
       echo "Error updating record: " . $conn->error;
   }
}
like image 146
Kevin Avatar answered Oct 20 '22 08:10

Kevin