Relate html and php in a single file

0

I'm quite new to php, however, my connection to the server is successful, what hinders me is to make a table in HTML with the fields that are extracted from the connection and I want the results to show me the table and something that I'm doing badly because at the top it shows me the results of the connection and below the table. My goal is for the table to show me the results of each field connected to each other! Here I show you my code

<?php
$servername = "xxxxxx";
$username = "xxxxx";
$password = "";
$db = "xxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";

$mysqli = new mysqli("xxxxx", "xxxx", "", "xxxxx");

/* comprueba la conexión */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}


/* devuelve el nombre de la base de datos actualmente seleccionada */
if ($result = $mysqli->query("SELECT DATABASE(chat)")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}
/* cambia de test bd a world bd */
$mysqli->select_db("xxxx");
/* devuelve el nombre de la base de datos actualmente seleccionadae */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}
/*selecciona campos de la tabla*/
$sql = "SELECT date, threads, operator_msgs, user_msgs, missed_threads, avg_waiting_time, invitations_sent, invitations_accepted, invitations_rejected, invitations_ignored  FROM cgchat";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "date: " . $row["date"]. " threads: " . $row["threads"].  "Operator messages: " . $row["operator_msgs"]. " User messages: " . $row["user_msgs"]. "Missedthreads " . $row["missed_threads"]. "Average waiting time " . $row["avg_waiting_time"]. "Sentinvitations: " . $row["invitations_sent"]. " Acceptedinvitations: " . $row["invitations_accepted"].  "Rejectedinvitations: " . $row["invitations_rejected"]. " Ignoredinvitations: " . $row["invitations_ignored"]. "<br>";
    }
} else {
    echo "0 results";
}

$mysqli->close();
?>

<!DOCTYPE html>
<html>
<head>


  <FORM action="conex.php" method="post">
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>DataTables example - Multiple tables</title>
  <link rel="shortcut icon" type="image/png" href="/media/images/favicon.png">
  <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.datatables.net/rss.xml">
  <link rel="stylesheet" type="text/css" href="/media/css/site-examples.css?_=6e5593ad4c5375eef5d919cfc10a0a54">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
  <style type="text/css" class="init">

  div.dataTables_wrapper {
    margin-bottom: 3em;
  }

  </style>
  <script type="text/javascript" src="/media/js/site.js?_=88b8e26b7e3dd4eee69f199f9880a0e0">
  </script>
  <script type="text/javascript" src="/media/js/dynamic.php?comments-page=examples%2Fbasic_init%2Fmultiple_tables.html" async>
  </script>
  <script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.4.js">
  </script>
  <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js">
  </script> 
  <script type="text/javascript" language="javascript" src="../resources/demo.js"> 
  </script> 
  <script type="text/javascript" class="init">

$(document).ready(function() {
  $('table.display').DataTable();
} );

  </script>
</head> 

<body class="wide comments example">

  <a name="top" id="top"></a>
  <div class="form-header">
                    <div class="form-header-inwards"></div>
                </div>


        <table id="" class="display" cellspacing="0" width="100%">
          <thead>
            <tr>
              <th>Date</th>
              <th>Threads</th>
              <th>Operator messages</th>
              <th>User messages</th>
              <th>Missedthreads</th>
              <th>Average waiting time</th>
              <th>Sentinvitations</th>
                        <th>Acceptedinvitations</th>
              <th>Rejectedinvitations</th>
              <th>Ignoredinvitations</th>
            </tr>
          </thead>
          <tfoot>
            <tr>
              <th>Total</th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              </tr>
          </tfoot>
          <tbody>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>

the result that appears in the upper part of the image I want you to show it to me but in the table that is shown, according to what I want to do in a single file, because if it were two, I just need a little help to explain how I would do it.?

Thanks

    
asked by Angie.Edu 22.01.2018 в 18:02
source

2 answers

0

As far as I could appreciate you are really new to php. The way to render data brought from a database in a table you must unite the two parts in a same fragment of code, not separately as what you have done so far. For example, if you want to show the name of a user that you have in a variable inside a html span element, it would be like this:

$name = "Pedro";
//para mostrarlo en html
echo "<span>".$name."</span>";
// o tambien: echo "<span>{$name}</span>";

Then, understanding this you can do what you want, knowing that in the cycle that you have in the last lines of your php code you need to write the elements tr and td that corresponds to the table you want to draw in html and move it towards the part of your html where you create the tbody, in short something like the following:

