简体   繁体   中英

How to display data from SQL database into PHP/HTML table

So I am already using post to insert data from a HTML form to a MySQL database running on XAMPP, how would I then display this data on another HTML page in a table? When I try run it from localhost it comes up with a blank page with a line of code on the top. I am new to this, here is my code: am I doing it right?

<html>
<head>
</head>
<body>
    <?php
    $con = mysql_connect('localhost', 'root', '');
    if (!$con){
        die("Can not connect: " . mysql_error());
    }
    mysql_select_db("form_process", $con);
    $sql = "SELECT * FROM `form_submissions`";
    $myData = mysql_query($sql,$con);
    echo "<table border=1>
    <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Phone Number</th>
    <th>Class interested in</th>
    </tr>"; 

    while($row= mysql_fetch_array($result)){
        echo "<tr>";
        echo "<td>" . $record['First'] . "</td>";
        echo "<td>" . $record['Last'] . "</td>";
        echo "<td>" . $record['Phone'] . "</td>";
        echo "<td>" . $record['Class'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";

    mysqli_close();

    ?>

</body>
</html>

Try below code and see comments for changes in program

<html>
  <head>
  </head>
  <body>
    <?php
      // MySQL has been deprecated so use mysqli or pdo.
      $con = mysqli_connect('localhost', 'root', '', 'form_process') die("Can not connect: " . mysql_error());

      $sql = "SELECT * FROM `form_submissions`";
      $myData = mysqli_query($con, $sql);

      echo "<table border=1>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Phone Number</th>
          <th>Class interested in</th>
        </tr>"; 

      // mysqli_fetch_array should have query result in parameters
      while($row = mysqli_fetch_array($myData)){
        echo "<tr>";
        // use proper array in this case its $row as in while condition
        echo "<td>" . $row['First'] . "</td>";
        echo "<td>" . $row['Last'] . "</td>";
        echo "<td>" . $row['Phone'] . "</td>";
        echo "<td>" . $row['Class'] . "</td>";
        echo "</tr>";
      }
      echo "</table>";

      mysqli_close();

    ?>

  </body>
</html>

you should use mysqli or pdo , mysql has been deprecated . mysqli is similar to mysql.

mysqli code bellow

  $con = mysqli_connect('localhost', 'root', '', 'form_process') die("Can not connect: " . mysql_error());

  $sql = "SELECT * FROM `form_submissions`";
  $myData = mysqli_query($con, $sql);

  while($row = mysqli_fetch_array($myData)){
  /// some code
  }
  mysqli_close();

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