Home > Software engineering >  include php script in html webpage
include php script in html webpage

Time:03-07

I have a 165 line php script that I would like to integrate into my html webpage.

The php script parses csv files uploaded by the user for column names. The html page allows the user to select variables from a dropdown menu. I want to let the php script run when a user uploads a file so the dropdown menu can be populated with the results from the php script.

this the html

<!DOCTYPE html>
<html lang="en">
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style type="text/css">
  body {
    padding-left: 11em;
 }
  ul.navbar {
    position: absolute;
    top: 2em;
    left: 1em;
    width: 9em }
  h1 {
    font-family: Helvetica, Geneva, Arial,
          SunSans-Regular, sans-serif }
  .float-child {
    width: 50%;
    float: left;
    padding: 20px;
}
label {
  cursor: pointer;
}

textarea {
  width: 400px;
  height: 150px;
} 
  </style>
<body>

<!-- Page content -->
<div  style="max-width:2000px;margin-top:46px">

    <div  style="max-width:800px" id="contact">
        <h2 >Create Crosstabs</h2>
        <ul >
            <li><a href="UploadCrosstabData.html">Upload Crosstab Data</a>
            <li><a href="CreateCrosstab.html">Create Crosstab</a>
            <li><a href="ViewCrosstab.html">View Crosstab</a>
            <li><a href="ViewPastCrosstabs.html">View Past Crosstabs</a>
        </ul>
      </div>

      <div >

        <div >
          <div >Choose Crosstab
            <label for="cars">Variable for Column 1: </label>
              <select name="cols" id="cols">
                <option value="Age">Age</option>
                <option value="Ethnicity">Ethnicity</option>
                <option value="Income">Income</option>
              </select>
              <br>
              <label for="cars">Variable for Column 2: </label>
              <select name="cols" id="cols">
                <option value="Age">Age</option>
                <option value="Ethnicity">Ethnicity</option>
                <option value="Income">Income</option>
              </select>
              <br>
              <button id="1" onClick="reply_click(this.id)">Create</button>
          </div>
        </div>
        
        <div >
          <div >Sucessfully Uploaded Records
            <div>
              <label for="input-file">Specify a file:</label><br>
              <input type="file" id="input-file">
             </div>
             <textarea id="content-target"></textarea>
          </div>
        </div>
        <h1><?php echo "This message is from server side." ?></h1>
<!-- End Page Content -->
</div>

<!-- Image of location/map -->
<img src="/w3images/map.jpg"  style="width:100%">

<script>
// Automatic Slideshow - change image every 4 seconds
var myIndex = 0;
carousel();

function reply_click(clicked_id)
  {
      alert(clicked_id);
  }

function carousel() {
  var i;
  var x = document.getElementsByClassName("mySlides");
  for (i = 0; i < x.length; i  ) {
    x[i].style.display = "none";  
  }
  myIndex  ;
  if (myIndex > x.length) {myIndex = 1}    
  x[myIndex-1].style.display = "block";  
  setTimeout(carousel, 4000);    
}

// Used to toggle the menu on small screens when clicking on the menu button
function myFunction() {
  var x = document.getElementById("navDemo");
  if (x.className.indexOf("w3-show") == -1) {
    x.className  = " w3-show";
  } else { 
    x.className = x.className.replace(" w3-show", "");
  }
}

// When the user clicks anywhere outside of the modal, close it
var modal = document.getElementById('ticketModal');
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

document.getElementById('input-file')
  .addEventListener('change', getFile)

function getFile(event) {
    const input = event.target
  if ('files' in input && input.files.length > 0) {
      placeFileContent(
      document.getElementById('content-target'),
      input.files[0])
  }
}

function placeFileContent(target, file) {
    readFileContent(file).then(content => {
    target.value = content
  }).catch(error => console.log(error))
}

function readFileContent(file) {
    const reader = new FileReader()
  return new Promise((resolve, reject) => {
    reader.onload = event => resolve(event.target.result)
    reader.onerror = error => reject(error)
    reader.readAsText(file)
  })
}
</script>

</body>
</html>

and this is the php



<?php
   //Connection
   $db = pg_connect( "host=localhost dbname=dbname user=postgres password=password"  );
   if(!$db) {
      echo "Error : Unable to open database";
   } else {
      echo "Opened database successfully";
      echo "<br>";
   }


   //Using this to test queries
   function testQuery($ret, $completedmsg=""){
      if(!$ret){
         echo pg_last_error();
         echo "<br>";
      }else{
         echo $completedmsg;
         echo "<br>";
      }
   }

   //Added a break function, I was sick of adding breaks for echoing
   function break_html(){
      echo "<br>";
   }



   //Getting file
   $CSV_File = "pi2sample5.csv";
   $csv = file($CSV_File);
   //Get type of each column (count(int), percentage(float), ""(varchar))
   $type = explode(",", $csv[0]);
   //Get each column name
   $column_name = explode(",", $csv[1]);
   //Remove .csv (lazy, but I will add a regex here)
   $table_name = substr($CSV_File,0,-4); 
   $table_name = preg_replace('/\..*/', '', $CSV_File);

   //Check if table exists
   $checkExists = "SELECT EXISTS (SELECT FROM pg_tables WHERE schemaname = 'public' AND tablename  =" . "'" . $table_name . "'". ")";
   $exists = False;
   $ret = pg_query($db, $checkExists);

   $i = 0;
   while ($row = pg_fetch_row($ret)) 
   {
      
      $count = count($row);
      $y = 0;
      while ($y < $count)
      {
         
         $c_row = current($row);
         if($c_row == 't'){
            $exists = True;
         }
         next($row);
         $y = $y   1;
      }
   }
   //If table exists, skip creation
   if(!$exists){
      //Create new Table
   $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . "()";
   
   $ret = pg_query($db, $sql);

   if(!$ret){
      echo pg_last_error();
      echo "<br>";
   }else{
      echo "CREATED NEW TABLE";
      echo "<br>";
   }
   //Making columns with correct variable types and names
   $i = 0;

   while ($i < count($column_name)){
       if ($type[$i] == "Count"){
          $new_type = "INT";
       }elseif ($type[$i] == "Dollars"){
          $new_type = "INT";
       }elseif ($type[$i] == "Percentage"){
          $new_type = "float8";
       }else{
         $new_type = "VARCHAR(12)";
       }
       $new_column = preg_replace('/[^A-Za-z0-9]/', '', $column_name[$i]);
       
       
       $i = $i 1;
        $ret = pg_query($db, "ALTER TABLE " . $table_name . " ADD COLUMN " .$new_column. " " . $new_type);
        if(!$ret){
          echo pg_last_error();
          echo "<br>";
          }else{
             echo "ADDED NEW COLUMN: " . $new_column;
             echo "<br>";
          }
      
    }

    //Copy file into a safe "previous" version
    if (!copy($CSV_File, "old" . $CSV_File)) {
      echo "failed to copy $file...\n";
   }
     //Remove first row of CSV (count, count, percentage, etc...)

      $new_csv = array_splice($csv, 1);
      file_put_contents($CSV_File, implode("", $new_csv));
      $createCSVtable ="COPY " . $table_name .  " FROM '/home/monty/PI2/PI2Team/" . $CSV_File . "' DELIMITER ',' CSV HEADER;";
      file_put_contents("rewritten.csv", $old_csv);
      $ret = pg_query($db, $createCSVtable);
      testQuery($ret);

      //Restore the file with removed row
      if (!copy("old" . $CSV_File, $CSV_File)) {
         echo "failed to copy $file...\n";
      }
      if(!unlink("old" . $CSV_File)){
         echo "Couldn't delete old$CSV_File";
      }
   }
   
  
  
   //GET VARIABLES/COLUMN NAMES
   $ret = pg_query($db, "SELECT
    column_name
FROM
    information_schema.columns
WHERE table_name =" . "'" . $table_name . "'" );
   
   if(!$ret){
      echo pg_last_error($db);
   } else{
      echo "SHOWING TABLE";
      //echo pg_fetch_row($ret);
   }

echo '<html><body><select name="variables">';

//Putting variables (column names) into dropdown menu in html
$i = 1;
while ($row = pg_fetch_row($ret)) 
{
    $count = count($row);
    $y = 0;
    while ($y < $count)
    {
      
        $c_row = current($row);
      echo "<option value=" . "'" . $c_row . "'" . ">" . $c_row .  "</option>";

      next($row);
        $y = $y   1;
    }
   
    $i = $i   1;
}
echo "</select>";
   pg_free_result($ret);
   pg_close($db);
?>

CodePudding user response:

Just set up your web server so that HTML files parse through PHP. This varies depending on your server. Alternatively, just save the file as .php and it should run!

  • Related