-3

I am trying to send the input from a user on a form to my database and I am not sure why it isn't going. I have the sql going to my database and all the correct IDs are met so I think it should be working but I am missing something. It may be something in the if(isset part of the code but most likely something in the dropdown portion. Any help would be appreciated.

<?php
    session_start();
    if(!isset($_SESSION["sess_user"])){
        header("location:login.php");
    } else {
    ?>   
<!doctype html>
<html>
  <head>
  <link rel="stylesheet" href="siteCSS.css">
    <meta charset="UTF-8">
    <title>Recommendations</title>    
  </head>
  <body>   
    <div id="wrapper">    
    <header>
    <h2>Welcome <?=$_SESSION['sess_user'];?>! <a href="logout.php">Click to Logout</a></h2>
        <nav>
            <ul>
                <li><a href="member.php">Home</a></li>
                <li><a href="committees.php">Committees</a></li>
                <li><a href="recommendations.php">Recommendations</a></li>
                <li><a href="voting.php">Voting</a></li>
            </ul>
        </nav>
    </header>    
    <h1>Recommendations Main Page</h1>
       <form action = "recommendations.php" method="POST">
         <br>
  <br>                 
 <label>Recommendation ID: </label>         
 <select name="recommended" required>   
         <?php   
         $conn = new mysqli('localhost', 'root', 'root', 'mydb');    
         if ($conn->connect_error) {    
           die("Failed: " . $conn->connect_error);    
         }
         $UserID = $_SESSION['sess_userID'];    
         $selectsql = "select * from user";    
         echo '<option value="" disabled selected>Choose option</option>';    
         $result = $conn->query($selectsql);    
         if ($result->num_rows > 0) {    
           while($row = $result->fetch_assoc()) {    
             echo '<option value=\"'.$row["UserID"].'">'.$row["UserName"].'</option>';            
           }    
         }              
         ?>    
         </select>
  <br>
  <br>    
    <label>Committee ID: </label>
 <select name="committee" required>   
         <?php    
         $conn = new mysqli('localhost', 'root', 'root', 'mydb');    
         if ($conn->connect_error) {    
           die("Failed: " . $conn->connect_error);   
         }          
         $selectsql = "select * from committee";   
         echo '<option value="" disabled selected>Choose option</option>';    
         $result = $conn->query($selectsql);
         if ($result->num_rows > 0) {
           while($row = $result->fetch_assoc()) {
             echo '<option value=\"'.$row["CommitteeID"].'">'.$row["CommitteeName"].'</option>';
           }
         }
         ?>
         </select>
    <br>
    <br>
    <label>Description (Why they should be recommended):</label>
    <input type="text" size = 25 class="textbox" id="RecommendationDescription" name="RecommendationDescription" required>
    <br>
    <br>
    <button type="submit" name="submit">Submit</button>
  <?php
  if(isset($_POST["submit"])){
    if(!empty($_POST['RecommendationDescription'])) {
      $recomuser=$_POST['RecommendationID'];
      $recommddesc=$_POST['RecommendationDescription'];
      $recomcommittee=$_POST['CommitteeID'];
      $conn = new mysqli('localhost', 'root', 'root', 'mydb');
      if ($conn->connect_error) {
        die("Failed: " . $conn->connect_error);
      }
        $userID = $_SESSION['sess_userID'];
        $sql="INSERT INTO mydb.recommendation(RecommendatedID, RecommendationDescription, RecommendationSubmissionDate, UserID, CommitteeID) VALUES('$recomuser', '$recommddesc', CURRENT_TIMESTAMP, '$userID', '$recomcommittee')";
        $result = $conn->query($sql);
        if($result){
          echo "Recommendation Successfully Created";
        } else {
          echo "Failure!";
        }
    }
  }
  ?>    
</form>
  <main>
  </main>
  </div>
  </body>
</html>
<?php
$variable=$_POST['RecommendationName'];
echo $variable;
}
?>
  • 1
    Welcome to Stack Overflow. I'd recommend reading [how to ask](https://stackoverflow.com/help/how-to-ask) for some pointers on writing questions, with the emphasis on the part about [minimal, reproducible examples](https://stackoverflow.com/help/minimal-reproducible-example). We can't run your code to debug it, so you need to do it for us. Check PHP's error log and use variable dumping to narrow the problem down to a specific piece of code. – El_Vanja Apr 26 '21 at 16:02
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Apr 26 '21 at 16:02
  • Can you please clarify, what doesn't work? You say, the data you send has appeared in the database, so what you're looking for is working. – Peter Apr 26 '21 at 16:28

1 Answers1

1

There are multiple things wrong, your array keys do not match your select names, which is answer to your question. I would like to mention that you should separate PHP code from HTML, you don't necessary have to, but it's good practice and use prepared statements to prevent sql injection. I had mood to do a little code review so here it is (take it with a grain of salt):

