0

Context: I've established a connection with a MySQL database that has Stock Ticker, Open, High, Low, Close prices, interval (1d, 1wk and 1mo) and date. Now, I'm trying to make it possible for a user to select the "ticker" name and "interval" in HTML and send this input as a MySQL search query with PHP. This data would then be saved in an array ($data_array[] = $row) so I could then use this data in a javascript variable. My main goal with this is first to be able to print the output from the MySQL query (i.e. the values of $data_array like this: [date,open,high,low,close],[date,open,high,low,close], etc. I will use this in a javascript to print out a graph using google charts. For the time being, I've established values for the ticker as AAPL and interval as 1mo (1 month) to test if I can get the data from the database

Problem: Whenever I run the PHP code, I keep getting "Undefined array key "ticker"" as well as "Undefined array key "interval"". I've found this topic mysql query result into php array, but not sure if this would fix the problem I'm having. I was also getting syntax error, unexpected variable "$stmt", but that seems to be solved by now

I'm new to PHP so any help is very welcome (specific documentation I might've missed,etc)! I apologize in advance if this is a duplicate, but I've been searching for possible solutions and I haven't been able to come up with one

HTML:

<form name="query" method="post" action="/connection.php">

              <!--<div class="ticker">-->
              <label for="ticker">Ticker:</label>
              <input style="background: rgba(255,255,255,0.5);border-radius: 10px; border: none;  text-align: center;"
                type="text" id="ticker" name="ticker" required minlength="1" maxlength="4" size="10"
                value="AAPL"></input>
              <!--</div>-->

              <!--<div class="interval"> -->

              <label for="interval">Period:</label>
              <select style="background: rgba(255,255,255,0.5);border-radius: 10px; border: none;  text-align: center;"
                name="interval" id="interval">
                <option value="1d">1 day</option>
                <option value="1wk">1 week</option>
                <option selected="selected" value="1mo">1 month</option>
              </select>
              <!--</div>-->
              <input class="button1" type="submit" formmethod="post" formaction="/connection.php" name="submit"></input>
            </form>

PHP:

<?php
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
$ticker = $_POST['ticker'];
$interval = $_POST['interval'];

if (isset($_POST['submit'])) {
  $stmt = $mysqli->prepare("SELECT Date, Open, High, Low, Close FROM symbols WHERE ticker='$ticker' AND interval='$interval'");
  $stmt->bind_param("ss", $ticker, $interval);
  $stmt->execute();

  $result = $stmt->get_result();
  while ($row = $result->fetch_assoc($result)) {
    $data_array[] = $row;
    echo "[" . $row["Date"]. "," . $row["Open"]. "," . $row["High"]. "," . $row["Low"]. "," . $row["Close"]. "],";
  } 
  $stmt->close();
}

?>

Testing:

    <?php
    $servername = "";
    $username = "";
    $password = "";
    $dbname = "";
    $ticker = $_POST['ticker'];
    $interval = $_POST['interval'];
    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
    }
    
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $stmt = $mysqli->prepare("SELECT Date, Open, High, Low, Close FROM symbols WHERE ticker=? AND interval=?");
      $stmt->bind_param("ss", $ticker, $interval);
      $stmt->execute();
    
      $result = $stmt->get_result();
      while ($row = $result->fetch_assoc($result)) {
        $data_array[] = $row;
        echo "[" . $row["Date"]. "," . $row["Open"]. "," . $row["High"]. "," . $row["Low"]. "," . $row["Close"]. "],";
      } 
      $stmt->close();
    }
    
    ?> 
<!DOCTYPE html>
<html>
<body>
    <div class="container-fluid">
      <div class="statistic-block block">
        <form name="query" method="post" action="" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    
          <!--<div class="ticker">-->
          <label for="ticker">Ticker:</label>
          <input style="background: rgba(255,255,255,0.5);border-radius: 10px; border: none;  text-align: center;"
            type="text" id="ticker" name="ticker" required minlength="1" maxlength="4" size="10"
            value="AAPL"></input>
          <!--</div>-->
    
          <!--<div class="interval"> -->
    
          <label for="interval">Period:</label>
          <select style="background: rgba(255,255,255,0.5);border-radius: 10px; border: none;  text-align: center;"
            name="interval" id="interval">
            <option value="1d">1 day</option>
            <option value="1wk">1 week</option>
            <option selected="selected" value="1mo">1 month</option>
          </select>
          <!--</div>-->
          <input class="button1" type="submit" name="submit" id="submit" onsubmit="return false"></input>
        </form>
      </div>
    </div>
</body>
</html>
  • Is "connection.php" the same file which contains your HTML form? If so you'll get those warning messages whenever you load the form, because loading the form triggers a GET request and of course those POST values are not populated yet because the user hasn't yet submitted the form containing them. In that case simple check whether the request is a POST or not before running any of the which tries to read from $_POST and run the query - see https://stackoverflow.com/a/1372163/5947043 for the simple solution. In fact you already have `if (isset($_POST['submit'])) {` - just move it up a bit! – ADyson Oct 04 '21 at 22:16
  • 2
    You also seem to have a misunderstanding about how parameter binding works in your query - you need to replace the variables in the SQL string with `?` placeholders. e.g. change `SELECT Date, Open, High, Low, Close FROM symbols WHERE ticker='$ticker' AND interval='$interval'"` to `SELECT Date, Open, High, Low, Close FROM symbols WHERE ticker=? AND interval=?"` - you're already sending the actual values in the `bind_param` function. Otherwise you'll likely get a mysqli error about a mismatch between the number of parameters and the number of placeholders. – ADyson Oct 04 '21 at 22:18
  • Hello, @ADyson, thank you for your time! It is a different file, should I create a separate .php file just to establish the connection and then put the SQL query inside the HTML form? I've tried doing the `($_SERVER['REQUEST_METHOD'] === 'POST')`, but I kept getting `Undefined array key "REQUEST_METHOD"`. I assume that is happening because I need to have that code in the same HTML form using ``? –  Oct 04 '21 at 22:21
  • Correct your query where clause like this `WHERE ticker= ? AND interval= ?");` or same as adyson said. –  Oct 04 '21 at 22:21
  • @Dlk no, mysqli doesn't understand named parameters. Only `?`s will work for that bit. You're probably thinking of PDO. – ADyson Oct 04 '21 at 22:22
  • @ADyson yes sorry I corrected comment. –  Oct 04 '21 at 22:24
  • `Undefined array key "REQUEST_METHOD"`...that's weird, and should not ever happen. But you can just move `$ticker = $_POST['ticker']; $interval = $_POST['interval'];` inside the `if (isset($_POST['submit'])) {` to get the same result. – ADyson Oct 04 '21 at 22:25
  • `It is a different file, should I create a separate .php file just to establish the connection and then put the SQL query inside the HTML form`, no there's no specific requirement to do that. But then it's strange why you get the warnings, unless you are somehow also accessing `connection.php` at a time when you didn't submit the form. – ADyson Oct 04 '21 at 22:26
  • I only call/mention the `connection.php` on my HTML form. I've made the changes you've suggested (and updated the OP) with the `?`, but I keep getting the same error. I'll try to move the query to the HTML form and see what happens –  Oct 04 '21 at 22:31
  • It shouldn't be necessary but ok. If there is still a problem after that, please update the question, to show exactly what changes you have made. Add filenames at the top of each section of code so we know where everything is located. Thanks. – ADyson Oct 04 '21 at 22:35
  • @ADyson I've added a "testing" section with the new changes, but I keep getting the same error. The connection.php and html are in the same parent folder so doing /connection.php for example would get the file –  Oct 04 '21 at 22:55
  • Thanks. As I said before, you need to move `$ticker = $_POST['ticker']; $interval = $_POST['interval'];` _inside_ the `if ($_SERVER["REQUEST_METHOD"] == "POST") {` area...then if this file is ever involved in a GET request somehow (such as when loading the form, in your second example), it won't try to read from the those $_POST values – ADyson Oct 05 '21 at 06:20

0 Answers0