I want to search a query in a MySQL table called "keys" based on a key, and then return other values for that query. (e.g. "id")
This is how my table looks like:
id key customer
88633631 gNjp4CW6E/VfdBqli6zBLw== Name1
41317488 bi74frT3LFGTRkvoW7B31Q== Name2
..and this is how my PHP code looks like:
<?php
require 'config.inc.php';
/* Declare variables */
$key = $_GET["key"];
$id = "";
$customer = "";
/* Connect to database and grab the keys */
@mysql_connect($g_mysql_host,$g_mysql_usr,$g_mysql_pass)
or die("Couldn't connect to database server");
@mysql_selectdb($g_mysql_db)
or die("Couldn't select database");
$query = "SELECT * FROM `keys` WHERE `key` = $key";
$result = mysql_query($query);
if (!$result) exit("INVALID KEY");
else {
while ($row = mysql_fetch_array($result)) {
echo $row['id'];
}
}
?>
But this does not work. I think that the problem is caused by the 2 equals at the end of the key, but I'm not sure. If I want to search the "id" and then print the "key" of the searched "id", it works.
I don't want to remove the 2 equals at the end, because they are related to AES128 padding.
Actually, the problem is not caused by the 2 equals at the end of the key. It is caused by the "+" character inside the string, but if I remove it I can't decrypt the AES128 encrypted text.
There are several things wrong with the way you do this.
First, you don't quote your value: '$key'
$query = "SELECT * FROM `keys` WHERE `key` = '$key'";
Second, your code is wide open to SQL injection. Escape your value:
$key = mysql_real_escape_string($_GET["key"]);
The code above is the absolute minimum you need to do.
The next thing is that the mysql_ functions have been deprecated a long time and have been removed in PHP 7.
You'll need to switch to either mysqli_ or PDO. The sooner you switch, the better.
Please read this question for further information: How can I prevent SQL injection in PHP?
Apart from all the problems above, you'll save yourself (and even more so others, if they ever have to read your code) some headache if you don't ever use keywords and reserved words as table or column names, as Jay Blanchard has noted.
That is happening because you didn't escaped the input it should be
"SELECT * FROM `keys` WHERE `key` = '$key'"
but anyway this is not the best way to do that, you have to use prepared statement and wrapper such as PDO
Something like this
$stmt = $db->prepare('SELECT * FROM `keys` WHERE `key` = :key');
$stmt->bindValue(":key", $_GET["key"]);
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['id'];
}
}
what about if you change the following line
$query = "SELECT * FROM `keys` WHERE `key` = $key";
to
$query = "SELECT * FROM `keys` WHERE `key` = '".$key."' ";