Home  >  Article  >  Backend Development  >  Small examples of php database connection, query, and display results

Small examples of php database connection, query, and display results

WBOY
WBOYOriginal
2016-07-25 08:55:551202browse
  1. /**
  2. * PHP operates database (connection, query, display results)
  3. * edit: bbs.it-home.org
  4. */
  5. define ('HOSTNAME', 'localhost'); //Database host name
  6. define ('USERNAME', 'username'); //Database Username
  7. define ('PASSWORD', 'password'); //Database user login password
  8. define ('DATABASE_NAME', 'testdb'); //Database to be queried
  9. $db = mysql_connect(HOSTNAME, USERNAME, PASSWORD) or
  10. die (mysql_error());
  11. //If the connection cannot be made, the reason for the mysql error will be displayed.
  12. mysql_select_db(DATABASE_NAME);
  13. //Switch to testdb
  14. $query =
  15. "SELECT uri,title FROM testdb WHERE 1 ORDER by rand() LIMIT 1";
  16. //The above sentence means to randomly extract an item from testdb data.
  17. $result = mysql_query($query);
  18. //Query
  19. while ($row = mysql_fetch_array($result)) { echo "

    " ,

  20. ($row['title'] ), "

    –" , nl2br($row['uri'])

  21. , "

    "; }
  22. //Display results
  23. mysql_free_result ($result);
  24. //Release the result
  25. mysql_close();
  26. //Close the connection
  27. ?>
Copy code

You may also like: php mysql database class (compatible with php4 and php5) PHP class to connect to mysql database (interface implementation) Simple example of php operating database A class for php to connect to mysql database php mysql database class (php newbies’ introduction) Simple example of php connecting to database php mysql database operation class php database operation class (implementing table additions, deletions, modifications, querying, fetching rows, querying multiple pieces of data, etc.) A simple mysql database class A class for php to call the database php database operation code collection Application examples of PHP database calling class (detailed comments)



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn