【问题标题】:PHP get data from database and put the data into a stringPHP从数据库中获取数据并将数据放入字符串
【发布时间】:2018-08-07 08:12:57
【问题描述】:

我还是 PHP 新手。我已经尝试了一些东西,但我就是无法让它发挥作用。

问题:我希望users 表中的所有数据都放在一个字符串中,用逗号分隔。然后当ID2; 用于净新行,依此类推。如果有人可以请帮助我。

$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;
}

问题2:但是,如果我希望将第一行数据库数据分开,然后在末尾加上;。我该怎么做?

输出:这段代码的输出是: Warning: implode(): Invalid arguments passed

【问题讨论】:

    标签: php sql


    【解决方案1】:

    您只是在调用 ìmplode 时使用了错误的变量。

    您已将所有列作为数组分配给 $row - 但您正试图内爆 $result

    将该行更新为:

    $rows = implode(";", $row);

    【讨论】:

    • 但是如果我想将DB 数据的第一行以, 分隔,然后在最后以; 分隔,我该怎么做?
    【解决方案2】:

    假设您的用户表有 2 个字段 Firstname 和 Lastname。我从您的问题中了解到,您希望您的输出类似于

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

    为此,您可以在字符串末尾附加 ';'

    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
    }
    

    【讨论】:

    • 是的,这就是我想要的。抱歉,如果我的问题结构错误。对 php 的东西还是陌生的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2018-08-16
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    相关资源
    最近更新 更多