MySQLl where子句

时间:2017-07-24 19:10:34

标签: php mysql pdo

我有一个用户可以在

后面输入的表单
Shape = Round, Triangle, Square, Rectangle, Rhombus, Kite, Decagon
Color = Red, Black, Green, Yellow, Blue, White
Size = 1, 2, 3 … 11

在数据库中,有多个具有上述特征的项目 示例红色圆形,大小为5,另一个圆形,黑色,大小为1等。

用户可以只选择一个或全部3个特征并提交表单,我想显示已创建的结果。 示例:如果仅选择用户颜色结果,则无论形状或大小如何,都应显示所选颜色的所有项目。如果用户选择形状和颜色所有选择了形状和颜色的项目。 我的问题是如何创建查询来执行此操作?

我尝试的代码

if (!empty($_POST["shape"])):
    $shape = trim($_POST["shape"]);
else:  
    $shape = "";
endif;

if (!empty($_POST["color"])):
    $color = strtolower(trim($_POST["color"]));
else:  
    $color = "";
endif;
if (!empty($_POST["size"])):
    $size = trim($_POST["size"]);
else:  
    $size = "";
endif;

SQL = SELECT * FROM items WHERE item_shape = $shape &&  item_color = $color && item_size = $size 

结果总是0,除非我只使用一个WHERE子句,它只像shape一样工作,并从命令中删除其他子句。

另外,我尝试像这样改变

if (!empty($_POST["shape"])):
    $shape = trim($_POST["shape"]);
else:  
    $shape = " Round, Triangle, Square, Rectangle, Rhombus, Kite, Decagon";
endif;

// changed all post parameters sane wat u did with shape

SQL = SELECT * FROM items WHERE item_shape in ($shape) &&  item_color in ($color) && item_size = ($size) 

我怎样才能做到这一点?感谢你的时间。

4 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

// add as many features as you like to filter in this array
$features = array();

if (!empty($_POST["shape"])):
    $features['shape'] = trim($_POST["shape"]);
endif;

if (!empty($_POST["color"])):
    $features['color'] = strtolower(trim($_POST["color"]));
endif;

if (!empty($_POST["size"])):
    $features['size'] = trim($_POST["size"]);
endif;

$sql = "SELECT * FROM items";

// if there is any feature in the array
if ( ! is_null($features))
{
    $i = 0;
    $len = count($features);

    // check each one of the features 
    foreach ($features as $feature => $feature_value) {
        if ($i == 0)
        {
            // if the first item, use WHERE
            $sql .= ' WHERE ';
        } else
        {
            // else, use &&
            $sql .= ' && ';
        }

        $sql .= 'item_' . $feature . ' = ' . $feature_item;
        $i++;
    }
}

答案 1 :(得分:2)

您可以构建动态查询,使用表单发送的名称映射数据库的列名。在使用foreach检查每个元素是否具有值时,如果为正,则在$new中创建新元素。最后使用WHERE创建implode()子句,它将使用AND关键字粘贴数组中的哪个元素。

$fakePost = array('Shape' => '', 'Color' => '', 'Size' =>'2');


$fieldsName = ['Shape' => 'shape_list', 'Round' => 'round_list', 'Size' => 'size_list', 'Color' => 'color_list'];
$new = [];
foreach($fakePost as $k => $v){
    if(!empty($v)){
        $new[] = $fieldsName[$k] . " = '$v'";
    }   
}

if(!empty($new)){
    echo ' WHERE '. implode(' AND ', $new);
}else{
    echo 'please select some value';
}

输出:

WHERE size_list = '2'

或:

WHERE shape_list = 'green' AND size_list = '2'

答案 2 :(得分:0)

这是我的版本:

  • getItems.php :获取已发布的值并调用函数以根据它们获取项目(getItems())。
  • itemsFunctions.php :处理项目的所有功能都可以在单独的文件中找到,以便重复使用。

getItems.php

<?php

require_once 'itemsFunctions.php';

