0

Context: I'm retrieving a bunch of Stock tickers from my database and putting those as options in a select element. Now, I'd like for the selected tickers by the user to be passed onto a MySQL query with PHP to retrieve the stock data (such as the open price). Even though I'm creating the select options dynamically, I feel like that should be enough to allow the query to be done successfully (referring to this SO topic - How to pass the selected value in dropdown (HTML) to PHP).

Minimally reproducible code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

    <select id="selectStock" name="selectStock">

    </select>

    <input class="button1" type="submit" name="submit" id="btnAdd"></input>

    <select id="list" name="list" multiple>
    </select>




  </form>
</body>
<script type="text/javascript">
  var dropdown = document.getElementById("selectStock");
  var selected = []
  //let options = <?php echo json_encode($tickerArray) ?>; //get data from MySQL tickers
  let options = [
    ["AAPL"],
    ["TSLA"],
    ["HOOD"],
    ["GOOGL"]
  ];
  var btnAdd = document.querySelector('#btnAdd');
  var sb = document.querySelector('#list');
  const name = document.querySelector('#selectStock');

  //var open = <?php echo json_encode($openPrices) ?>; This is the variable that I want to retrieve the open prices, but the query isn't working


  //Insert list of tickers in the options
  for (var i = 0; i < options.length; i++) {
    var list = options[i]; //save every option as opt
    var opt = document.createElement("option");
    opt.innerHTML = list; //change the HTML so that the newly added element for a select option is equal to the tickers in opt
    opt.value = list; //give the value of the element created as the ticker name
    dropdown.appendChild(opt); //append the latest element created to the select options
  }

  //Function to add the selected tickers in the list box
  btnAdd.onclick = (e) => {

    e.preventDefault();

    // validate the option
    if (name.value == '') {
      alert('Please enter the name.');
      return;
    }
    // create a new option
    option = new Option(name.value, name.value);

    // add it to the list
    sb.add(option, undefined);

    selected.push({
      x: option.value,
      y: Math.random(), //percentualIncrease, //openCalc
    });
    // reset the value of the input
    name.value = '';
    name.focus();

    console.log(selected)
    console.log(open)
    console.log(option.value)

  };
</script>

</html>

This is the PHP:

<?php
              $servername = "...";
              $username = "...";
              $password = "...";
              $dbname = "...";
              $tickerChosen = "";
              $openPrices = array();
              mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
              $conn = mysqli_connect($servername, $username, $password, $dbname);
              // Check connection
              if (!$conn) {
                die("Connection failed: " . mysqli_connect_error());
              }
              if (isset($_POST["submit"])) {
                $tickerChosen = $_POST["option"];
                echo $tickerChosen;
                $stmt = $conn->prepare("SELECT Open FROM symbolsv2 WHERE ticker=? ORDER BY Date DESC LIMIT 2");
                $stmt->bind_param("s", $tickerChosen);
                $stmt->execute();

                $result = $stmt->get_result();
                while ($open = $result->fetch_all()) {
                  $openPrices = $open;
                }
                $stmt->close();
              }
              $conn->close();

              ?>

I already tried changing the $tickerChosen = $_POST["..."] with selectStock, name, option, etc, but none of those seemed to be able to "grab" the user input and pass it to the query.

Any suggestions? Thank you in advance!

  • Have you tried defining the `options` variable as a normal array instead of a multidimensional array? `options = ["AAPL", ....]`? The way you've defined it now, ` `opt.value = list` will set the value as an array `["AAPL"]` instead of just `AAPL`, which won't work. – M. Eriksson Oct 30 '21 at 22:55
  • And when the form is submitted, it will use the input/select elements `name` attribute, so it needs to be `$_POST['selectStock']`, not `$_POST['option']`. – M. Eriksson Oct 30 '21 at 23:02
  • Btw, how are you actually submitting the form? You have a `e.preventDefault()` on the submit button and I don't see you making any ajax call? – M. Eriksson Oct 30 '21 at 23:08
  • Thank you for your input! I changed the `options` using the spread operator like this ` options = [].concat(...options);` and it is now 1D, but I still can't get the query to work. –  Oct 30 '21 at 23:14
  • Why are you overcomplicating things? Just do `var options = ["AAPL", "TSLA", etc];` when you define it and be done with it. That was also only one of multiple things I pointed out/asked. – M. Eriksson Oct 30 '21 at 23:24
  • The multidimensional array is retrieved from PHP in that format that's why I used the spread operator. –  Oct 30 '21 at 23:31
  • So change the PHP to return it in the format you need it. But you still haven't answered the rest of my question. If we comment/ask things, it's because we need to know those things in order to help you. If you ignore it, then there isn't much we can do. Also, what debugging have you done? Have you done a `var_dump($_POST)` in your PHP to see what you're actually getting? – M. Eriksson Oct 30 '21 at 23:35
  • Your PHP code is also wrong. `$openPrices = $open;` inside the while loop will just overwrite the variable `$openPrice` on each iteration. The variable will only contain the last record from the last iteration. Or rather it would have, if you used mysqli correctly. It should be `while ($open = $stmt->fetch())`, not `$result->fetch_all()` (you can remove `$result = $stmt->get_result()`). Make sure you have error reporting turned (set to E_ALL) on and have enabled display errors – M. Eriksson Oct 30 '21 at 23:39
  • ...or you can keep `$result = $stmt->get_result()` and then only do `$openPrices = $result->fetch_all(MYSQLI_ASSOC)` without the `while`-loop. You're mixing concepts here. – M. Eriksson Oct 30 '21 at 23:44

0 Answers0