简体   繁体   中英

How to insert data from a mysql database into a table in a html file?

I am having trouble adding new rows with data from a mysql database. Right now it only works if the person submits new information, but what i am trying to do is that the data stays on the html file and when someone inputs new data it just updates the table in the html file to have this new data.

HTML code below

<form id="form" method="POST" action="db.php">
            <div class="form-row">

                <div class="form-group col-md-3">
                            <label for="Name">Full Name of the Person: </label>
                            <input type="text" class="form-control" name="Name" id="Name" value="">
                </div>

                  <div class="form-group col-md-3">
                    <label for="Date">Birthdate: </label>
                    <input type="text"  name="Date" class="form-control" id="Date" placeholder="MM/DD/YY" value="">
                  </div>

                <div class="form-group col-md-3">
                        <label for="personPN">Phone Number: </label>
                        <input type="text" class="form-control" name="personPN" id="personPN" placeholder="(XXX)XXX-XXXX" value="">
                </div>
                <div class="form-group col-md-3">
                        <label for="Sex">Sex</label>
                          <select name="Sex" class="form-control" id="Sex">
                              <option selected>Choose</option>
                              <option value="F">Female</option>
                              <option value="M">Male</option>
                              <option value="U">Unknown</option>
                          </select>
                </div>
                <div class="form-group col-md-3">
                        <label for="Weight">Weight</label>
                        <input type="text" class="form-control" name="Weight" id="Weight" placeholder="Weight lbs" value="">
                </div>
                <div class="form-group col-md-3">
                        <label for="Height">Height</label>
                        <input type="text" class="form-control" name="Height" id="Height" placeholder="X'X" value="">
                </div>
                <div class="form-group col-md-3">
                  <label for="ECN">Emergency Contact Name: </label>
                  <input type="text" class="form-control" name="ECN" id="ECN" value="">
          </div>
          <div class="form-group col-md-3">
                  <label for="ECPN">Emergency Contact Name Phone Number: </label>
                  <input type="text" class="form-control" name="ECPN" id="ECPN" placeholder="(XXX)XXX-XXXX" value="">
          </div>

            </div>

                  <div class="form-group">
                        <label for="MedicalIssues">Medical Issues</label>
                        <textarea class="form-control" id="MedicalIssues" name="MedicalIssues" rows="3"></textarea>
                    </div>

            </div>

            <div class="form-row">
                    <div class="form-group col-md-12 text-right">
                        <button id="button" type="submit" class="btn btn-primary">Submit</button>
                    </div>
                </div>
    </form>

ajax code

<script type="text/javascript">
              $(document).ready(function(){
                $('#form').on('submit', function (e){
                  e.preventDefault();
                  var formData = $(this).serialize();

                  $.ajax({
                    type: "POST",
                    url: 'db.php',
                    data: formData,
                    success: function(data){
                      $('#test').append(data);
                      alert ("Saved Data");
                    }
                  })
                });
              });

PHP code

$servername = "localhost";
$username = "username";
$password = "server";
$dbname = "password";


$conn = new mysqli($servername, $username, $password, $dbname);

if($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}


$name = mysqli_real_escape_string($conn, $_POST['Name']);
$date = mysqli_real_escape_string($conn, $_POST['Date']);
$personPN = mysqli_real_escape_string($conn, $_POST['personPN']);
$sex = mysqli_real_escape_string($conn, $_POST['Sex']);
$weight = mysqli_real_escape_string($conn, $_POST['Weight']);
$height = mysqli_real_escape_string($conn, $_POST['Height']);
$ecn = mysqli_real_escape_string($conn, $_POST['ECN']);
$ecpn = mysqli_real_escape_string($conn, $_POST['ECPN']);
$medicalIssues = mysqli_real_escape_string($conn, $_POST['MedicalIssues']);

$sql = "INSERT INTO db (Name, Birthdate, PhoneNumber, Sex, Weight, Height, EmergencyContactName, EmergencyContactNamePhoneNumber, MedicalIssues) VALUES('$name', '$date', '$personPN', '$sex', '$weight', '$height', '$ecn', '$ecpn', '$medicalIssues')";

if($conn->query($sql) == TRUE){
    echo "New Record created successfully";
}else {
    echo "<br>";
    echo "Error: " . $sql . "<br>" . $conn->error;
    echo "<br>";
}

$input = "SELECT `Id`, `Name`, `Birthdate`, `PhoneNumber`, `Sex`, `Weight`, `Height`, `EmergencyContactName`, `EmergencyContactNamePhoneNumber`, `MedicalIssues` FROM `db`";

$result = $conn-> query($input);


echo "<table class='table'>";
echo "<thead>";
echo "<tr>";
echo "<th scope='col'>ID #</th>";
echo "<th scope='col'>Name</th>";
echo "<th scope='col'>Birthdate</th>";
echo "<th scope='col'>Sex</th>";
echo "<th scope='col'>Weight</th>";
echo "<th scope='col'>Height</th>";
echo "<th scope=col'>Phone Number</th>";
echo "<th scope='col'>Emergency Contact Name</th>";
echo "<th scope='col'>Emergency Contact Name Phone Number</th>";
echo "<th scope='col'>Medical Issues</th>";
echo "</tr>";
echo "</thead>";


if($result-> num_rows > 0){
    while ($row = mysqli_fetch_array($result)){
        echo "<tbody>";
        echo "<tr>";
        echo "<th scope=". $row['id'] ."</th>"; 
        echo "<td>". $row['Name'] ."</td>";
        echo "<td>". $row['Birthdate'] ."<td>";
        echo "<td>". $row['PhoneNumber'] ."<td>";
        echo "<td>". $row['Sex'] ."<td>";
        echo "<td>". $row['Weight'] ."<td>";
        echo "<td>". $row['Height'] ."<td>";
        echo "<td>". $row['EmergencyContactName'] ."<td>";
        echo "<td>". $row['EmergencyContactNamePhoneNumber'] ."<td>";
        echo "<td>". $row['MedicalIssues'] ."<td>";


    }
    echo "</tr>";
}
echo "</table>";

$conn->close();

I have also tried just including (below, without the echo like a regular table) in the html file but then it does not put the information like how i have it above.

echo "<table class='table'>";
echo "<thead>";
echo "<tr>";
echo "<th scope='col'>ID #</th>";
echo "<th scope='col'>Name</th>";
echo "<th scope='col'>Birthdate</th>";
echo "<th scope='col'>Sex</th>";
echo "<th scope='col'>Weight</th>";
echo "<th scope='col'>Height</th>";
echo "<th scope=col'>Phone Number</th>";
echo "<th scope='col'>Emergency Contact Name</th>";
echo "<th scope='col'>Emergency Contact Name Phone Number</th>";
echo "<th scope='col'>Medical Issues</th>";
echo "</tr>";
echo "</thead>";

Im out of ideas so any help would be greatly appreciated.

Your code is to complicated, you need to separate database connection and include in your files. And separate your listing query and insert query from each other.

Define variables and initialize with empty values. these arrays will prevent you to having undefined errors in form.

$name = "";
$date = "";

First of all you need is to check if form submited

if($_SERVER["REQUEST_METHOD"] == "POST"){
// put all your insert code in here and do validating
}

in html part add field in value so when user return to form exist info will be there

<input type="text" name="name" class="form-control" value="<?php echo $name; ?>">
<input type="text" name="date" class="form-control" value="<?php echo $date; ?>">

See this example for the complete tutorial :

https://www.tutorialrepublic.com/php-tutorial/php-mysql-crud-application.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM