0
<?php
    function searchDatabase($key, $value)
    {
        $key = $key;
        $query = "SELECT * FROM user_data WHERE username='$value'";
        $result = mysqli_query(loadDatabase(), $query);
        $numRows = mysqli_num_rows($result);
        if ($numRows > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
?>

So I am using this code to search through my database to reveal a match on a key/value pair, but $key doesn't find the correct column in my database when passed into the query function. If I replace it with the word username, it matches fine. Is it a type issue? I am not explicitly stating its type so I can search other columns with the same function.

username: varchar(40)

3
  • Uh? $key = $key; must be a mistake? replace username by $key. Commented Feb 27, 2015 at 8:58
  • $query = "SELECT * FROM user_data WHERE username='$value'"; should be $query = "SELECT * FROM user_data WHERE username='".$value."'"; Commented Feb 27, 2015 at 9:00
  • Your code is vulnerable. Don't use mysqli without real-escape-string, because your site will attackable by SQL injection. Commented Feb 27, 2015 at 9:01

4 Answers 4

2
<?php
function searchDatabase($key, $value)
    {
        $query = "SELECT * FROM user_data WHERE ".$key." = '".$value."'";
        $result = mysqli_query(loadDatabase(), $query);
        $numRows = mysqli_num_rows($result);
        return ($numRows > 0);
    }
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! This worked for me! So what exactly happened? Was it a type issue?
You used username instead $key.
0

Try this

$query = "SELECT * FROM user_data WHERE ".$key."='$value'";

Comments

0

Like so:

function searchDatabase($key, $value)
{
  $query = "SELECT * FROM user_data WHERE $key='$value'";
  $result = mysqli_query(loadDatabase(), $query);
  $numRows = mysqli_num_rows($result);
  return ($numRows > 0);
}

Comments

0

The problem is in the query. PHP variables are not properly echoed in the query.

<?php
function searchDatabase($key, $value)
    {
        $query = "SELECT * FROM user_data WHERE username='".$value."'";
        $result = mysqli_query(loadDatabase(), $query);
        $numRows = mysqli_num_rows($result);
        return ($numRows > 0);
    }
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.