CodeX
CodeX

Reputation: 57

Search DB through MYSQLi

I have one simple question which I can't understand why it doesn't work. I'm trying to querying the DB through MySQLi and if I hard code a variable works perfect, if I try to make dynamic (via an input box) displays nothing.

Here is the code:

if(isset($_GET['search'])) {
    $searchByInput = $_GET['search'];
}

$query = 'SELECT * FROM table WHERE vin="$searchByInput"';

if ($stmt = $mysqli->prepare($query)) {
    $stmt->execute();

    $result = $stmt->get_result();

    if($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            //display the table
        }
    }
}

If I'm 'echo'ing the variable inside the if statement, displays the right value but for some reason doesn't want to execute the query correctly with this variable.

I hope someone can point me in the right direction.

Thank you

Upvotes: 1

Views: 41

Answers (2)

JM Mayo
JM Mayo

Reputation: 319

Change the variable to:

$query = "SELECT * FROM table WHERE vin='$searchByInput'";

I think it's a problem with string quotes format. Simple quote format doesn't expand variables.

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116110

You should use single quoted strings inside the query to make it valid, and you should (conveniently) use double quote to expand variables inside the string in the first place:

$query = "SELECT * FROM table WHERE vin='$searchByInput'";

Even better, let MySQL handle this itself by binding a parameter. This also solves the SQL injection vulnerabilities that were mentioned in the comments:

$searchByInput = '';
if(isset($_GET['search'])) {
    $searchByInput = $_GET['search'];
}

$query = 'SELECT * FROM table WHERE vin=?';

if ($stmt = $mysqli->prepare($query)) {
    $stmt->bind_param('s', $searchByInput);

    $stmt->execute();

    $result = $stmt->get_result();

    if($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            //display the table
        }
    }
}

Upvotes: 5

Related Questions