创建PHP查询在多个位置使用的函数
我有一个国家,州,城市级联下拉列表,我用在添加属性和编辑属性页。country表有两列:country\u id和country\u name 现在,当我想将值加载到编辑页面时,我想将country_id转换为country_name以显示在下拉列表中。我已经能够使用以下代码执行此操作:创建PHP查询在多个位置使用的函数,php,dropdown,Php,Dropdown,我有一个国家,州,城市级联下拉列表,我用在添加属性和编辑属性页。country表有两列:country\u id和country\u name 现在,当我想将值加载到编辑页面时,我想将country_id转换为country_name以显示在下拉列表中。我已经能够使用以下代码执行此操作: <?php $country_id = $data['property_country']; $select = $con->prepare("SELECT country_name from
<?php
$country_id = $data['property_country'];
$select = $con->prepare("SELECT country_name from tbl_country where country_id='$country_id'");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();
$data2 = $select->fetchAll();
foreach ($data2 as $row1) {
echo $row1['country_name'];
}
?>
最好给我们提供更多关于您的程序是如何构造的信息,但无论如何,一般的做法是创建一个国家级
并创建一个方法,在该方法中,您可以在不使用循环的情况下放置代码
当您需要数据时,导入类文件,实例化传递国家id的类并调用该方法。提供一个更多关于问题的信息,例如您的数据将如何运行以及您的答案如何运行
首先创建一个类,然后在调用页面上添加require_once“className.php”
class A {
function __construct() {
}
function __destruct() {
}
public function countryIdToName($data, $con = null) {
//Create you connection here or just pass connection link
$country_id = $data['property_country'];
$select = $con->prepare("SELECT country_name from tbl_country where country_id='$country_id'");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();
$data2 = $select->fetchAll();
foreach ($data2 as $row1) {
echo $row1['country_name'];
}
}
}
现在,在您的调用文件上,让我们取文件名为abc.php
require_once 'A.php';
$classObject = new A();
$classObject->countryIdToName($data,$conn);
class国家{
受保护的$id;
函数构造($id){
$this->id=$id;
}
职能(国家){
粘贴代码并将$this->id作为参数传递,然后返回$data
}
}
现在在你看来
导入视图顶部的类;
$countries=新国家/地区(传递id);
$list=$countries->getCountries()代码>
然后结束循环。程序在核心中结构化。因此,我有一个文件夹classes,我可以在其中放置文件,并调用视图文件。`classcountry{protected$id;function{uuu-construct($id){$this->id=$id;}getCountries(){粘贴代码并将$this->id作为参数传递}