0

I'm having this issue with my code.

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 ''articles' WHERE (`title` LIKE '%EPA%') OR (`text` LIKE '%EPA%')' at line 1

This is my code:

 $raw_results = mysqli_query($conn, "SELECT * FROM 'articles'
            WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysqli_error($conn));
Arulkumar
  • 12,966
  • 14
  • 47
  • 68
GetRekt
  • 23
  • 1
  • 2
  • 6
  • 1
    Show us the final query. Not the code that builds it. – slepic Jun 26 '19 at 05:19
  • 1
    **WARNING: You are vulnerable to SQL injection!** Attackers are able to easily run arbitrary commands against your database. You should *strongly* consider using [prepared statements](https://stackoverflow.com/a/60496/2605758) and parameterized queries. You can do this using either PDO or MySQLi. – Hoppeduppeanut Jun 26 '19 at 05:38

1 Answers1

2

The immediate cause of the error is probably that you put the table name articles into single quotes. We could fix that and move on, but now would be a good time to learn about prepared statements, which fix another problem with your code. The other major problem with your query string is that you are building via string concatenation. This leaves open the possibility that someone from the outside might inject malicious SQL fragments, in order to run commands which you might not want being run. Consider this updated version of your code:

$query = '%'.$query.'%';
$stmt = $mysqli->prepare("SELECT * FROM articles WHERE title LIKE ? OR text LIKE ?");
$stmt->bind_param("ss", $query, $query);
$stmt->execute();
$raw_results = $stmt->get_result();
Dharman
  • 30,962
  • 25
  • 85
  • 135
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360