php - Can I use a variable as table name in a MySQL query? -


i want mysql query variable table. here i'm looking for:

mysql_query("select * $var $anothervar ='1'")) 

how can this?

first of all, stop using mysql_ functions. have been deprecated. check out mysqli or pdo.

when using php query database can build entire query please. can type out full query or add variables more dynamic queries. did correct (except double parenthese on right).

<?php $query = "select * users id ='1'";  //the above same  $var = 'users'; $anothervar = 'id'; $query = "select * $var $anothervar ='1'";  //execute query. ?> 

so yes, can use variable table name when constucting query in php. need keep in mind variables use can lead sql injection. if getting values table , column names user input, make sure validate them properly!

simply using mysql_real_escape_string() or mysqli_real_escape_string() not work on table , column names, because not enclosed in quotes. vote go whitelist if receive user input columns/tables , concatenating queries. eg:

<?php $allowed_tables = array("users", "articles", "messages");  if (!in_array($var, $allowed_tables)) {   echo 'invalid table';   exit(); } ?> 

another read how-to-prevent-sql-injection-in-php goes parameterized queries, want do, in more secure manner concatenating strings.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -