r/PHPhelp • u/GuybrushThreepywood • Jan 15 '25
How can I avoid 'x values expected' warning when using a $variable as col name
Screenshot of error: https://ibb.co/n1dzm2B
Am I doing this wrong? I keep getting a warning from PHPStorm '1 value expected, got 2' because I am using a variable for one of the column names
$query = <<<MySQL
INSERT INTO
users_preferences
(
client_id,
$col->name
)
VALUES
(
?,? <<---- WARNING HERE
)
ON DUPLICATE KEY UPDATE
$col->name = VALUES($col->name);
MySQL;
$conn->execute_query(
$query,
[
$clientId,
$newValue,
]
);
0
Upvotes
3
u/MateusAzevedo Jan 15 '25
It looks like your IDE isn't parsing that correctly and giving you a false positive, but the code should work fine.
Just remember: be careful when adding variables to things that can't be substituted by a placeholder. It must be filtered through a whitelist of valid options.
2
u/davvblack Jan 15 '25
something i want to flag here, it's EXTREMELY easy to accidentaly make injectible code if you're doing this kind of substitution because you require that sql interpret identifiers as not-string-literals, so normal escaping doesn't work.
Be absolutley certain that $col->name can only come from static, hardcoded data, or use the native ways to escape identifiers. In some of these examples, you can generate dangerous sql if the user can control the value of $col->name (for example an api that sends the name of the setting and the new value)
1
u/GuybrushThreepywood Jan 15 '25
I wrapped with `, like:
It seems to work. Are there any other ways?
1
u/flyingron Jan 15 '25
When you want to use a non trivial variable substitution (i.e., anything other than $foo or the like), you need to wrap the substitution in { }
1
u/colshrapnel Jan 15 '25
I don't know how to disable this warning in your IDE, but your users_preferences should really store its data in rows, not columns.
So this code would be
getting client settings will be slightly more complex than now but NOT that complex
But your overall code will become whole world better, more manageable, without potential SQL injections and without the need to alter your database to add a new setting.