Oskari Ahola
Oskari Ahola

Reputation: 41

How can I list result from sql to html table

So I have simple table in database: "users"

------------------------------------------------------
|     id    |   fname   |  sname  |  uname  |   pw   | 
------------------------------------------------------
|     1     |   John    |   Doe   |  jdoe   |  123   | 
------------------------------------------------------
|     2     |   John1   |   Doe1  |  jdoe1  |  234   | 
------------------------------------------------------
|     3     |   John2   |   Doe2  |  jdoe2  |  345   | 
------------------------------------------------------

etc. I want to make html table where i can edit these values in database. How can print out all users user first and last names from that table?

$sql= mysqli_query("SELECT * FROM users"); 
$result= mysqli_fetch_array($sql);
$count=count($result);
for ($x=1;$x<$count;$x++)
{
  echo $result['fname']." ".$result['sname'];
}

I have this kind of code to make the user list but that doesn't work.

Upvotes: 4

Views: 187

Answers (3)

Dave Sexton
Dave Sexton

Reputation: 11188

Not the ideal way but you could always change your SQL statement to this:

SELECT '<table>' AS x
UNION ALL
SELECT 
  '<tr><td>id</td><td>fname</td><td>' + 
  'sname</td><td>uname</td><td>pw</td></tr>'
UNION ALL
SELECT
  '<tr><td>' + id + '</td><td>' + 
  fname + '</td><td>' + 
  sname + '</td><td>' + 
  uname + '</td><td>' + 
  pw + '</td></tr>'
FROM USERS
UNION ALL
SELECT '</table>'

Upvotes: 0

Wallack
Wallack

Reputation: 792

Try this code:

echo "<table><tr><td>id</td><td>fname</td><td>sname</td><td>uname</td><td>pw</td></tr>";
$sql = mysqli_query("SELECT * FROM users"); 
while($result = mysqli_fetch_array($sql))
{
    echo "<table><tr><td>".$result['id']."</td><td>".$result['fname']."</td><td>".$result['sname']."</td><td>".$result['uname']."</td><td>".$result['pw']."</td></tr>";
}
echo "</table>";

Anyways this is a rough example. Try never yo print HTML with a echo or print, instead of that close the PHP tag, print the HTML and open it again to avoid unnecessary server work.

Also try to use PDO to connect to the database: PHP PDO Manual

Upvotes: 0

Fabio
Fabio

Reputation: 23480

Try to loop while fetching data from database with while

$sql= mysqli_query("SELECT * FROM users"); 
while($result= mysqli_fetch_array($sql))
{
    echo $result['fname']." ".$result['sname'] . '<br>';
}

Upvotes: 3

Related Questions