First of all, I know it's not how it's supposed to be. But the system has been setup like this so I have to try and work with it.
I have a column of entries in a mySQL table that look like this {12}-{32} and so forth. 12 is the id of the brand of a car, 32 the model.
Now I have to create a query in PHP where a part of it is like this:
(PD1.fieldValue = '{". $_SESSION['carId'] ."}-{". $_SESSION['carModelId'] ."}'
Guess what, that doesnt work with curly braces ofcourse. The SESSION part is completely empty (yes, they have a value outside the query).
Is there anyway to fix this so I still can send the variables inside the braces to mySQL?
Whenever you find yourself having trouble getting some characters into your database, that is a strong hint that your database code is insecure and vulnerable to SQL injection. You have to take a step back and look a little more broadly, thinking "What are all of the possible characters that aren't being escaped properly?" Luckily, you don't have to actually know. You just need to use the built-in escape functions.
The ideal solution is to use placeholders. The syntax depends on what database API you're using (mysqli, or PDO; deprecated mysql doesn't support them). There exist many excellent resources on how to use placeholders; this is the first result I pulled from Google and it looks right to me.
The somewhat less ideal solution is to use the real_escape_string
function for your database API. Example for either mysqli
or mysql
:
// Using heredoc syntax, you can clean up your queries like so.
$sql_template = <<<SQL
SELECT
PC.id AS cId,
P.id AS pId
FROM PAGE_CATALOG P
LEFT JOIN PAGE_CATALOG_CONFIG PC ON (PC.id = P.cId)
WHERE PD1.fieldValue = '%s'
AND P.productCode REGEXP '%s'
AND PC.id = '1'
AND P.enabled = '1'
GROUP BY P.id
ORDER BY P.productVolgorde ASC
LIMIT 0, 10
SQL;
// For mysqli:
// $mysqli = new mysqli(...)
$sql = sprintf(
$sql_template,
$mysqli->real_escape_string('{' . $_SESSION['carId'] . '}-{' . $_SESSION['carModelId'] . '}'),
$mysqli->real_escape_string($MAL_TYPE)
);
$result = $mysqli->query($sql);
// For mysql:
$sql = sprintf(
$sql_template,
mysql_real_escape_string('{' . $_SESSION['carId'] . '}-{' . $_SESSION['carModelId'] . '}'),
mysql_real_escape_string($MAL_TYPE)
);
$result = mysql_query($sql);