简体   繁体   中英

PHP MySQL Where clause isn't working

I have a database like which has multiple columns and when querying it with a WHERE clause it won't get any results. Here is the code I am using :

$columns = $_GET['var'];
$where = $_GET['where'];
$checkValue = $_GET['checkValue'];
$userInput = $_GET['userInput'];

$query = "SELECT ";

foreach($columns as $val)
    $query .= "$val, ";

$query .= "FROM Email";

if($where === "yes")
    $query .= " WHERE $checkValue = '$userInput'";

$columns is multiple checkboxes for the user to select which columns they wish to see. It works perfectly except when adding the where clause. When I've been testing it I made sure that the it was exactly the same as in the database. Also the $checkValue is a dropdown list which values are exactly the same as in the database. Also just to note later on I edit the query so the last comma is removed.

To print it out I use :

while($c = mysqli_fetch_assoc($results)){
    foreach($columns as $val){
        $header = ucwords($val);
        echo "<b>$header</b><br>";
        echo $c[$val]."<br>";   
    }
    echo "-------------------------------<br>";
}

This is the query that is outputted when not using the where clause and works:

 SELECT date, mediatype FROM Email

And here is the query that doesnt work:

 SELECT date, mediatype FROM Email WHERE mediatype = 'Blog'

Any advice?

EDIT: Here is the table with: D b

There is more columns but these are ones I want to focus on.

Your generate SQL request seems to have a syntax error. Just change the way you generate it.

Instead of

foreach($columns as $val)
  $query .= "$val, ";

Try

$query .= implode(', ' $columns);

That will skip the last comma.

The blog column had an extra empty line that 'Blog%' wasn't working on. I went in the database and deleted the extra line and used the query again and it worked.

Thanks everyone for the help :)

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