weardstuff
weardstuff

Reputation: 807

Auto select from db

I want to do the folowing thing, here is simple select, that gets info from db.I have one db that have id/city/people.SO this is like some example selects

  Select1|Select2|
    City1   |2    
    City2   |Poeple2      
    City3   |People3      
    City4   |People1        
    City5   |PopleFromFirstCity  

Here is what i want to do, when i select some city from the first select, i want in the second select that is Select2 the output to be auto changet to what i picket in the first, so if i pick City1, the second select to have PeopleFromFirstCity and People1

Upvotes: 1

Views: 1061

Answers (1)

Filip Krstic
Filip Krstic

Reputation: 713

For first selection make this:

 <form>
 Select city: <select name="cities" onchange="showCity(this.value)">
 <option value="0">Chose city...</option>
 <?php          
 $sql="SELECT id,city FROM table1 ORDER BY ID DESC";      
 $result = mysql_query($sql);
 while($row = mysql_fetch_array($result))
 {
 echo"<option value=" . $row[id] . ">" . $row[city] . "</option>";
 }
 ?>
 </select></form>

For output from selection2 make div:

<div id="txtHint"></div>

Now make second table table2 which contain peoples, and make .js file

var xmlhttp;

function showCity(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="http://fullpathtoselection2file/selection2.php"; // Example: http://www.site.com/files/selection2.php
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
      }
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}

Implement to your file where is selection 1 this js file. And now make selection 2:

<?php
// Get city id
$q=$_GET["q"];
// Select from SQL where city = city id
$sql="SELECT peoples,city_id FROM table2 WHERE city_id = '".$q."' order by id desc";

$result = mysql_query($sql);

// echo it
while($row = mysql_fetch_array($result))
{
echo $row['peoples'];
}

How you have 2 tables. table1 for cities second table2 for peoples. When you update your database for example from admin panel, u need to update 2 tables. for peoples and for cities. For table 1 need to contain: id, city... Table 2 need to contain id,peoples, city_id.

Code isn't tested.

Upvotes: 1

Related Questions