Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在WordPress中使用PHP和MySQL组合几个选择框的结果_Php_Mysql_Wordpress_Jquery Selectbox - Fatal编程技术网

在WordPress中使用PHP和MySQL组合几个选择框的结果

在WordPress中使用PHP和MySQL组合几个选择框的结果,php,mysql,wordpress,jquery-selectbox,Php,Mysql,Wordpress,Jquery Selectbox,我有4个动态相关选择框,现在我想将4个选择的结果合并到一个查询中。我有下面所有的相关代码 选择框的字体结束部分 <form class="select-boxes" action="<?php echo site_url("/part-search-result/"); ?>" method="POST" target="_blank"> <?php include(__DIR__.'/inc/part-search.php'); ?> </fo

我有4个动态相关选择框,现在我想将4个选择的结果合并到一个查询中。我有下面所有的相关代码

选择框的字体结束部分

<form class="select-boxes" action="<?php echo site_url("/part-search-result/"); ?>" method="POST" target="_blank">
    <?php include(__DIR__.'/inc/part-search.php'); ?>
</form>
ajaxdata.php

<?php
    include( __DIR__.'/db-config.php' );
    $query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
    $rowCount = $query->num_rows;
?>

<select name="manufacturer" id="manufact" onchange="manufactText(this)">
    <option value="">Select Manufacturer</option>
    <?php
        if($rowCount > 0){
            while($row = $query->fetch_assoc()){
                echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
            }
        }else{
            echo '<option value="">Manufacturer Not Available</option>';
        }
    ?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
    function manufactText(ddl) {
        document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
    }
</script>

<select name="type" id="type" onchange="typeText(this)">
    <option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
    function typeText(ddl) {
        document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
    }
</script>

<select name="year" id="year" onchange="yearText(this)">
    <option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
    function yearText(ddl) {
        document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
    }
</script>

<select name="model" id="model" onchange="modelText(this)">
    <option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
    function modelText(ddl) {
        document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
    }
</script>

<input type="submit" name="search" id="search" value="Search">


<script type="text/javascript">
    jQuery(function($) {
        $('#manufact').on('change',function(){
            var manufactID = $(this).val();
            if(manufactID){
                $.ajax({
                    type:'POST',
                    url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
                    data:'manufact_id='+manufactID,
                    success:function(html){
                        $('#type').html(html);
                        $('#year').html('<option value="">Select Type First</option>');
                    }
                });
            }else{
                $('#type').html('<option value="">Select Manufact First</option>');
                $('#year').html('<option value="">Select Type First</option>');
            }
        });

        $('#type').on('change',function(){
            var typeID = $(this).val();
            if(typeID){
                $.ajax({
                    type:'POST',
                    url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
                    data:'type_id='+typeID,
                    success:function(html){
                        $('#year').html(html);
                        $('#model').html('<option value="">Select Year First</option>');
                    }
                });
            }else{
                $('#year').html('<option value="">Select Type First</option>');
                $('#model').html('<option value="">Select Year First</option>');
            }
        });

        $('#year').on('change',function(){
            var yearID = $(this).val();
            if(yearID){
                $.ajax({
                    type:'POST',
                    url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
                    data:'year_id='+yearID,
                    success:function(html){
                        $('#model').html(html);
                    }
                });
            }else{
                $('#model').html('<option value="">Select Year First</option>');
            }
        });
    });
</script>
<?php

include( __DIR__.'/db-config.php' );

if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
    $query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");

    $rowCount = $query->num_rows;

    if($rowCount > 0){
        echo '<option value="">Select Type</option>';
        while($row = $query->fetch_assoc()){
            echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
        }
    }else{
        echo '<option value="">Type Not Available</option>';
    }
}

if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
    $query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");

    $rowCount = $query->num_rows;

    if($rowCount > 0){
        echo '<option value="">Select Year</option>';
        while($row = $query->fetch_assoc()){
            echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
        }
    }else{
        echo '<option value="">Year Not Available</option>';
    }
}

if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
    $query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");

    $rowCount = $query->num_rows;

    if($rowCount > 0){
        echo '<option value="">Select Model</option>';
        while($row = $query->fetch_assoc()){
            echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
        }
    }else{
        echo '<option value="">Model Not Available</option>';
    }
}

?>
<?php

