简体   繁体   中英

How to print records from a MySQL table based on a field being equal to one of multiple values

I have a table full of member records. There is a field called MB_COUNTRY, I want to display records when there MB_COUNTRY field = one of 6 values that I have chose.

My Query:

        <?php
        $sql = "SELECT * FROM member ";
        $sql .= "WHERE MB_COUNTRY IN('103', '39', '149', '193', '194', '229')";
        $query1 = mysql_query($sql) or die(mysql_error());
        ?>

My table being displayed

            <table width="70%" cellpadding="5" cellspace="5" class="table table-hover table-striped">

            <tr>
                <td><strong>Company Name</strong></td>
                <td><strong>Website</strong></td>
                <td><strong>Phone</strong></td>
                <td><strong>Address</strong></td>
            </tr>

            <?php while ($row = mysql_fetch_array($query1)) { ?>
            <tr> 
                <td><?php echo $row['MB_COMPANY'];?></td>
                <td><a href="http://<?php echo $row['MB_MOBILE'];?>"><?php echo $row['MB_MOBILE'];?></a></td>
                <td><?php echo $row['MB_PHONE'];?></td>
                <td><?php echo $row['MB_ADDRESS1'];?>, <?php echo $row['MB_ADDRESS2'];?>, <?php echo $row['MB_TOWN'];?>, <?php echo $row['MB_COUNTY'];?></td>
            </tr>
            <?php } ?>

            </table>

error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE MB_COUNTRY = '103' OR MB_COUNTRY = '39' OR MB_COUNTRY = '149' OR MB_COUNTR' at line 1

As you can see I have tried using the OR operator however this produces an error (above). I simply want to display records that have a MB_COUNTRY value of: 103' '39' '149' '193' '194' '229'

If anyone has a way of doing this I'd really appreciate it.

You have to concatenate your mysql query. You also should use IN() for better performance and cleaner code.

$sql = "SELECT * FROM member ";
$sql .= "WHERE MB_COUNTRY IN('103', '39', '149', '193', '194', '229')";

You need to concate the variable

    $sql = "SELECT * FROM member ";

    $sql .="WHERE MB_COUNTRY = '103' OR MB_COUNTRY =  ...";

Your $sql variable is reassigned to

 $sql ="WHERE MB_COUNTRY = '103' OR MB_COUNTRY =  ...";

And hence getting the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM