嘿大家希望一切都好。我需要你的专业知识。
我有一个 html 表单,在其中我有一个下拉选项来选择一个状态
<select name="State">
<option value="0" selected="selected">Select a State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
etc.....
</select>
每当客户选择一个州并提交表单时,它就会转到我的 mssql 数据库,并提取与他们在 html 表单中选择的州相关的 IP 地址。
+-----------+-------+---------------+ | stateip_id| state | user_ip | +-----------+-------+---------------+ | 1 | AL | 67.100.244.74 | | 2 | AK | 68.20.131.135 | | 3 | AZ | 64.134.225.33 | +-----------+-------+---------------+
So for example, lets say they choose Alabama (AL), when they submit the form i want the code to connect to the php file and then show the ip address releavant to the state, in this case (AL). For each state i have 200 different ip addresses, so i want it to randomly choose and ip for the state choosen.
I found some php code and have tested it with my details and it is connecting to the database fine.
<?php
$Server = "00.00.000.000,0000";
$User = "username";
$Pass = "password";
$DB = "dbname";
//connection to the database
$dbhandle = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server");
//select a database to work with
$selected = mssql_select_db($DB, $dbhandle)
or die("Couldn't open database $DB");
//declare the SQL statement that will query the database
$query = "SELECT stateip_id, state, user_ip ";
$query .= "FROM state_ip ";
$query .= "WHERE state='AK'";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["stateip_id"] . $row["state"] . $row["user_ip"] . "</li>";
}
//close the connection
mssql_close($dbhandle);
?>
我遇到的问题是 WHERE 部分
$query .= "WHERE state='AK'";
如果我像上面那样在“”部分添加 AK 或 AL,它会显示与 AL 或 AK 关联的所有 IP 地址。我想让它做的是识别从表单中选择的状态,然后只显示一个根据状态随机选择的 ip 地址
我只是不确定要向 WHERE state='what in here'"; 部分添加什么以使其全部正常工作并让它从状态中随机选择一个 ip
如有任何帮助,我们将不胜感激。
谢谢大家
最佳答案
试试这个。
$state = $_POST['State'];
$query = "SELECT TOP 1 stateip_id, state, user_ip
FROM state_ip
WHERE state='$state'
ORDER BY RAND()";
关于php - mssql连接状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8322956/