Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get data from MySql table using PDO and PHP in a select input form
    text
    copied!<p>I am trying to create a form where when the user first selects a country, and then a list off all the cities of the selected county should appear. See the following code:</p> <pre><code>&lt;select name="country" id="countryS"&gt; &lt;option value=""&gt;Select Country&lt;/option&gt; &lt;option value="1"&gt;USA&lt;/option&gt; &lt;option value="2"&gt;RUSSIA&lt;/option&gt; &lt;option value="3"&gt;United Kingdom&lt;/option&gt; &lt;/select&gt; &lt;select name="city" id="citiesS"&gt; &lt;option value=""&gt;Select City&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Then with JQuery I use the following code:</p> <pre><code> $('#countryS').on('change', function (e) { var optionSelected = $("option:selected", this); var valueSelected = this.value; $.post('Showcountries.php', { valueSelected: valueSelected}, function(results){ }); </code></pre> <p>And my question is how can I use the above jQuery code so as to be able to show the appropriate cities in the following html code?</p> <pre><code>&lt;select name="city" id="citiesS"&gt; &lt;option value=""&gt;Select City&lt;/option&gt; &lt;/select&gt; </code></pre> <p>In <code>showCountries.php</code> I have stored the following code:</p> <pre><code>&lt;?php require_once('../class.myclass.php'); if(isset($_POST['valueSelected'])){ $selectedVal = $_POST['valueSelected']; if(!empty($selectedVal)){ $locations = new location(); $cities = $locations-&gt;TheCities($selectedVal); return $cities; } } ?&gt; </code></pre> <p>And finally in <code>class.myclass.php</code> i have the code below which returns all the appropriate cities.</p> <pre><code>&lt;?php class location { private $host = "xxxxxxxx"; private $user = "xxxxxxxx"; private $password = "xxxxxxxx"; private $name = "xxxxxx"; public function TheCities($country) { $db = new PDO('mysql:host=' . $this-&gt;host . ';dbname=' . $this-&gt;name, $this-&gt;user, $this-&gt;password); $sql = "SELECT * FROM CITIES WHERE COUNTRY = :country"; $sth = $db-&gt;prepare($sql, array(PDO::ATTR_CURSOR =&gt; PDO::CURSOR_FWDONLY)); $sth-&gt;execute(array(':country' =&gt; $country)); $results = $sth-&gt;fetchAll(); return $results; } } ?&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload