1

Can a PHP variable be used as a table name in an SQL query? In my case the PHP variable that goes after FROM should be the value being sent from my JQuery code. I want the SQL query to change based on the value sent from JQuery (different value depending on which option of the select box is chosen).

$file_absolute = ---Placeholder for correct file path---;
include_once($file_absolute);
$mysql = new mysqli($db_host, $db_username, $db_password, $db_name);
$verb_value = $_POST['verb_value'];

$mysql->query("SET CHARACTER SET 'utf8'");

$result = $mysql->query("SELECT present_tense FROM $verb_value");
1
  • STOP. Don't do this. You're vulnerable to SQL injection attacks, and are just begging to get your server pwn3d. Commented Sep 19, 2012 at 15:14

2 Answers 2

4

You can do this, yes. Whether you want it is quite another matter - if you're adding user input to your SQL queries, you've got a huge SQL injection hole.

That said, with table names, you can implement a whitelist, and compare the passed values against that to get a measure of security.

You can't pass table names (or column names) as bound parameters, though - they need to be generated as part of the query.

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

8 Comments

Glad you answered this Andrew. I was about to go research binding methods.
The user is never typing in anything. The value being sent is a value I send based on what option is selected by the user in a select box.
You're taking in data from $_POST['verb_value'] - what is there to stop a user from editing the value that's being submitted?
@andrewsi I'm not sure how the user would edit the value. I'm using the following JQuery code: $('#verb').live('change', function() { $.post("loadTextBox.php", {verb_value: $(this).val()}, function(data) { $("#textbox").html(data.first); $("#textbox2").html(data.second); $("#textbox3").html(data.third); $("#textbox4").html(data.fourth); $("#textbox5").html(data.fifth); $("#textbox6").html(data.sitxh); },"json"); });
With tools like firebug, you can see what values are about to be submitted on a page, and edit them before submitting. Also, could I create a form locally that has your PHP page as it's action? Then I can enter whatever I want to.
|
0

A double-quoted string will parse any variables within it, so this will work. A single-quoted string would not.

However, this is generally not considered secure. I'm not sure if you can use a bindParam method to achieve this (I use PDO, not mysqli) as it's not actually a parameter.

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.