如何将变量从一个PHP脚本拉到另一个PHP脚本

时间:2018-06-16 02:23:24

标签: javascript php

无法将变量从一个PHP拉到另一个脚本。

我有三个不同的文件:adminPage.html,reportScript.php和report.php。

adminPage.html从用户获取变量并使用AJAX post函数将变量发布到reportScript.php。

report.php应该从reportScript.php中提取这些已发布的变量并在SQL函数中使用这些变量,但是,我收到一条错误,指出我有一个"未定义的索引:startDate"和"未定义的索引:endDate"我在PHP中实例化变量。

adminPage.html:

<center><h2> Choose the dates below that you need an order list from: </h2>
</br>
  <form>
    <h2>Start:</h2>
    <input type="date" id ="reportStartDate" name = "startDate">
      </br>
    <h2>End:</h2>
    <input type="date" id ="reportEndDate" name = "endDate">
  </form>
</center>

</br></br>
    <button id="runReportButton" onclick = "runReport()"> Run Report </button>

<script>



function runReport()
{
  var jStartDate;
  var jEndDate;

  jStartDate = document.getElementById("reportStartDate").value;
  jEndDate = document.getElementById("reportEndDate").value;

  /*console.log(jStartDate);
  console.log(jEndDate); */

  $.ajax
  ({
    type: "POST",
    url: "phpScripts/reportScript.php",
    data: {startDate: jStartDate, endDate: jEndDate},
    success: function(response)
      {
        console.log("posted");
       window.open("report.php", "_self");
      }
  });

}

</script>

reportScript.php:

    <?php
    require 'connect.php';

    //posts data to db
    $startDate = $_POST["startDate"];
    $endDate = $_POST["endDate"];

    $sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < startDate OR 
    dateOrdered > endDate)";

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

    if($result){
    echo "true";
    }

    else{
    echo "false";
    }
    ?>

report.php:

<?php
require 'phpScripts/connect.php';

require 'phpScripts/reportScript.php';

//posts data to db

/*$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];*/

/*$startDate = '2018-01-01';
$endDate = '2018-08-08'; */

$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < '$startDate' OR dateOrdered > '$endDate');";

$result = $conn->query($sql);
//above is reportScript.php, below is pulling list method from order.php
//below works, just needs variables from the reportScript
echo "<ul>";
if($result->num_rows >0)
{
  $i = 0;
  while($row = $result->fetch_assoc()) // this loads database into list, also 
creates array of pricing which someone can pull from later to get total
  {
    echo  "<li style='font-size:15px'>".$row["drinkName"]. ", Date Ordered: " 
.$row["dateOrdered"] . ",Cost: " .$row["drinkCost"] . "</li>";
    echo "</br>";

  $i = $i+1;
  }
}else {
  echo "<p> you're a dummy and you did this wrong </p>";
}
echo "</ol>";


?>

2 个答案:

答案 0 :(得分:1)

您在reportScript.php。

中忘记了变量中的dollar sign ($)
 $sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < $startDate OR 
    dateOrdered > $endDate)";

此声明也容易受到sql injection的攻击。<​​/ p>

答案 1 :(得分:0)

利用@Ralf的一些建议,我结合了reportScript.php和report.php,并使用$ _GET语句在打开时将日期变量放入URL。这样,查询不会被放置两次,并且变量仍会保存。