Show Me the User PHP Help

You need a page that shows a user’s information in a way that makes sense to the user. This means that this page is going to pull information from the users table, but it’s not a form; there’s no need (at least. not yet) to do anything but display information. Most of the work here isn’t code; it’s getting a good user profile page built. You’ll want to start with HTML

Luckily, most web servers are configured to take a request for a file ending in ,php and create HTML output. which is handed to a user’s browser. As a result, you can create HTML, drop it into a file ending in .orr: and when you start adding actual PHP you’re ready to go. Your web server will send the HTML in that file to a requesting web browser, and your user’s (or you) see HTML output

Creating a Mockup of a User Profile Page

Figure 7-7 shows a solid-looking profile page. It shows the basics of each user’s contact information as well as a short bio and a picture of the user.

php and MySQL

php and MySQL

Here’s the HTML for the page in Figure 7-7. Because of (SS, it stays pretty simple

<link href= …./css/phpMM.css ..rel=”stylesheet” type=”text/css” />
<div id=”header”><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id=”example”>User Profile</div>
<div id=”content”>
<div class=”user_profile”>
<h1>Yu Darvish</h1>
<img src= …./images/darvish.jpg ..c1ass=”user_pic” />

Attended Tohoku High School in northern Sendai, a school which also produced major league pitchers Kazuhiro Sasaki and Takashi Saito he had a 1.10 ERA in his high school career, and pitched a no-hitter against Kumamoto Technical High School in the first round of the National High School Baseball Invitational Tournament on March 26, 2004 he was drafted by the Fighters in the first round on November 17, 2004 and signed on December 17.</p> <p>Went 18-6 with a 1.44 ERA (37 ER/232.0 IP) for Hokkaido in his final season in Japan …the 1.44 ERA was the lowest of his career, as he also posted career highs in wins (18), strikeouts (276), innings (232.0), starts (28), and shutouts (6)matched career low with 5 HR allowed (also 2010) …led NPB in strikeouts, innings, opponents average (.190), shutouts (tied), home runs per 9 innings (0.19), opponents aBP (.229), and opponents slugging (.241) …the opponents aBP and slugging figures were career lows …ranked among circuit leaders in ERA (2nd), complet games (2nd), strikeout/walk ratio (3rd, 7.67), and wins (T3rd) … tossed at least 7.0 innings in every outing last season, with his lone_outing of more than 3 runs coming in his first start …his career-low run support average of 3.10 runs per 9 innings ranked 23rd out of NPB’s 33 qualifying pitchers …received one or zero runs of support in 4 of his 6 defeats.</p>
<p class=”contact_info”>Get in touch with Yu:</p>

<li>by emailingthemat<ahref=”[email protected]”>[email protected]
<li> by <a href=”
Darvish/55933782070″>checking them out on Facebook</a></li>
<li> …by <a href=””>following
them on Twitter</a></li>
<div id=”footer”></div>

Even though this example is straightforward, what you need is really even simpler. Imagine (or type) this page without the placeholder text but instead with variables in the place of the dummy text. For example, wherever the user’s first name goes, envision $first_ name,and then $last_ name,$email, and so on. The result is clean

<link href=” ../css/php/oVol.css” rel=~stylesheet” type=”text/css” />
<div id=”header”><h1>PHP & MySOL: The Missing Manual</h1></div>
<div id=”example”>User Profile</div>
<di v Id=” c-ontent” >
<div class=”useryrofile”>
<h1>$first_name $last_name</h1>
<p><img src=”$user_image” class=”user_pic” />
<p class=”contact_info”>Get in touch with $first_name:</p>
<li> …by emailing them at
<a href=”$email”>$email</a></li>
<li> …by
<a href=”$facebook_url”>checking them out on Facebook</a></li>
<li> …by <a href=”$twitter_url”>following them on Twitter</a></li>
<div id=”footer”></div>

Imagine this page with nothing more than a name and some contact links. What a bore for your users, as well as you. With this simple mockup, you’ve figured out several important things:

1. You’re missing some key information in your users table. You’d like to have , a bio, which is just a long chunk of text, and a way to load an image of the user.
2. Once you update your table, you need to update your create_ user.ntmt and create_user.php form and code to let users enter that information, and then save the new information to your database.
3. Finally-and this is great news-with those changes, you can build a pretty nice-looking user profile page.

The question now is, what do first? Well, the database is usually the centerpiece of things, so you have to update your users table.

Changing a Table’s Structure by Using ALTER

There are two pieces of information missing from users: a bio and an image. For now leave the image thing alone. That takes a little bit of work, and you can always drop a placeholder in and come back to that. The bio however is easy.

First, you need to change your table’s structure by adding a new column. That’s not hard at all; the SOL ALTER command lets you do just that:

ADD bio varchar(1000);

This statement is as simple as it looks. You provide SOL with the name of the table to ALTER, and then specify how you want to alter it. In this case you want to add a column, so you use ADD to give it the new column name and a type.

Of course there are implications here:

Is it okay for a user to leave a biography blank, or should the bio column be NOT NULL? It’s probably okay if it’s left blank, so NOT NULL really isn’t required.

How in the world does information get into this column for new users? For that. you need to update your HTML web form as well as the script that does the database work. That’s up next.

Can you alter a table any time you want? Yes! That’s the tieauty of databases. They’re pretty flexible

Using SELECT to Retrieve a User from Your Database

You’ve got your variables, and you’ve got your HTML. Now, you need to get your user. But, you know just what to do because you’ve already used SELECT a few times

FROM users;

In fact. you can run that command now on your database. What you get back are all the rows you have

row set

row set

In this case, there’s just a single user. Once you retrieve this user, you can pullout the values for first_name and last_name, email, and so on and stuff them in $first_ name, $last_name, and the rest of your variables

There’s still one big question lurking about: how do you know user to get? Obviously, in the table output here there’s only one user. But. what about when your new app is a hit and you have hundreds or thousands, or even hundreds of thousands of users? You need to be able to select just one of those users for _ user.ono to display

Think about the ways that users will end up at Here are a few:

These situations all have one thing in common: Nobody ever goes to directly by typing in a URL. In each case someone selects a user or creates a user or logs in as a user and then some link takes her

The point is that in every reasonable situation your code sends the user to snow .user ore: therefore, so your code is really in control. If for example you need to send some information to Show. user that’s possible. What might your code want to send to  You want to send the unique 10 of the user that show_tser should load from the database and display.

Take a moment to revisit those same scenarios again:

The beauty of this solution is not just that it’s possible, because you have control over all the ways your users might get to ~how_user.r)hc, but it’s also perfect because you can pass in the 10 of the user to show as part of the request, and you’ve already pulled information out of the request before, by using $_REQUEST

So far, you’ve seen a few WHERE clauses and they do just what you might expect. The WHERE clause narrows a set of results by applying an additional condition or restriction to the item you’re looking for. In this case, you’re saying, “Give me everything (*) from the us(;'(s table, but only for the records (rows) that have a user _id of the value in $user _id.”

Thus, if your sample user has a user _id of 1,and $user _id is 1,you’ll get that sample user. If you don’t have any rows that have a user _id of 1, you’ll get nothing back from the SELECT. Here’s what’s really cool: you made user _id a primary key (with PRIMARY KEY), which means that you’ll never have more than one result returned. This means that you don’t have to see how many values are returned, or do anything special to handle one row or multiple rows. You’ll either get nothing back because there was no match, or you’ll get just a single row back

When you put all this together, you can make some really important additions to

// Get the user ID of the user to show
$user_id = $_REOUEST[‘user_id’);
// Build the SELECT statement
$select_query = “SELECT * FR{)IIuIsers WHERE user_id = $user_id;
// Run the query
$result = mysql_query($select_query);
// Assign values to variables
<!– All your HTML and inline PHP –>

This script now connects to your database, builds the SELECT statement from the user _id request parameter that was passed to it and then runs the query. All that’s left is the one entirely new piece to this script: running through the actual result from a query and pulling information from that result.

Pulling Values from a SQL Query Result

The $resul t variable is a resource, a special type of variable that holds a reference to more information, as explained .You can pass that resource to other PHP functions, and use it to get more information.

In the case of a SELECT query, what you really want is all the actual rows that the query returned, and then for each row, you want the different values. That’s exactly what you can use a resource for, so you’re all set to finish off slow_user ‘) and start accepting requests

You begin by ensuring that $result has a value. That’s equivalent to ensuring that $result is not false, which is returned when there’s a problem with your SQL

