简体   繁体   中英

MYSQL search returns all results in the table no matter what is searched

The code below pairs with the HTML to search the db for the results. It is supposed to search based on what is entered into the search field. I had posted a question and got a lot of great responses about SQL injection, so I have updated my code.

CODE OPTION 1 I TRIED If I just press the search button with the field empty, it returns every result in the table. If I put something into the field, it still returns every result in the table. It doesn't matter what is put in the field, all this code seems to do is return every result in the table. Where have I gone wrong where the search doesnt work?

function my_function_name() {
global $wpdb;

$search = trim($_POST['search']);
$query = $wpdb->prepare("SELECT * FROM mytable name WHERE columnname LIKE '%%%s%%'", $search);
$results = $wpdb->get_results($query);

if($results)

{echo json_encode($results); /* echo 'added'; */}

else{ echo 'no results found'; } die; }

CODE OPTION 2 I TRIED If I just press the search button with the field empty, it returns echos 'no results found' which is my else{ code. If I put something into the field, it still says the same thing. Doesnt matter what I put in there

function my_function_name() {           

global $wpdb;
$search = $_POST['search'];
$wpdb->prepare( "SELECT * FROM {$wpdb->prefix} mytable WHERE id = %d AND columnname = %s", $id, $secret);


if($results)

{echo json_encode($results); /* echo 'added'; */}

else{ echo 'no results found'; } die; }

The HTML

<form action="<?php echo admin\_url('/admin-ajax.php'); ?>" method="post" id="ajax\_my\_function\_id" autocomplete="off">

Search <input type="text" name="search"><br>
<input type ="submit">

</form>

May be it cannot identifies the format specifier properly as it is within multiple % sign. Use concatenation operator.

$query = $wpdb->prepare("SELECT * FROM mytable name WHERE columnname LIKE '%%' . $search . '%%'");

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