-2
    <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "comp4";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id , First_Name, Last_Name FROM member WHERE username='tracy'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["First_Name"]. " " . $row["Last_Name"]. "<br>";
}
} else {
echo "0 results";
}



$conn->close();
?>

I have this code in order to display some details about a member in my database but I want to make it into a string and a variable, I tried to use the php implode function but I recieved an error saying that some of the other variables were unexpected any tips or anything wrong that im doing?

4 Answers4

4

Where you used implode()

`<?php
      $id = $row["id"];
      $first_name = $row["First_Name"];
      $arr=array ($id,$first_name);
      echo implode(" ",$arr);
    ?>`
KuMaR
  • 203
  • 1
  • 2
  • 10
0

In your while loop, you should first concatenate all your column in one array, to be then collapsed in one single string as following :

while($row = $result->fetch_assoc()) 
    {
        // temp variables
        $id = $row["id"];
        $first_name = $row["First_Name"];
        $last_name = $row["Last_Name"];

        $array = array($id, $first_name, $last_name); // creating an array

        $result = implode(" - ", $array); // Collapsing data using dash

        printf($result); // displaying data collapsed
    }

from official php implode doc

Anwar
  • 4,162
  • 4
  • 41
  • 62
  • Thank you for your reply, I tried to put that into the code and get an unexpected end of file error which im trying to resolve now – Bhavesh Jan 20 '15 at 13:43
0

I you want the result in a string, replace the echo by this: $results .= "id: " . $row["id"]. " - Name: " . $row["First_Name"]. " " . $row["Last_Name"]. "<br>";

Now everithing is in $results

Eddy
  • 1
-1

Here is perfect solution for your problem.. It will work. i am using mysql extension rather than mysqli..

enter image description here

Nirmal Kumar
  • 125
  • 8