简体   繁体   English

从MySQL获取逗号分隔的链接列表-PHP

[英]Fetch comma seperated link list from MySQL - PHP

id      name
1       Abc
2       Bcd
3       Def
4       Efg
5       Xyz

Now i am using mysqli prepared statements to fetch my data 现在我正在使用mysqli准备好的语句来获取我的数据

<?php
  if ($stmt1 = $mysqli->prepare("SELECT name FROM TABLE")) {
      $stmt1->execute();
      $res1 = $stmt1->get_result();             
      while($rwv=mysqli_fetch_array($res1)) {
?>

   <a href="page.php?name=<?php echo $rwv['name']; ?>"><?php echo $rwv['name']; ?></a>

<?php } } $stmt1->close(); ?>

Output i get on using above query: 我使用上面的查询输出:

AbcBcddefEfgXyz

Desired Ouput: 所需的Ouput:

Abc, Bcd, Def, Efg, Xyz

I searched on Google and found solutions to use GROUP_CONCAT func. 我在Google上进行了搜索,找到了使用GROUP_CONCAT函数的解决方案。 I used GROUP_CONCAT function but then it shows an error on a href that variable "name" is undefined. 我使用了GROUP_CONCAT函数,但是随后在href上显示错误,表明未定义变量“名称”。 How i can get the desired output ?? 我如何获得所需的输出? Thanks in advance... 提前致谢...

Please check below example, You can use GROUP_CONCAT in mysql. 请检查以下示例,您可以在mysql中使用GROUP_CONCAT。

"SELECT GROUP_CONCAT(CONCAT('<','a href=\"pagename.php?name=', title, '\"\>', title, '<', '/a>')) as name FROM YOUR_TABLE"

The above example fetch the records with comma separated value from mysql with column name name , So you will not get the error as you mentioned above. 上面的示例从列名称为name mysql处获取逗号分隔值的记录,因此不会像上面提到的那样出现错误。 May be it will help you. 可能会对您有帮助。

The other answer is just terrible. 另一个答案是可怕的。

We are trying desperately to make PHP users to refrain from intermixing PHP with HTML, but that answer is lowering a problem a level deeper, intermixing HTML with SQL. 我们正拼命地尝试使PHP用户避免将PHP与HTML混合,但是这个答案将HTML和SQL混合在一起的程度降低了。

While using separation from HTML you can make your code real neat 使用与HTML分离时,您可以使代码真正整洁

<?php
    $data = $mysqli->query("SELECT name FROM users")->fetch_all(MYSQLI_ASSOC);
    $last = count($data) - 1;
?>
<? foreach ($data as $i => $row) { ?>
    <a href="page.php?name=<?= $row['name'] ?>"><?= $row['name'] ?></a><!--
    --><?php if ($i != $last) { ?>,<?php } ?>
<?php }  ?>

Another way to go that you can use with your existing code is: (added 3 lines to the code, all with comment //Added this 可以与现有代码一起使用的另一种方法是:(在代码中添加了3行,全部带有注释//添加了此代码

<?php
  if ($stmt1 = $mysqli->prepare("SELECT name FROM TABLE")) {
      $stmt1->execute();
      $res1 = $stmt1->get_result();
      $hasGonePastFirst = false;  //Added this             
      while($rwv=mysqli_fetch_array($res1)) {

       if($hasGonePastFirst) echo ' , ';   //Added this
       else $hasGonePastFirst = true;      //Added this
?>

   <a href="page.php?name=<?php echo $rwv['name']; ?>"><?php echo $rwv['name']; ?></a>

<?php
 } } $stmt1->close(); ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM