<?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?
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
}
Where you used implode()
`<?php
$id = $row["id"];
$first_name = $row["First_Name"];
$arr=array ($id,$first_name);
echo implode(" ",$arr);
?>`
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
Here is perfect solution for your problem.. It will work. i am using mysql extension rather than mysqli..