Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL parameterized query with LIKE '% ? %' PHP

Tags:

php

mysql

I have a Search function in php and have created it using a parameterized query to make it secure.

$words = $_POST['words']//words is the form that has the words submitted by the user 
$array = explode(',', $words);
$con = mysqli_connect("localhost","user","pass","database");

$stmt = $con->prepare(" SELECT column_name FROM table WHERE column_name LIKE ?")
foreach($array as $key) { //searches each word and displays results   
  $stmt->bind_param('s', $key)
  $stmt->execute();
  $result = $stmt->get-result();

  while($row = $result->fetch_assoc(){
    echo $row["column_name"]
  }
}

however I want $stmt statement to be

  $stmt = $con->prepare(" SELECT column_name FROM table WHERE column_name LIKE '%?%' ")

otherwise people have to type in the entire value of column_name to find it.

like image 821
user3634933 Avatar asked Apr 07 '15 01:04

user3634933


People also ask

How do I write a parameterized query in SQL?

Declare statements start with the keyword DECLARE , followed by the name of the parameter (starting with a question mark) followed by the type of the parameter and an optional default value. The default value must be a literal value, either STRING , NUMERIC , BOOLEAN , DATE , or TIME .

How pass variable in SQL query in PHP?

Show activity on this post. $user = mysql_real_escape_string($_POST["userlogin"]); mysql_connect("uritomyhost","myusername","password"); mysql_select_db('mydatabase'); mysql_query('UPDATE table SET field = field + ($userlogin)');

Is SQL injection possible with parameterized query?

Parameterized query is used to solve SQL injection attack as it pass values as constant at backend.

What is $STMT in PHP Mysqli?

" $stmt " obviously (I think) stands for "statement". As a variable name it's arbitrary, you can name that variable anything you want. $stmt is just rather idiomatic. A prepared statement as such is a database feature.


1 Answers

You can use CONCAT(), like this:

LIKE CONCAT ('%', ?, '%')
like image 86
Funk Forty Niner Avatar answered Oct 06 '22 21:10

Funk Forty Niner