【问题标题】:why I can not store selected value by $_POST in php为什么我不能通过 $_POST 在 php 中存储选定的值
【发布时间】:2017-04-09 11:46:40
【问题描述】:

我创建了一个下拉列表来选择值:

 <form action="." method="post" id="aligned">
    <input type="hidden" name="action" value="update_customer">
    <input type="hidden" name="customer_id" 
           value="<?php echo htmlspecialchars($customer['customerID']); ?>"> 


    <label>Country:</label>
    <select name="selected">
     <?php  

        $dbhost = 'localhost';
        $dbuser = 'root';
        $dbpass ='';
        $db = 'tech_support';

        $conn = mysql_connect($dbhost, $dbuser, $dbpass);
        if(!$conn)
            die('Could not connect: '. mysql_error());

        mysql_select_db($db);
        $selected= mysql_query("select * from countries where countryCode = '" .$customer['countryCode']. "'");
        $sql = mysql_query("select * from countries order by countryName");

        if($selectedrow = mysql_fetch_array($selected)){
             echo "<option selected value=\"VALUE\">" . $selectedrow['countryName']."</option>";
        }
         //echo "<select>";

        while ($row = mysql_fetch_array($sql)) {
        echo "<option value =\"VALUE\">". $row['countryName']."</option>";
        }
        //echo "</select>";
       ?> 
    </select><br>

在下面的另一个 php 文件中,我试图存储 Country 的选定值,但没有存储任何内容,为什么?

<?php $country_name = $_POST["selected"];
echo $country_name;//it always print out 'VALUE'-I guess it means null.
?>

【问题讨论】:

  • echo "&lt;option value =\"VALUE\"&gt;" 因为您将实际值设置为VALUE
  • 用任何参数或变量替换VALUE...echo "&lt;option selected value="'.$selectedrow['countryName'].'"&gt;" . $selectedrow['countryName']."&lt;/option&gt;"; }
  • 试试这个 echo "";
  • mysql_* 函数自 PHP 5.5 起已被弃用(并且在 PHP 7 中完全删除),如果可以的话,您应该stop using them。您应该选择另一个允许您使用 prepared statements 的 API(在处理变量时您确实应该使用它),例如 mysqli_* 或 PDO - 请参阅 choosing an API

标签: php select post


【解决方案1】:

你应该使用

echo "<option value ='".$row['countryName']."'>". $row['countryName']."</option>";

我想补充一点,MySQL 在 PHP5 中已弃用并从 PHP7 中删除。你的 PHP 版本是什么。如果您使用 PHP 5 或更高版本,请使用 mysqli。

【讨论】:

  • 好吧,当我使用 mysqli 连接到 localhost 时,它工作正常。但是一旦连接到远程服务器 mysqli 就不能以某种方式进行查询。我正在使用 mysql php5。
  • 检查远程服务器上 mysqli 的连接。如果我们很好,那么您将查询发送到服务器是错误的。您的远程服务器的 PHP 版本是什么。
  • 我使用的是 PHP 5.6。 Mysqli 连接到服务器,因为没有打印出错误。但是查询结果没有正确呈现。
猜你喜欢
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多