Mysql选择结果作为文本变量

我有这两个变量获取 SQL 长文本列 ( $results_text) 和另一个 ( $results_f2) 从用户获取信息:


那是我的新代码:



    <?php

    $results = mysqli_query($conn, "SELECT rc.text2, rl.* FROM table_config AS rc JOIN table_list AS rl ON rc.user = rl.user WHERE rl.email = 'user@gmail.com'");

    while($row1 = mysqli_fetch_array($results))

    {

      $text2 = $row1[0];

      $name = $row1[3];

      $role = $row1[4];

      $company = $row1[6];


      echo $text2 .= str_replace(":name:", $name, $text2);

      echo $text2 .= str_replace(":role:", $role, $text2);

      echo $text2 .= str_replace(":company:", $company, $text2);

    }

        mysqli_close($conn);

    ?>

它正在工作,但给了我很多废话,比如一个带有名称的 text2,另一个带有角色,另一个带有公司,然后最后一个替换了所有变量/字符串。


江户川乱折腾
浏览 89回答 1
1回答

哆啦的时光机

内循环仅在外循环的第一次迭代期间工作。一旦你完成了从查询中获取结果,下次它就不会回到开头。由于第二个查询只返回一行,因此您应该在循环之外只获取一次。或者您可以在一个查询中简单地连接两个表。$results = mysqli_query($conn, "&nbsp; &nbsp; SELECT tc.text1, tl.*&nbsp; &nbsp; FROM table_config AS tc&nbsp; &nbsp; CROSS JOIN (&nbsp; &nbsp; &nbsp; &nbsp; SELECT *&nbsp; &nbsp; &nbsp; &nbsp; FROM table_list AS tl&nbsp; &nbsp; &nbsp; &nbsp; WHERE tl.user = 'user'&nbsp; &nbsp; &nbsp; &nbsp; LIMIT 1) AS tl&nbsp; &nbsp; WHERE tc.user = 'user'");您将获得 3 个输出,因为您正在回显每个替换。您应该进行所有替换,然后回显。&nbsp; &nbsp; &nbsp; $text2 .= str_replace(":name:", $name, $text2);&nbsp; &nbsp; &nbsp; $text2 .= str_replace(":role:", $role, $text2);&nbsp; &nbsp; &nbsp; $text2 .= str_replace(":company:", $company, $text2);&nbsp; &nbsp; &nbsp; echo $text2;您还可以通过将模板和替换放入数组来一次完成所有替换。$text2 = str_replace([":name:", ":role:", ":company:"], [$name, $role, $company], $text2);echo $text2;
打开App,查看更多内容
随时随地看视频慕课网APP