Using a MySQL database with PHP - Page 2September 24, 2002 Running queriesNow that you're connected, let's try and run some queries. The easiest kind of query to perform is one that doesn't return any results, such as an INSERT, UPDATE or DELETE statement. The function used to perform queries is once again aptly named - mysql_query(). In the case of a query that doesn't return results, the resource that the function returns is simply a value true or false. True means the query succeeded, and false means it failed. The link identifier in our case is $dbh, the database handle. We don't need the result mode yet. Let's add another row of data to the table. Change the script to read as follows: <?php $username = "pee_wee"; $password = "let_me_in"; $hostname = "localhost"; $dbh = mysql_connect($hostname, $username, $password) Note that you don't need to end the query with the semicolon you usually end MySQL queries with. PHP takes care of that for you. The first time you run this script, all going well, it will display "Successfully inserted record". If you run it again, you should get "Failed to insert record". Remember that we made the id field a primary key. When we try and add '5' to the id field a second time, the query fails because it would result in a duplicate key if it succeeded. To return the results of a query, for example with a SELECT statement, we start in the same way, with the mysql_query() function. This time though the function returns a resource that contains the results of the query, called the result set (or statement handle). We can then use one of the many fetch functions to examine the result. We're going to use the most flexible one, mysql_fetch_array, which returns the results row by row as both an associative array and a numeric array. <?php $username = "pee_wee"; $password = "let_me_in"; $hostname = "localhost"; $dbh = mysql_connect($hostname, $username, $password) |