Qube
Qube

Reputation: 573

how to use LIKE clause in mysql when using with php

i'm trying to use like in mysql from php and i write this code

$query = mysqli_query($connection, "SELECT * FROM items order by create_at desc where content LIKE '" . $content . "%'")
  or die(mysqli_error($connection));

but it says there is an error in my syntax it says like this

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'where content LIKE 'c%'' at line 1

Upvotes: -1

Views: 4911

Answers (3)

Erdz Wardex
Erdz Wardex

Reputation: 94

$query = mysqli_query($connection, "SELECT * FROM items order by create_at desc where content LIKE '%.$content.%'") or die(mysqli_error($connection));

Upvotes: 0

Muhammad Tahir Qaiser
Muhammad Tahir Qaiser

Reputation: 708

Order BY clause always come in the end, use WHERE clause first and then use ORDER BY

Solution would be this :

SELECT * FROM items where content LIKE 'yourVariable%' ORDER BY create_at DESC 

Upvotes: 4

Naveed Ramzan
Naveed Ramzan

Reputation: 3593

Your PHP code should be:

$query  = "SELECT * FROM items  where content LIKE '" . $content . "%' order by create_at desc";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));

Query clauses sequence should be :

  • Select
  • From
  • join
  • where
  • group by
  • order by
  • limit

Upvotes: 1

Related Questions