-1

I'm trying to insert form values into the tables and column spots in SQL queries, in hopes of PHP passing it's value to MySQL.

like this:

$sql= "SELECT * FROM  '{$table}' WHERE '{$catagory}' = '{$value}'";

So is there a way I can do something like this without getting a syntax error?

Marc Delisle
  • 8,879
  • 3
  • 29
  • 29
ahmad
  • 3
  • 1
  • 1
    Possible duplicate of [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Tim Dec 05 '15 at 02:02

3 Answers3

0

Did you try like this

$sql= "SELECT * FROM  $table WHERE $catagory = '$value'";

or if you trying to select from form input fields you can try like this

$sql= "SELECT * FROM $_POST[table] WHERE $_POST[category] = '$_POST[value]'";

just please be aware that this second example is not secure way to inserting input fields values into query since someone can SQL inject your query, so you know.

Standej
  • 749
  • 1
  • 4
  • 11
0

Yes, just like this...

$sql= "SELECT * FROM $table WHERE $category ='$value'";

Just make sure the whole string is within double quotes " "

I do this all the time, but I use prepared statements...you should as well

VIDesignz
  • 4,703
  • 3
  • 25
  • 37
0

First of all, let me make my disclaimer that you should never use raw input data from a form to determine databases, tables, or columns in your queries. It's bad news. Create some sort of mapping that does not expose your database schema to end users and restricts the values to only what you want and cannot be changed by developer tools in the browser or a bot trying to hack your site.

If you want to do it with mysql you will need to do to escape the form data with mysqli_real_escape_string to prevent SQL injection. I use sprintf to make it cleaner but it's not required.

$sql = sprintf(
    "SELECT * FROM `%s` WHERE `%s` ='%s'",
    mysqli_real_escape_string($table),
    mysqli_real_escape_string($column),
    mysqli_real_escape_string($value)
);

Please note the backticks (`) around the table and column names. There are not apostrophes a.k.a. single quotes ('). It's the proper way to encapsulate databases, tables, and columns in MySQL queries. It will help prevent issues with special characters in the names.