<?php
session_start();
if(!isset($_SESSION["sess_user"])){
    header("location:login.php");
    exit; // you should call exit here !
}

// the PHP stuff

// store session values to variables
// in case you change their values during code execution which would cause unnecesary behavior
$UserName = $_SESSION['sess_user'];
$UserID = $_SESSION['sess_userID'];

// mysqli error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// following line should be called only once per code !
$conn = new mysqli('localhost', 'root', 'root', 'mydb');

$result = $conn->query('select * from user');
$userList = $result->fetch_all(MYSQLI_ASSOC);
$result = $conn->query('select * from committee');
$committeList = $result->fetch_all(MYSQLI_ASSOC);

$flashMessage = '';
$validationErrors = [];
if(isset($_POST["submit"])){
    // prepare variables for each post value
    $recomuser = (int)($_POST['RecommendationID'] ?? 0); // note: the "??" operator act like: (isset(left_side)?left_side:right_side)
    $recomcommittee = (int)($_POST['CommitteeID'] ?? 0);
    $recommddesc = $_POST['RecommendationDescription'] ?? '';
      
    // server side validation
    if(!$recomuser)
        $validationErrors['RecommendationID'] = 'Recommendation is required.';
    if(!$recomcommittee)
        $validationErrors['CommitteeID'] = 'Committee is required.';
    if(empty($recommddesc))
        $validationErrors['RecommendationDescription'] = 'Description is required.';
        
    // only when the validation pass
    if(!$validationErrors){
        // prepared statement to prevent sql injection
        // mydb.recommendation can simply be recommendation because you selected the DB in, attribution to @Dharman in comment
        $stmt = $conn->prepare('INSERT INTO recommendation(RecommendatedID, RecommendationDescription, RecommendationSubmissionDate, UserID, CommitteeID) VALUES(?, ?, CURRENT_TIMESTAMP, ?, ?)');
        $stmt->bind_param('isii', $recomuser, $recommddesc, $UserID, $recomcommittee);
        $stmt->execute();
        $flashMessage = 'Recommendation Successfully Created';
    }
}    

// here you can see the advantage of doing all the PHP stuff before HTML,
// because we now can use results and affect HTML

// the HTML part
?>   
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" href="siteCSS.css">
    <meta charset="UTF-8">
    <title>Recommendations</title>    
  </head>
  <body>   
    <div id="wrapper">    
        <header>
            <h2>Welcome <?=$UserName?>! <a href="logout.php">Click to Logout</a></h2>
                <nav>
                    <ul>
                        <li><a href="member.php">Home</a></li>
                        <li><a href="committees.php">Committees</a></li>
                        <li><a href="recommendations.php">Recommendations</a></li>
                        <li><a href="voting.php">Voting</a></li>
                    </ul>
                </nav>
            </header>    
            <h1>Recommendations Main Page</h1>
<?php 
if($flashMessage)
    echo '<p class="flash">'.$flashMessage.'</p>';
?>
            <form action = "recommendations.php" method="POST">
                <br>
                <br>                 
                <label>Recommendation ID: </label>       
                <select name="RecommendationID" required>
                    <option value="" disabled selected>Choose option</option>
<?php 
foreach($userList as $row) {
                        // you had unnecesary escape here    
    echo '<option value="'.$row["UserID"].'">'.$row["UserName"].'</option>';            
}              
?>    
                </select>
<?php
if(isset($validationErrors['RecommendationID'])){
    echo '<p class="form-error">'.$validationErrors['RecommendationID'].'</p>';
}
?>
                <br>
                <br>    
                <label>Committee ID: </label>
                <select name="CommitteeID" required>
                    <option value="" disabled selected>Choose option</option>  
<?php    
foreach($userList as $row) {
                        // again you had unnecesary escape here   
    echo '<option value="'.$row["CommitteeID"].'">'.$row["CommitteeName"].'</option>';
}
?>
                </select>
<?php
  if(isset($validationErrors['CommitteeID'])){
      echo '<p class="form-error">'.$validationErrors['CommitteeID'].'</p>';
  }
?>
                <br>
                <br>
                <label>Description (Why they should be recommended):</label>
                <input type="text" size = 25 class="textbox" id="RecommendationDescription" name="RecommendationDescription" required>
<?php
    if(isset($validationErrors['CommitteeID'])){
        echo '<p class="form-error">'.$validationErrors['CommitteeID'].'</p>';
    }
 ?>
                <br>
                <br>
                <button type="submit" name="submit">Submit</button>
            </form>
        </div>
    </body>
</html>
<?php
// better to not use the "?>" at the end of file to prevent unwanted white characters to print
Dharman
  • 30,962
  • 25
  • 85
  • 135
Kazz
  • 1,030
  • 8
  • 16
  • `mydb.recommendation` can simply be `recommendation` because you selected the DB in connection. – Dharman Apr 26 '21 at 17:27