$shape = isset($_POST['shape']) ? trim($_POST['shape']) : '';
$color = isset($_POST['color']) ? strtolower(trim($_POST['color'])) : '';
$size = isset($_POST['size']) ? trim($_POST['size']) : 0;

// Get items.
$items = getItems($shape, $color, $size);

// Do something with the fetched items
// (like display them in a table/grid).

itemsFunctions.php

/**
 * Fetch items from items table.
 * 
 * @param string $shape [optional] Item shape.
 * @param string $color [optional] Item color.
 * @param integer $size [optional] Item size.
 * @return array Fetched items.
 */
function getItems($shape = '', $color = '', $size = 0) {
    // Array containing the WHERE conditions.
    $where = array();

    // Add WHERE conditions to array based on the given values.
    if (!empty($shape)) {
        $where[] = 'item_shape = ' . $shape;
    }

    if (!empty($color)) {
        $where[] = 'item_color = ' . $color;
    }

    if ($size > 0) {
        $where[] = 'item_size = ' . $size;
    }

    // Build the sql statement.
    $sql = sprintf('SELECT * FROM items %s'
            , count($where) > 0 ? ' WHERE ' . implode(' AND ', $where) : ''
    );

    // Run query for fetching items by using the sql statement...
    // Fetched items as array.
    $items = array(
        array(
            'item_shape' => 'round',
            'item_color' => 'red',
            'item_size' => '45',
        ),
        array(
            'item_shape' => 'square',
            'item_color' => 'blue',
            'item_size' => '1258',
        ),
    );

    return $items;
}

/**
 * Add item to items table.
 * 
 * @param string $shape [optional] Item shape.
 * @param string $color [optional] Item color.
 * @param integer $size [optional] Item size.
 * @return integer Last insert id.
 */
function addItem($shape = '', $color = '', $size = 0) {
    //...
}

/**
 * Update item in items table.
 * 
 * @param integer $id Item ID.
 * @param string $shape [optional] Item shape.
 * @param string $color [optional] Item color.
 * @param integer $size [optional] Item size.
 * @return bool TRUE if updated, FALSE otherwise.
 */
function updateItem($id, $shape = '', $color = '', $size = 0) {
    // Validate item ID...
    //...
}

/**
 * Remove item from items table.
 * 
 * @param integer $id Item ID.
 * @return bool TRUE if deleted, FALSE otherwise.
 */
function deleteItem($id) {
    // Validate item ID...
    //...
}

备注:

  • 大小应该是整数。
  • 我使用了函数sprintf()。它打印为echo(),但它 允许使用占位符(%s)。我经常使用它 构建复杂的sql语句。

建议:在PHP代码中使用prepared statements以避免MySQL注入。

祝你好运!

答案 3 :(得分:0)

据我所知,query下面的问题会给出您想要的确切结果

    $shape = $_POST['shape'])??trim($_POST['shape']) ;
    $color = $_POST['color'])??trim($_POST['color']) ;
    $size  = $_POST['color'])??trim($_POST['color']) ;

    $where = array();

    if (!empty($shape)) {

        $shape_arr = explode(',', $shape);

        $temp_shape = '';

        foreach ($shape_arr as $key => $value) {
          $temp_shape .= "'".$value."',";
        }

        $temp_shape = rtrim($temp_shape,',');

        $where[] = " item_shape IN(".$temp_shape.") ";
    }

    if (!empty($color)) {

        $color_arr = explode(',', $color);

        $temp_color = '';

        foreach ($color_arr as $key => $value) {
          $temp_color .= "'".$value."',";
        }

        $temp_color = rtrim($temp_color,',');

        $where[] = " item_color IN(".$temp_color.") ";
    }


    if (!empty($size)) {
        $where[] = " item_size IN(".$size.") ";
    }

    $sql = "SELECT * FROM items ";

    if(count($where)>0){
      $sql .= " WHERE ". implode(" AND ", $where) ;
    }