if (isset($_POST['search'])) {
    $clauses = array();
    if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
        $clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
    }
    if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
        $clauses[] = "`type` = '{$_POST['type_text']}'";
    }
    if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
        $clauses[] = "`year` = '{$_POST['year_text']}'";
    }
    if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
        $clauses[] = "`model` = '{$_POST['model_text']}'";
    }
    $where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
    $sql = "SELECT * FROM `wp_products` ". $where;
    $result = filterTable($sql);
} else {
    $sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
    $result = filterTable($sql);
}

function filterTable($sql) {
    $con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
    if (!$con) {
        die('Could not connect: ' . mysqli_error($con));
    }
    $filter_Result = mysqli_query($con, $sql);
    return $filter_Result;
}

?>

    <?php get_header(); ?>

    <div class="container">
        <div id="products" class="row list-group">
        <?php while ( $rows = mysqli_fetch_array($result) ): ?>
            <div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">
                <div class="thumbnail">
                    <?php
                        echo '<img name="product-image" class="group list-group-image hvr-bob" src=' . $rows['image_url'] . ' width="400px" height="250px" alt="" />';
                    ?>
                    <div class="caption">
                        <h4 class="group inner list-group-item-heading">
                        <?php
                            echo "Manufacturer:\t".$rows['manufacturer'].'<br>';
                            echo "Type:\t".$rows['type'].'<br>';
                            echo "Year:\t".$rows['year'].'<br>';
                            echo "Model:\t".$rows['model'].'<br>';
                            echo '<br>';
                            echo "Description:\t".$rows['description'].'<br>';
                        ?>
                        </h4>                           
                    </div>
                </div>
            </div>
        <?php endwhile; ?>
        </div>
    </div>

    <?php get_footer(); ?>
现在我的问题是:

如果只选择前一个框,或选择前两个框,然后单击
搜索
按钮,它将成功跳转到结果页面。但是,如果连续选择第三个框,结果页将消失,Chrome Console将返回错误:


加载资源失败:服务器响应状态为404(未找到)

让我问你一个问题。您已将其标记为WordPress网站。对的那么为什么不使用内置的数据库处理程序,
$wpdb
来准备数据库并与之通信呢?这是使用数据库最安全、最快捷的方法

修订代码

在这里,我修改了您的代码以执行以下操作:

  • 使用
    $wpdb->prepare
    $\u POST
    值进行清理,以保护数据库免受恶意用户的攻击
  • 通过在列名列表中循环并使用您指定的字段命名模式(在列名后面加上
    \u text
    )来删除冗余
  • 使用
    $wpdb->get_results()
    获取结果
修订后的守则如下:

/**
 * Build the search's WHERE SQL from the form's $_POST fields.
 *
 * @since 1.0.0
 *
 * @return string
 */
function build_search_where_sql() {
    global $wpdb;

    $column_names = array(
        'manufacturer',
        'type',
        'year',
        'model',
    );

    $where_clauses = [];
    foreach( $column_names as $column_name ) {
        $post_key = $column_name . '_text';
        if ( isset( $_POST[ $post_key ] ) && $_POST[ $post_key ] ) {
            $where_clauses[] =  $wpdb->prepare( "{$column_name} = %s", $_POST[ $post_key ] );
        }
    }

    if ( empty( $where_clauses ) ) {
        return '';
    }

    $where_sql = " WHERE " . join( ' AND ', $where_clauses );

    return $where_sql;
}

/**
 * Get the search results from the database.  If the records
 * do not exist or an error occurs, false is returned.  Else,
 * an array with stdClass objects for each record is returned.
 *
 * @since 1.0.0
 *
 * @return bool|array
 */
function get_search_database_results() {
    $where_sql = isset( $_POST['search'] )
        ? build_search_where_sql()
        : "WHERE manufacturer = ''";

    if ( ! $where_sql ) {
        return false;
    }

    global $wpdb;

    $sql_query = "SELECT * FROM wp_products {$where_sql};";

    $records = $wpdb->get_results( $sql_query );

    if ( ! $records ) {
        return false;
    }

    return $records;
}
更新:您的战略

