根据下拉菜单修改MySQL查询

时间:2018-07-15 作者:Morts81

我希望能够根据下拉菜单中的选择修改MySQL查询。这将更新页面上显示的后续表格。

我当前的代码如下(注意我正在使用PHP code snippets (Insert PHP) 插件)但是,这没有预期的结果,因为没有生成表。

如有任何帮助,我们将不胜感激。

<form method="POST">
<select name="post_ID">
    <option value="21">21</option>
    <option value="22">22</option>
</select>
</form>

[insert_php]
global $wpdb;
echo $_POST[\'post_ID\'];
$myQuery = $wpdb->get_results(\'SELECT * FROM \' . $wpdb->prefix.\'posts\' . \'WHERE ID = $_POST[\'post_ID\']\');

if($myQuery){
echo \'<table>\';
    echo "<tr>"; 
    echo "<th>Header 1</th>"; 
    echo "<th>Header 2</th>"; 
    echo "<th>Header 3</th>"; 
    echo "<th>Header 4</th>"; 
    echo "</tr>"; 
foreach ( $myQuery as $result ) 
    {
        echo \'<tr><td>\'.$result->post_title.\'</td><td>\'.$result->post_status.\'</td><td>\'.$result->post_date_gmt.\'</td><td>\'.$result->ID.\'</td></tr>\';
    }
echo \'</table>\';
}
[/insert_php]

1 个回复
最合适的回答,由SO网友:Atlas_Gondal 整理而成

您不需要编写自己的查询,只需使用wordpress函数即可。

例如,通过id获取post;使用get_post

<form method="POST">
  <select name="post_ID">
    <option value="21">21</option>
    <option value="22">22</option>
  </select>

 <input type="submit" value="Get Selected Value" />
</form>

<?php

 $post_id = $_POST[\'post_ID\'];

 if ( is_int( $post_id ) && !empty ($post_id ) ){

   $post = get_post( $post_id );

   if($post){

      echo \'<table>\';
      echo "<tr>";
      echo "<th>Header 1</th>";
      echo "<th>Header 2</th>";
      echo "<th>Header 3</th>";
      echo "<th>Header 4</th>";
      echo "</tr>";

      //foreach loop is removed because it will return only single object
      echo \'<tr><td>\'.$post->post_title.\'</td><td>\'.$post->post_status.\'</td><td>\'.$post->post_date_gmt.\'</td><td>\'.$post->ID.\'</td></tr>\';

      echo \'</table>\';
  }

}
顺便说一句,如果您需要检索多篇帖子,请尝试get_posts

结束