Now that you're connected, the next step is to select which database to use with the mysql_select_db command. It takes two parameters: the database name and, optionally, the database connection. If you don't specify the database connection, the default is the connection from the last mysql_connect. $db_select = mysql_select_db($db_database); Again, it's good practice to check for an error and display it every time you access the database.
Now that you've got a good database connection, you're ready to execute your SQL query. Building the SQL SELECT Query Building a SQL query is as easy as setting a variable to the string that is your SQL query. Of course, you'll need to use a valid SQL query, or MySQL returns with an error when you execute the query. The variable name $query is used, but you can choose anything you'd like for a variable name. The SQL query in this example is SELECT * FROM books .
You can build up your query in parts using the string concatenate (.) operator: $select = ' SELECT '; Which is a more flexible version of this: $query = "SELECT * FROM books"; The query string could also use a variable in the WHERE clause to limit which rows are returned based on user information or another query. Now that you have your query assigned to a variable, you can execute it. Executing the Query To have the database execute the query, use the mysql_query function. It takes two parameters--the query and optionally the database link--and returns the result. Save a link to the results in a variable called, you guessed it, $result! This is also a good place to check the return code from mysql_query to make sure that there were no errors in the query string or the database connection by verifying that $result is not FALSE. $result = mysql_query( $query ); When the database executes the query, all of the results form a result set. These correspond to the rows that you saw upon doing a query using the mysql command-line client. To display them, you process each row, one at a time.
|
|
|
|
|
|
|
|