Php Not updating

I'm new to programming but I'm sure there is a simple solution: When I try to use this code, I get no errors but the database is not updating. I am having no trouble connecting to the DB. I have also tried variations of quotes. The update code works in phpmyadmin but not on the page. I am trying to update the information entered onto a form upon submission

    <?php
    if(isset($_POST['submit'])){
    $dbhost = 'localhost';
    $dbuser = 'dbuser';
    $dbpass = 'dbpass';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass);

      $mon_am = $_POST['mon_am'];
       $sql = "UPDATE `mydatabase` 
       SET `mon_am` = $mon_am
      WHERE `id` = 1";
           } 
    mysql_close($conn);
?>

<!DOCTYPE html>
    <html>
    <head>
        <title>title</title>
    </head>
    <body>
        <form method="POST" action="mon_am.php">
            <input type="text" Name="mon_am">
            <input type="submit" name="submit">
    </form>
    </body>
    </html>

2 answers

  • answered 2018-05-16 06:12 phoe

    you must select your db after connect. Use mysql_query for executing your sql.

    <?php
        ...
        $conn = mysql_connect($dbhost, $dbuser, $dbpass);
        $selectDb = mysql_select_db("yourDatabaseName");
        $mon_am = $_POST['mon_am'];
        $sql = "UPDATE `yourTableName` SET `mon_am` = $mon_am WHERE `id` = 1";
        $query = mysql_query($sql);
        mysql_close($conn);
    ?>
    

  • answered 2018-05-16 06:17 sam28

    That should do the trick. Part of the credit goes to @Nigel Ren who pointed the fact that you forgot to execute the query AND that you should use mysqli or PDO.

    Also note the use of prepared statement and parameters binding, which prevent the end user to post some nasty sql that will be injected in your query through the $mon_am variable.

    <?php
    
    if(isset($_POST['submit']))
    {
    
      $dbhost = 'localhost';
      $dbuser = 'dbuser';
      $dbpass = 'dbpass';
      $dbname = 'YOURDBNAME'; //Change YOURDBNAME with the actual name of your database
    
      $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
      $sql = 'UPDATE mydatabase SET mon_am = ? WHERE id = 1;' //mydatabase must be a table, not the actual database name !!
      $stmt = $conn->prepare($sql);
      $stmt->bind_param('s', $_POST['mon_am']); //First parameter defines the data type
      $stmt->execute();
    
      echo $stmt->affected_rows; // This is only to show if the data was updated. You can delete it once your code is working
    
      $stmt->close();
      $conn->close();
    }
    
    ?>
    
    <!DOCTYPE html>
    <html>
    <head>
        <title>title</title>
    </head>
    <body>
        <form method="POST" action="mon_am.php">
            <input type="text" Name="mon_am">
            <input type="submit" name="submit">
    </form>
    </body>
    </html>