13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

276 Chapter 11 Accessing Your <strong>MySQL</strong> Database from the <strong>Web</strong> with <strong>PHP</strong><br />

Several variations can be used to get results from a result identifier. Instead of an array<br />

with named keys, you can retrieve the results in an enumerated array with<br />

mysqli_fetch_row(), as follows:<br />

$row = $result->fetch_row($result);<br />

or<br />

$row = mysqli_fetch_row($result);<br />

The attribute values are listed in each of the array values $row[0], $row[1], <strong>and</strong> so on.<br />

(The mysqli_fetch_array() function allows you to fetch a row as either or both kinds<br />

of array.)<br />

You could also fetch a row into an object with the mysqli_fetch_object() function:<br />

$row = $result->fetch_object();<br />

or<br />

$row = mysqli_fetch_object($result);<br />

You can then access each of the attributes via $row->title, $row->author, <strong>and</strong> so on.<br />

Disconnecting from the Database<br />

You can free up your resultset by calling either<br />

$result->free();<br />

or<br />

mysqli_free_result($result);<br />

You can then use<br />

$db->close();<br />

or<br />

mysqli_close($db);<br />

to close a database connection. Using this comm<strong>and</strong> isn’t strictly necessary because the<br />

connection will be closed when a script finishes execution anyway.<br />

Putting New Information in the Database<br />

Inserting new items into the database is remarkably similar to getting items out of the<br />

database.You follow the same basic steps: make a connection, send a query, <strong>and</strong> check the<br />

results. In this case, the query you send is an INSERT rather than a SELECT.<br />

Although this process is similar, looking at an example can sometimes be useful. In<br />

Figure 11.3, you can see a basic HTML form for putting new books into the database.<br />

The HTML for this page is shown in Listing 11.3.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!