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

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

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据
  • ¥15 为什么openeluer里面按不了python3呢?