现在,我已经看到了您提出的HTML代码,并且知道您正在学习构建网站,让我们为您的项目讨论一种不同的体系结构策略

  • 不要使用自定义数据库表
  • 改用名为
    products
    的自定义帖子类型
  • 使用post元数据设置每个产品的属性,即制造商、型号、年份、类型等
  • 使用表单插件,例如忍者表单
  • 如果你有足够的技术能力,你可以自己为元数据构建元框。否则,您可以使用第三方插件,如CMB2或ACF
  • 自定义帖子类型

    WordPress为您提供了添加自定义内容的功能。它们提供内置的post类型。我们开发人员可以添加特定内容上下文的自定义内容。Products是定制职位类型的一个很好的候选者

    您可以在上生成代码。实际上,创建它只需要几行代码

    在哪里可以了解自定义帖子类型

    嗯,有很多教程。提供文档和示例。我在学校教它。Tuts+有很多教程。还有许多其他的

    为什么要自定义Post类型而不是自定义Db表

    是的,您可以构建自定义数据库表。但它需要您添加模式、为表种子、编写管理员与内容交互的接口,然后编写并保护交互。要填充
    选择
    中的选项,必须使用
    $wpdb
    查询数据库,然后编写一个模型将其转换为视图。然后您必须编写表单处理以进行交互和保存

    换句话说,这将花费你的时间和金钱。为什么?因为它更多的是代码,而不是WordPress的原生代码。您必须自己编写、保护、测试和维护它

    如果您想坚持当前的战略

    如果您更愿意坚持使用自定义数据库表策略,那么以下是一些帮助您解决问题的建议:

  • 对于每个
    select
    元素,不需要隐藏的
    输入。为什么?发布表单时,为每个
    选择设置的选项将发布回服务器
  • 我将
    select
    名称更改为一个数组,如下所示:
    name=“part select[manufacturer]”
    然后对type、model、year等重复操作。然后您可以抓取
    $\u POST['part-select']
    以获取所有值
  • 您将要添加以保护内容。在执行AJAX时,请确保将其与数据包一起传递
  • 使用,可以从数据库请求记录。为了构建SQL查询,您需要修改我给您的代码。然后循环遍历结果,构建要发送回前端的HTML
  • 我喜欢在服务器端构建HTML标记,然后在执行AJAX时将其发送回前端

  • 干杯。

    让我问你一个问题。您已将其标记为WordPress网站。对的那么为什么不使用内置的数据库处理程序,
    $wpdb
    来准备数据库并与之通信呢?这是使用数据库最安全、最快捷的方法

    修订代码

    在这里,我修改了您的代码以执行以下操作:

    • 使用
      $wpdb->prepare
      $\u POST
      值进行清理,以保护数据库免受恶意用户的攻击
    • 通过在列名列表中循环并使用您指定的字段命名模式(在列名后面加上
      \u text
      )来删除冗余
    • 使用
      $wpdb->get_results()
      获取结果
    修订后的守则如下:

    /**
     * Build the search's WHERE SQL from the form's $_POST fields.
     *
     * @since 1.0.0
     *
     * @return string
     */
    function build_search_where_sql() {
        global $wpdb;
    
        $column_names = array(
            'manufacturer',
            'type',
            'year',
            'model',
        );
    
        $where_clauses = [];
        foreach( $column_names as $column_name ) {
            $post_key = $column_name . '_text';
            if ( isset( $_POST[ $post_key ] ) && $_POST[ $post_key ] ) {
                $where_clauses[] =  $wpdb->prepare( "{$column_name} = %s", $_POST[ $post_key ] );
            }
        }
    
        if ( empty( $where_clauses ) ) {
            return '';
        }
    
        $where_sql = " WHERE " . join( ' AND ', $where_clauses );
    
        return $where_sql;
    }
    
    /**
     * Get the search results from the database.  If the records
     * do not exist or an error occurs, false is returned.  Else,
     * an array with stdClass objects for each record is returned.
     *
     * @since 1.0.0
     *
     * @return bool|array
     */
    function get_search_database_results() {
        $where_sql = isset( $_POST['search'] )
            ? build_search_where_sql()
            : "WHERE manufacturer = ''";
    
        if ( ! $where_sql ) {
            return false;
        }
    
        global $wpdb;
    
        $sql_query = "SELECT * FROM wp_products {$where_sql};";
    
        $records = $wpdb->get_results( $sql_query );
    
        if ( ! $records ) {
            return false;
        }
    
        return $records;
    }
    
    更新:您的战略

    现在,我已经看到了您提出的HTML代码,并且知道您正在学习构建网站,让我们为您的项目讨论一种不同的体系结构策略

  • 不要使用自定义数据库表
  • 改用名为
    products
    的自定义帖子类型
  • 使用post元数据设置每个产品的属性,即制造商、型号、年份、类型等
  • 使用表单插件,例如忍者表单
  • 如果你有足够的技术能力,你可以自己为元数据构建元框。否则,您可以使用第三方插件suc