// Run the query
Sresult = mysql_query($select_query);
if ($result) {
// Get the query result rows using $result
} else {
die(“Error locating user with ID {$user_id}”);

This if statement also (marginally) handles errors. If $resul tis false, something went wrong, which presumably means the USer for whom you were searching by using $user _id doesn’t exist, or there was a problem finding that user. So far, it doesn’t format the error nicely providing you with little information about what actually happened that caused the problem. For the time being that’s OK; you’ll beef up your error handling soon, so this if is a decent short-term solution.

Now, you need a new PHP function: mysql_ fetch _array. This function takes a resource from a previously run SOL query. That’s exactly what you have in $result:

Here’s where things get a little odd. Take note of how the preceding script stores the result from mysql_fetch_array in $row. This implies that mysql_fetch_ array returns a single row from your SOL query-and that’s correct.

But. the function’s name suggests something else: It leads you to believe that an an av is returned-mysql_ fetch_array, not mysql_ fetch_row. So, is it a row or is it an array? Well, it’s both. The mysql_fetch_array function does return an array, but it returns an array for a single row of the query associated with the result you pass into it

This means that for mysql_ fetch _array($result), you’re going to get back a single row of results but that the .c’/ that row is returned is in the form of an array .

Because you know how to work with arrays, getting back an array in $row is good news. In fact. $row is just like another array you know, the $_ REQUEST array. And just like $-REQUEST, you have not only a list .of values, but values that are keyed based on a name

When a request came in with a parameter named “first_name,” you pulled the value for that parameter with $ REQUEST[‘ first name’]. The same principle applies to $row. You can give it the name of a column returned in your SQL query, and you’ll get the value for that column in the specific row you’re examining.

Once you have .$ row you can just grab all the columns you want. and then stuff them into some variables

// Run the query
$result = mysql_query($select_query);
if ($result) {
$row = mysql_fetch_array($result);
$first_name = $row[‘first_name’)j
$last_name = $row[‘last_name’)j
$bio = $row[‘bio’)j
$email = $row[’email’)j
$facebook_url = $row[‘facebook_url’)j
$twitter_handle = $row[‘twitter_handle’)j
// Turn $twitter_handle into a URL
$twitter_url =
substr($twitter_handle, $position + l)j
// To be added later
$user_image = “/not/yet/implemented.jpg”j
} else {
die(“Error locating user with ID {$user_id}”);

At this point, you have a fully functional script! In fact, other than figuring out how to use the $result resource with rflysql_ fetch_array, all of this should be no problem for you.

Passing a User 10 into show_user.php

At this point, you need to get a user 10 into your script so that it can use that 10 to look up a user, get her information, and display it. But before you spend a bunch of time of} other scripts, it’s a good idea to ensure that show_user.php works

Fortunately, there’s a very easy way to test your script. The $_REQUEST array has all the information passed into your script through its request, including extra information passed through the request URL itself. Remember, this isn’t the ordinary way you’d either pass information into or even access snow; user.on in the first place. Instead, scripts like or maybe a My Profile button would direct your users to this script.

But for now, you’re just testing. So, go directly to the page by using a URL like _user.php. As long as you’re there, you can feed that script request data with request parameters on the URL itself. You can simply add these to the URL, after a ? (question mark) character.

The format is basically as follows:


For example, you might use  Now, you could grab $_REQUEST[ ‘first_name’]. and you’d get back “Lance.” You can stack these up, too; just separate the parameters with an & (ampersand) character. You could go further and do

php and MySQL

php and MySQL

At this point. you’ve done just about everything you can to ensure that . is going to behave. It’s missing some information, like the user’s pic and bio, but you can deal with the picture later, and you can take care of the bio by updating Other than that, it’s time to leave alone and revisit the script that actually gets users to ~nG “‘. c =ro in the first place

Is a scripts/ Directory a Good Idea

Storing all your scripts in a directory (or, technically, a sub directory)
called is a practice that largely dates back to older programming languages like Perl and CGI

But PHP really blurs the line between what’s a script, and what’s a viewable page. The  script is actually a lot more HTML than it is PHP,and it’s going to be common for a user to actually go to directly. In other words, PHP is more than just a way to write scripts to which your forms submit behind the scenes. There will be lots of times when usess click a link to a PHP page rather than an HTML page, or even type in a URL for the PHP script in his browser

Therefore, beginning in Chapter 8, this change will kick into gear. It’s good that you’ve been thinking about the difference between what you’ve been doing as a web page creator with HTML.CSS,and JavaScript, and your new PHP skills. But, now that you’ve moved beyond just submitting forms to PHP,it’s time to blur the lines even further and let your PHP scripts live alongside your HTML

Posted on January 13, 2016 in Generating Dynamic Web Pages

Share the Story

Back to Top
Share This