首页 > 解决方案 > mysql查询中的concat()函数或替代方案

问题描述

我正在尝试在 mysql 查询中添加一个字符之前/之后的值。但我不能让它工作。这是在我的情况下不起作用的部分:

$query = "select CONCAT ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC"; 

你可以在下面看到完整的代码。请有任何想法为什么它不起作用或我可以获得替代解决方案。谢谢。

<div class="container">
<div class="left">
<?php

include ("etc/config.php");

$query = "select concat ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC"; 
$result = mysqli_query($link, $query); 
if (!$result) { 
    $message = 'ERROR:' . mysqli_error($link); 
    return $message; 
} else { 
    $i = 0; 
    echo '<form name="select" action="" method="GET">';
    echo '<select name="mySelect" id="mySelect"  size="44" onchange="this.form.submit()">'; 
    while ($i < mysqli_field_count($link)) { 
        $meta =  
            mysqli_fetch_field_direct($result, $i); 
        echo '<option>' . $meta->name . '</option>'; 
        $i = $i + 1; 
    } 
    echo '</select>';
    echo '</form>';
}

    ?>

   </div>
  <div>

  <?php

if(isset($_GET['mySelect'])) {
    $myselect = $_GET['mySelect']; 
    $sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";   
    $result = mysqli_query($link, $sql);   

    if ($result->num_rows > 0) {

        $table_row_counter = 3;
        echo '<table>';

        while($row = $result->fetch_assoc()) 
        {
            $table_row_counter++;
            if ($table_row_counter % 30 == 1) {
                echo '</table>';
                echo '<table>';
            }

            echo "<tr><td>" . $row["mySelect"] . "</td></tr>";

        }
    }
} 

echo '</table>';
mysqli_close($link);
?> 

</div>
</div>

标签: phpmysql

解决方案


对于代码的后半部分,您可以这样做:请注意,您不需要在初始查询中连接任何内容

if(isset($_GET['mySelect'])) {
    // configure every option here, if there's not pre/postfix, use a blank string
    $prepostfixes = [
        'DuRpt' => ['.', '.'],
        'DaRpt' => ['', ''],
    ];
    $myselect = $_GET['mySelect'];
    if (!isset($prepostfixes[$myselect])) {
        die ('Unknown Select'); // this will prevent sql injection
    }
    $sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";
    $result = mysqli_query($link, $sql);

    if ($result->num_rows > 0) {

        $table_row_counter = 3;
        echo '<table>';
        $prefix = $prepostfixes[$myselect][0];
        $postfix = $prepostfixes[$myselect][1];

        while($row = $result->fetch_assoc())
        {
            $table_row_counter++;
            if ($table_row_counter % 30 == 1) {
                echo '</table>';
                echo '<table>';
            }

            echo "<tr><td>" . $prefix . $row["mySelect"] . $postfix . "</td></tr>";

        }
    }
}

推荐阅读