Please help with getting a textbox entry with submit button into a mysqli query

Hi Guys. Thanks for your help.sofar The search box is now working, and displays the whole class but after selecting the record, it only shows the row to update. I can sort of live with that, but after updating a record, it returns no records and the Submit button has to be clicked again to display the class and updated records. Not cool.

The other issue I’m having is trying to get the query to order by name.

$result = $mysqli->query(“SELECT * FROM data WHERE classroom = '”.$classroom."’ ORDER BY ‘.name’;") or die($mysqli->error);

//index.html

<?php require_once 'process.php'; ?> <?php if (isset($_SESSION['message'])): ?>
        <div class="alert alert-<?=$_SESSION['msg_type']?>">
            <?php 
                echo $_SESSION['message']; 
                unset($_SESSION['message']);
            ?>
        </div>
    <?php endif ?>
<?php ?> Home of English Reports = body { margin: 0; font-family: Arial, Helvetica, sans-serif; } .topnav { overflow: hidden; background-color: #008080; } .topnav a { float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover { background-color: #ddd; color: black; } .topnav a.active { background-color: #4CAF50; color: white; }
Class name:

<input type="submit" value="Submit">
<?php $resultcomment = $mysqli->query("SELECT EnglishComment FROM comments"); ?>
    <div class="container" align-content-center>
    <?php
    $classroom = (isset($_GET['classroom']) ? $_GET['classroom'] : null);
    $result = $mysqli->query("SELECT * FROM data WHERE classroom = '".$classroom."' ORDER BY '.name';") or die($mysqli->error);

    ?>
<!-- ************************************** End Connect DB ****************************************************  -->

<div class="row justify-content-center">
    <form action="process.php" method="POST">
        <input type="hidden" name="id" value="<?php echo $id; ?>">

        <div class="form-group">
            <h1><label><?php echo $name?></label></h1>
        </div>

        <form action="process.php" method="POST">
        <input type="hidden" name="id" value="<?php echo $id; ?>">

        <div class="form-group">
            <h3><label>PA Teacher's Comment</label></h3> <select name = "pacomment">
           <?php
                while($rows = $resultcomment-> fetch_assoc())
                {
                    $EnglishComment = $rows['EnglishComment'];
                    echo "<option value='$EnglishComment'>$name.$EnglishComment</option>";
                }
                ?></h2> 
            </select><br>
            <p>

        <div class="form-group">
        <?php 
        if ($update == true): 
        ?>
            <button type="submit" class="btn btn-info" name="update">Update</button>
        <?php else: ?>
            <!-- <button type="submit" class="btn btn-primary" name="save">Save</button> -->
        <?php endif; ?>
        </div>
    </form>

<!-- ************************************** Begin Setup Table Headers ***************************   -->        
        <div class="row justify-content-center">
            <table class="table" width = "20%" border = "5" cellpadding = "1";>
                <thead>
                    <tr>
                        <th><center>Action</center></th>
                        <th><center>ID</center></th>
                        <th>Name and Comment</th>
                    </tr>
                </thead>
                
<!-- ************************************** End Setup Classlist Table Headers ******************   -->

<!-- ****** Loop thru Every Record From $result Query Variable and get variables and echo each variable into the table rows  **********   -->
        <?php
            while ($row = $result->fetch_assoc()): ?>

        <tr>
                    <td>
                    <center><a href="index.php?edit=<?php echo $row['id']; ?>"
                        class="btn btn-info">Assess</a></center>                         
                    </td>
<!-- ************************************** Put data into Classlist table rows *************************   -->
                
                    <td><center><?php echo $row['studentid']; ?></center></td>
                    <td><?php echo $row['name']." ".$row['pacomment'] ?></td>
                    
        </tr>
              
        <?php endwhile; ?>  

            </table> <!-- *************** End of Classlist Table  ****************************************   -->

        </div> 

    </div>
    </div>
</body>

____process.php

<?php session_start();

$mysqli = new mysqli(“localhost”,“ray”,“password”,“reports”) or die(mysqli_error($mysqli));

$id = 0;
$update = false;
$name = ‘’;
$classroom = ‘’;

if (isset($_GET[‘edit’])){
$id = $_GET[‘edit’];
$update = true;
$result = $mysqli->query(“SELECT * FROM data WHERE id=$id”) or die($mysqli->error());
if(isset($result->num_rows) && $result->num_rows > 0) {
$row = $result->fetch_array();
$name = $row[‘name’];
$classroom = $row[‘classroom’];
$pacomment = $row[‘pacomment’];
}
}

if (isset($_POST[‘update’])){
$id = $_POST[‘id’];
$pacomment = $_POST[‘pacomment’];
$mysqli->query(“UPDATE data SET pacomment= ‘$pacomment’ WHERE id=$id”) or die($mysqli->error);

$_SESSION['message'] = "Record has been updated!";
$_SESSION['msg_type'] = "warning";

header('location: index.php');

}

You would use a prepared query, with only a ? place-holder in the sql query statement where the hard-coded value and the quotes are now, then supply the actual value that’s submitted from the form when the query gets executed.

Some other things you should be/not be doing -

  1. The search form should use method=‘get’ (which is the default if you leave the method attributed out of the form tag), since it is determining what will be displayed on the page.
  2. If it is not already, the search form should be on the same page that it submits to. To do this, just leave the action attribute out of the form tag.
  3. The search form should be ‘sticky’ and re-populate the form field(s) with any existing submitted data.
  4. Since you are selecting from existing values, you should instead use a select/option menu, then query for the existing data and dynamically build the option choices. This will help prevent typo mistakes and provide a better User eXperience (UX.) The user can only select a valid choice and doesn’t need to know/remember the format for the values.
  5. You should switch to the much simpler and more consistent PDO database extension.
  6. Don’t use or die(…) for error handling. Use exceptions instead and in most cases let php catch and handle the exception where php will use its error related settings to control what happens with the actual error information.
  7. Build the sql query statement in a php variable. This makes debugging easier and it separates the sql syntax as much as possible for the php code, reducing the amount of typo mistakes.
  8. List out the columns you are SELECTing in the query.
  9. Almost every query should have an ORDER BY … term so that the rows in the result set will be in a desired order.
  10. All inputs to a web page should be trimmed and validate before using them. Since the search input is required for the page to work, if it does not contain a non-empty value, that’s an error. You would setup and display an error message for the visitor telling them that they must select a classroom.
1 Like

I wrote a script in my Sandbox that uses the world database (I think it still can be found on the web for free) to goof around developing search in php. The script is old and some of the php is a little outdated, but the search principal itself is still pretty good in my opinion or at least give you a very good idea. Create a PHP Sandbox in my opinion is a good way to learn PHP and it helps when you need to refresh your memory. It might help you a little?

<?php
include 'lib/includes/connect/connect.php';

$db_options = [
    /* important! use actual prepared statements (default: emulate prepared statements) */
    PDO::ATTR_EMULATE_PREPARES => false
    /* throw exceptions on errors (default: stay silent) */
    , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    /* fetch associative arrays (default: mixed arrays)    */
    , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
];
if (filter_input(INPUT_POST, submit)) {

    $pdo = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=world;charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);

    $query = 'SELECT Name, CountryCode, District, Population FROM city WHERE CountryCode=:CountryCode ORDER BY District'; // Set the Search Query:

    $stmt = $pdo->prepare($query); // Prepare the query:

    $result = $stmt->execute([':CountryCode' => filter_input(INPUT_POST, countryCode)]); // Execute the query with the supplied user's parameter(s):
}
?>
<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Database Search</title>
        <link rel="stylesheet" href="lib/css/reset.css">
        <link rel="stylesheet" href="lib/css/grids.css">
        <link rel="stylesheet" href="lib/css/searchstyle.css">
    </head>
    <body>
        <div class="container seachBackground">
            <form id="searchForm" action="search.php" method="post">
                <label for="searchStyle">search</label>
                <input id="searchStyle" type="text" name="countryCode" value="" placeholder="Enter Country Code (For Exampe : USA)..." tabindex="1" autofocus>
                <input type="submit" name="submit" value="submit" tabindex="2">
            </form>
        </div>
        <div>
            <table id="search" summary="Cities Around the World!">
                <thead>
                    <tr>
                        <th scope="col">City</th>
                        <th scope="col">Country Code</th>
                        <th scope="col">District / State</th>
                        <th scope="col">Population</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ($result) {
                        while ($record = $stmt->fetch()) {
                            echo "<tr>";
                            echo '<td>' . $record->Name . "</td>";
                            echo '<td>' . $record->CountryCode . "</td>";
                            echo '<td>' . $record->District . "</td>";
                            echo '<td>' . $record->Population . "</td>";
                            echo "</tr>";
                        }
                    } 
                    ?>
                </tbody>
            </table>
        </div>

    </body>
</html>
1 Like

It appears that you have completely replaced the 1st post in this thread with a new problem and new code, more than once. There are two problems with that - 1) no one noticed that you are asking a new question, so, no one replied, 2) you have changed the meaning of the thread, so, none of the existing answers make any sense and are useless to anyone else who happens to find this thread.

If you have a new issue with the same code, add it to the end of the existing thread or start a completely new thread. Closing this thread.

Sponsor our Newsletter | Privacy Policy | Terms of Service