duancunsu9209
2018-08-07 08:12
浏览 94
已采纳

PHP从数据库中获取数据并将数据放入字符串中

I am still new to PHP. I have tried a few stuff, but I just can't get it to work.

Question: I want all the data from my users table to be in a string, separated by comma. Then when the ID is 2 to be ; for net new row, so on and so forth. If someone can please help me.

$server = "localhost";
$user_name = "root";
$password = "";
$database = "users";

$conn = new mysqli($server, $user_name, $password, $database);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM Users;";
$result = $conn ->query($sql);

while($row = mysqli_fetch_array( $result )) {
    $rows = implode (";",$result);
    $array = $rows;

    echo $array;
}

Question2: But if I want first row of DB data to be, separated and then at the end with a ;. How would I do that?

Output: The output of this code is: Warning: implode(): Invalid arguments passed

图片转代码服务由CSDN问答提供 功能建议

我还是PHP新手。 我尝试了一些东西,但我无法让它工作。

问题:我想要来自用户的所有数据< / code> table以字符串形式,以逗号分隔。 然后,当 ID 2 ; 为新的新行,依此类推。 如果有人可以帮助我。

  $ server =“localhost”; 
 $ user_name =“root”; 
 $ password =“”; 
 $ database =“users”; 
 \  n $ conn = new mysqli($ server,$ user_name,$ password,$ database); 
if($ conn-&gt; connect_error){
 die(“Connection failed:”。$ conn-&gt; connect_error); \  n} 
 
 $ sql =“SELECT * FROM Users;”; 
 $ result = $ conn  - &gt; query($ sql); 
 
while($ row = mysqli_fetch_array($ result)){
  $ rows = implode(“;”,$ result); 
 $ array = $ rows; 
 
 echo $ array; 
} 
   
 
 

< strong>问题2:但是,如果我想要第一行DB数据,分开,然后在最后用; 。 我该怎么做?

输出:此代码的输出为: 警告:implode():传递的参数无效

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dpuwov1487 2018-08-07 08:53
    最佳回答

    Let's say your user table has 2 fields Firstname and Lastname. What I understood from your question is you want your output to be something like

    $array = ['steve,jobs;', 'mark,zukerberg;'];
    

    To achieve this you can append ';' at the end of the string.

    while($row = mysqli_fetch_array( $result )) {
         $rows = implode(',',$row) . ';'; //you have named this variable $rows but it is going to have data of a single row
         $array = $rows; //you could directly var_dump($rows) instead of assigning it to a new variable
         echo $array; //you could rather use var_dump($array) for this
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题