Search code examples
phphtmlmysqlvariablessql-like

mysqli where clause with php getting error


i'am trying to use mysqli select where clause with a variable in php but i get this error

Error: Our query failed to execute and here is why: Query: SELECT * FROM Products WHERE 'ProductCategory' LIKE laptops Errno: 1054 Error: Unknown column 'laptops' in 'where clause'

  viewby.php
 <?php
 include('db/functions.php');
  $result= getproductsbycategory($_GET['ctg']);

while($product = $result->fetchassoc()){
    echo $product['ProductName'];
}

?>

//functions.php

 <?php
 function getproductsbycategory($ctg){
 include('connect.php');
     $sql = "SELECT * FROM Products WHERE 'ProductCategory' LIKE $ctg ";
 if(! $result = $mysqli->query($sql))
{
    echo "Error: Our query failed to execute and here is why: \n";
    echo "Query: " . $sql . "\n";
    echo "Errno: " . $mysqli->errno . "\n";
    echo "Error: " . $mysqli->error . "\n";
    exit;
}
return $result;
 }
  ?>
 //index.php

<a href="viewby.php?ctg=<?php echo $ctg; ?>">

 //viewby.php

<?php
 include('db/functions.php');
  $result= getproductsbycategory($_GET['ctg']);

while($product = $result->fetchassoc()){
    echo $product['ProductName'];
}

?>

i really have no idea what is the problem ,if i run the query from phpmyadmin it work fine, Sorry if the problem is too obvious thanks


Solution

  • try to change your query with this one

     $sql = "SELECT * FROM Products WHERE `ProductCategory` LIKE '%$ctg%' ";
    

    you were inserting simple quotes ' instead of this one `