如何使用字段中的值作为$ table?

时间:2011-11-16 16:25:19

标签: php hidden

我将表格中的表格作为隐藏字段,我必须以某种方式这样做,但是当我执行以下操作时它不起作用:

 // This is being processed from the previous page in a form
 $table = mysql_real_escape_string($_POST['just_field']);

//Here i am using the $table value to use in place of a table name
$sql = "select `Field` from `$table` where `another_field` = '$id' 
and `another_another_field` = '$something'";
$query = mysql_query($sql) or die ("Error: ".mysql_error());

while ($row = mysql_fetch_array($query)){

    $somefield = $row['field'];
  }
 mysql_free_result($query);

如何让它工作,以便命令读取$table ...

5 个答案:

答案 0 :(得分:2)

表格分配不需要引号。

$table = mysql_real_escape_string($_POST['just_field']);

答案 1 :(得分:1)

您的问题是区分大小写的。

在您的查询中:

select `Field` from `$table`....
        ^ Capital F

后来的

$somefield = $row['field'];
                   ^ lower case f

一个例子

php > $cxn = mysql_connect( 'localhost', '****', '****' );
php > mysql_select_db( 'test' );
php > $res = mysql_query( 'select * from genres' );
php > $row = mysql_fetch_assoc( $res );
php > print_r( $row );
Array
(
    [id] => 1
    [name] => Pop //notice the field name is lower case
)
php > echo $row['name']; //this works
Pop // <- see
php > echo $row['Name']; //this doesn't
php > // <- look, nothing

答案 2 :(得分:1)

这对你有用吗<​​/ p>

$sql = "select `Field` from ".$table." where `another_field` = '$id' 
and `another_another_field` = '$something'";

答案 3 :(得分:1)

尝试打印$table的内容,然后通过mysql_real_escape_string()发送,以确保其中包含您认为的值。

答案 4 :(得分:1)

尝试包含连接字符串

$sql = "select `Field` from `$table` where `another_field` = '$id' 
and `another_another_field` = '$something'";
$query = mysql_query($sql,$conn) or die ("Error: ".mysql_error());

 while ($row = mysql_fetch_array($query)){

    $somefield = $row['field'];
  }
 mysql_free_result($query);

如果您没有使用任何框架