1

So I have a table with 6 columns, each column corresponds to a certain product type. Each column holds a number that corresponds to the number of times people have chosen that product type.

A | B | C | D | E | F
---------------------
0 | 0 | 0 | 0 | 0 | 0

So if the user picks type A, then I want to update column A's number from 0 to 1. So here's the SQL code I wrote:

$link = new PDO('***;dbname=***;charset=UTF-8','***','***');
$stmt = $link->prepare("UPDATE table SET :column=:num");
$stmt->bindParam(':column', $column);
$stmt->bindParam(':num', $num);
$stmt->execute();

But it's not updating anything at all. So i'm guessing there is something wrong with the SQL code, most likely having to do with the column placeholder :column. Can anyone tell me the right SQL code?

1 Answer 1

4

First make sure, $column is in an accepted list of values. Next, you can't bind :column you will have assign it like so:

$stmt = $link->prepare('UPDATE table SET ' . $column .' = :num'); 
$stmt->bindParam(':num', $num);
$stmt->execute();

If you were going to check for a valid $column I would use

$valid_column = preg_match('/[a-z0-9_]/i, $column);

or a sufficient replace (preg_replace). Though you would likely wrap it in a try/catch and set exceptions to be thrown in your PDO instance to make sure it's even legit.

Sign up to request clarification or add additional context in comments.

3 Comments

To teach good practices, the injection of $column into the SQL would deserve some escaping.
I would never suggest a type of assignment or mass assignment in this fashion. So yes, +1. I'm bender from the future ;)
Um, no, don't escape it. I'd do a check of 'is the string given exactly one in this set'. Anything else raises the possibility of problems. Your given check won't restrict the column selected to the 'proper' list, and is only valid for the english/latin alphabet; if you check some of the other questions on this site, you'll see database table/columns with names with non-latin characters. It also won't allow 'escaped' names (which may have been reserved words, not usually valid column names).

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.