如何使用变量PHP在SELECT中的for循环中创建字符串

时间:2018-07-27 19:09:28

标签: php mysql string variables for-loop

我在哪里出错,无法像我在下面写的那样获得输出?

  1. 内部数组是表的名称。

假设这些表中有0行,所以每个地方的输出都应该为0。

<?php
$g_module =
array(
  'm_b_broadcast_live',
  'm_b_browsing_live',
  'm_e_askfm_likes_live',
  'm_e_facebook_followers_live',
  'm_e_facebook_group_joins_live',
);

for ($i = 0; $i <= 5; $i++) {
  $modules_names = "g_module[$i]";
  $modules_from = '$'.$modules_names;

  $modules_rows = '$g_module_row_'.$i;

  $$modules_rows = mysql_num_rows("SELECT * FROM $$modules_from");
}

echo $g_module_row_1;
echo '</br>';
echo $g_module_row_2;
echo '</br>';
echo $g_module_row_3;
echo '</br>';
echo $g_module_row_4;
echo '</br>';
echo $g_module_row_5;

/* output should be:
0

0

0

0

0
*/
?>

2 个答案:

答案 0 :(得分:0)

<?php
    $g_module =
    array(
        'm_b_broadcast_live',
        'm_b_browsing_live',
        'm_e_askfm_likes_live',
        'm_e_facebook_followers_live',
        'm_e_facebook_group_joins_live',
    );

    foreach($g_module as $table_name){
        $count = mysql_num_rows("SELECT * FROM $table_name");
        echo "<br/>".$count;
    }
?>

我认为您应该尝试这样。

答案 1 :(得分:0)

正如您对问题的评论中所述,mysql_num_rows()将查询结果作为参数,而不是查询字符串。
此外,您应该使用mysqli!查看文档here

您可以简化的另一件事是转义美元符号,这样您就不必再次将其与$modules_names串联。

更正后的代码如下:

<?php
$g_module = [
    'm_b_broadcast_live',
    'm_b_browsing_live',
    'm_e_askfm_likes_live',
    'm_e_facebook_followers_live',
    'm_e_facebook_group_joins_live',
];

// you have to create a connection to your database server first
// of course you will have to swap out my placeholders for the actual credentials
$con=mysqli_connect('mysql_server_address_here','username_here','password_here','database_name_here');

for($i=0;$i<=5;$i++){
    $modules_from = "\$g_module[$i]";

    $modules_rows = "\$g_module_row_$i";

    $q=mysqli_query("SELECT * FROM $$modules_from");

    //use mysqli_num_rows instead
    $$modules_rows = mysqli_num_rows($q);
}

// close your connection after you are finished
mysqli_close($con);

echo $g_module_row_1;
echo '</br>';
echo $g_module_row_2;
echo '</br>';
echo $g_module_row_3;
echo '</br>';
echo $g_module_row_4;
echo '</br>';
echo $g_module_row_5;