<?php
$servername = "xxxxxx";
$username = "xxxxx";
$password = "";
$db = "xxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";

$mysqli = new mysqli("xxxxx", "xxxx", "", "xxxxx");

/* comprueba la conexión */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* devuelve el nombre de la base de datos actualmente seleccionada */
if ($result = $mysqli->query("SELECT DATABASE(chat)")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}
/* cambia de test bd a world bd */
$mysqli->select_db("xxxx");
/* devuelve el nombre de la base de datos actualmente seleccionadae */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}
/*selecciona campos de la tabla*/
$sql = "SELECT date, threads, operator_msgs, user_msgs, missed_threads, avg_waiting_time, invitations_sent, invitations_accepted, invitations_rejected, invitations_ignored  FROM cgchat";
$result = $conn->query($sql);

?>

<!DOCTYPE html>
<html>
<head>


  <FORM action="conex.php" method="post">
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>DataTables example - Multiple tables</title>
  <link rel="shortcut icon" type="image/png" href="/media/images/favicon.png">
  <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.datatables.net/rss.xml">
  <link rel="stylesheet" type="text/css" href="/media/css/site-examples.css?_=6e5593ad4c5375eef5d919cfc10a0a54">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
  <style type="text/css" class="init">

  div.dataTables_wrapper {
    margin-bottom: 3em;
  }

  </style>
  <script type="text/javascript" src="/media/js/site.js?_=88b8e26b7e3dd4eee69f199f9880a0e0">
  </script>
  <script type="text/javascript" src="/media/js/dynamic.php?comments-page=examples%2Fbasic_init%2Fmultiple_tables.html" async>
  </script>
  <script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.4.js">
  </script>
  <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js">
  </script> 
  <script type="text/javascript" language="javascript" src="../resources/demo.js"> 
  </script> 
  <script type="text/javascript" class="init">

$(document).ready(function() {
  $('table.display').DataTable();
} );

  </script>
</head> 

<body class="wide comments example">

  <a name="top" id="top"></a>
  <div class="form-header">
                    <div class="form-header-inwards"></div>
                </div>


        <table id="" class="display" cellspacing="0" width="100%">
          <thead>
            <tr>
              <th>Date</th>
              <th>Threads</th>
              <th>Operator messages</th>
              <th>User messages</th>
              <th>Missedthreads</th>
              <th>Average waiting time</th>
              <th>Sentinvitations</th>
                        <th>Acceptedinvitations</th>
              <th>Rejectedinvitations</th>
              <th>Ignoredinvitations</th>
            </tr>
          </thead>
          <tfoot>
            <tr>
              <th>Total</th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              </tr>
          </tfoot>
          <tbody>
            <?php
            if ($result->num_rows > 0) {
                // output data of each row
                while($row = $result->fetch_assoc()) {
                    echo "<tr><td>" . $row["date"]. "</td><td>" . $row["threads"].  "</td><td>" . $row["operator_msgs"]. "</td><td>" . $row["user_msgs"]. "</td><td>" . $row["missed_threads"]. "</td><td>" . $row["avg_waiting_time"]. "</td><td>" . $row["invitations_sent"]. "</td><td>" . $row["invitations_accepted"].  "</td><td>" . $row["invitations_rejected"]. "</td><td>" . $row["invitations_ignored"]. "</td></tr>";
                }
            } else {
                echo "<tr><td>0 results</td></tr>";
            }

            $mysqli->close();
            ?>
        </tbody>
        </table>
    </body>
</html>
    
answered by 22.01.2018 в 18:20
0

You can mix your PHP code with HTML content as much as you want. You just have to know how to open and close PHP blocks correctly.

I have changed the following:

  • I put up the initial part of HTML, following a logical order of how the page would appear
  • In that first part we build the first elements of the table. This can still be improved ... for example, if no data is found, the table does not have to be displayed.
  • When we arrive at the reading of the possible results, I create a variable $strHTML to which I will concatenate the different rows / columns. This will prevent us from opening and closing mixed PHP / HTML blocks that seem horrible to me in particular, as well as producing illegible code.
  • I have left the foot of the table as it is, since your code does not refer to those totals that you want to show and it is not the objective of your question.
  • At the end we close the table.
  • The result would be this:

    <!DOCTYPE html>
    <html>
    <head>
    
      <FORM action="conex.php" method="post">
      <meta http-equiv="Content-type" content="text/html; charset=utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <title>DataTables example - Multiple tables</title>
      <link rel="shortcut icon" type="image/png" href="/media/images/favicon.png">
      <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.datatables.net/rss.xml">
      <link rel="stylesheet" type="text/css" href="/media/css/site-examples.css?_=6e5593ad4c5375eef5d919cfc10a0a54">
      <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
      <style type="text/css" class="init">
    
      div.dataTables_wrapper {
        margin-bottom: 3em;
      }
    
      </style>
      <script type="text/javascript" src="/media/js/site.js?_=88b8e26b7e3dd4eee69f199f9880a0e0">
      </script>
      <script type="text/javascript" src="/media/js/dynamic.php?comments-page=examples%2Fbasic_init%2Fmultiple_tables.html" async>
      </script>
      <script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.4.js">
      </script>
      <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js">
      </script> 
      <script type="text/javascript" language="javascript" src="../resources/demo.js"> 
      </script> 
      <script type="text/javascript" class="init">
    
    $(document).ready(function() {
      $('table.display').DataTable();
    } );
    
      </script>
    </head> 
    <body class="wide comments example">
    
      <a name="top" id="top"></a>
      <div class="form-header">
                        <div class="form-header-inwards"></div>
                    </div>
    
    
            <table id="" class="display" cellspacing="0" width="100%">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Threads</th>
                  <th>Operator messages</th>
                  <th>User messages</th>
                  <th>Missedthreads</th>
                  <th>Average waiting time</th>
                  <th>Sentinvitations</th>
                  <th>Acceptedinvitations</th>
                  <th>Rejectedinvitations</th>
                  <th>Ignoredinvitations</th>
                </tr>
              </thead>
    <?php
    /*Ahora necesitamos PHP, abrimos un bloque*/
    $servername = "xxxxxx";
    $username = "xxxxx";
    $password = "";
    $db = "xxxxx";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $db);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    echo "Connected successfully";
    
    $mysqli = new mysqli("xxxxx", "xxxx", "", "xxxxx");
    
    /* comprueba la conexión */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    
    
    /* devuelve el nombre de la base de datos actualmente seleccionada */
    if ($result = $mysqli->query("SELECT DATABASE(chat)")) {
        $row = $result->fetch_row();
    //    printf("Default database is %s.\n", $row[0]);
        $result->close();
    }
    /* cambia de test bd a world bd */
    $mysqli->select_db("xxxx");
    /* devuelve el nombre de la base de datos actualmente seleccionadae */
    if ($result = $mysqli->query("SELECT DATABASE()")) {
        $row = $result->fetch_row();
    //    printf("Default database is %s.\n", $row[0]);
        $result->close();
    }
    /*selecciona campos de la tabla*/
    $sql = "SELECT date, threads, operator_msgs, user_msgs, missed_threads, avg_waiting_time, invitations_sent, invitations_accepted, invitations_rejected, invitations_ignored  FROM cgchat";
    $result = $conn->query($sql);
    
    $strHTML="";
    
    if ($result->num_rows > 0) {
    
        // output data of each row
        while($row = $result->fetch_assoc()) {
            /*La variable concatenará los valores de la tabla*/
            $strHTML="<tr>";
                $strHTML.="<td>".$row["date"]."</td>". 
                          "<td>".$row["threads"]."</td>". 
                          "<td>".$row["operator_msgs"]."</td>".
                          "<td>". $row["user_msgs"]."</td>".
                          "<td>".$row["missed_threads"]. "</td>".
                          "<td>".$row["avg_waiting_time"]."</td>".
                          "<td>".$row["invitations_sent"]."</td>".
                          "<td>".$row["invitations_accepted"]."</td>".
                          "<td>".$row["invitations_rejected"]."</td>".
                          "<td>".$row["invitations_ignored"]."</td>";
            $strHTML="</tr>";
        }
    } else {
        $strHTML= "0 results";
    }
    echo $strHTML;
    $mysqli->close();  /*Aquí termina todo el código PHP y seguimos con HTML*/
    ?>
              <tfoot>
                <tr>
                  <th>Total</th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                  </tr>
              </tfoot>
            </table>
    
        
    answered by 22.01.2018 в 18:27