0

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

0

2 Answers 2

2

You've simply used the wrong variable in your call to ìmplode.

You've assigned all the columns as an array to $row - but you're trying to implode $result.

Update that line to this:

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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 Comment

Yes this is what i wanted. sorry if i structured my question wrong. Still new to the php stuff

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.