PHP/MySQLi User Account List

Introduction: This tutorial will cover creating a list of information retrieved from a database through PHP/MySQLi/HTML. Pre-creation: For this tutorial, we are specifically going to be creating a list of all the registered users. As such; if you are going to follow this tutorial exactly, you will need to ensure you have a database of user accounts. Steps of Creation: Step 1: First we need to connect to the database holding the user accounts...
  1. <?php
  2. $con = mysqli_connect('localhost', 'root', '', 'freelanceTutorials') or die(mysql_error());
  3. ?>
mysqli_connect uses the parameters; server, username, password* Step 2: Now we are going to create a query. Here is the structure:
  1. $query = mysqli_query({Connection}, "{ACTION} {COLUMNS} {ACTION} {TABLE}");
And here is our actual query to select all the rows/user accounts from our "users" table:
  1. $query = mysqli_query($con, "SELECT * FROM `users`");
This will give us all the data (*) from each rows in our users table. We could just get the username column if we wanted, which would look like this:
  1. $query = mysqli_query($con, "SELECT `username` FROM `users`);
Step 3: Now that we have sent the query, we are going to make sure that we have data. To do this we will make sure there are one or more rows returned:
  1. if (mysqli_num_rows($query) > 0) {
  2. }
Step 4 If we do have rows of data returned, we are going to loop through the data, adding the username from each row to a custom string variable named ourLine...
  1. $ourLine = '';
  2. while ($row = mysqli_fetch_array($query)) {
  3. $ourLine .= $row['username'].' ';
  4. }
Step 4 Finally we are going to output the variable of user accounts names through echo:
  1. echo $ourLine;
Please note: For my environment, I have: Table name as 'users'. Database name as 'freelanceTutorials'. The column in my table holding the username is called 'username'.

Add new comment