Home >> FAQs/Tutorials >> MySQL Tutorials >> Index

MySQL FAQs - PHP Connections and Query Execution

By: FYIcenter.com

Part:   1  2  3  4  5  6  

(Continued from previous part...)

Can You Select Someone Else Database?

If your MySQL server is provided by an Internet service company, they will provide you one database for your use only. There are many other databases on the server for other users. But your user account will have no privilege to select other databases. If you try to access other databases, you will get an error. The following tutorial exercise shows you a guest user trying to access the system "mysql" database:

<?php
  $con = mysql_connect('localhost:8888', 'guest', 'pub');
  if (mysql_select_db('mysql', $con)) {
    print("Database mysql selected.\n");
  } else {
    print("Database selection failed with error:\n");
    print(mysql_errno($con).": ".mysql_error($con)."\n");
  }
  mysql_close($con); 
?>

You will get something like this:

Database selection failed with error:
1044: Access denied for user 'guest'@'%' to database 'mysql'

How To Run a SQL Statement?

You can run any types of SQL statements through the mysql_query() function. It takes the SQL statement as a string and returns different types of data depending on the SQL statement type and execution status:

  • Returning FALSE, if the execution failed.
  • Returning a result set object, if the execution is successful on a SELECT statement or other statement returning multiple rows of data.
  • Returning TRUE, if the execution is successful on other statements.

Here is a good example of running a SQL statement with the mysql_query() function:

<?php
  include "mysql_connection.php";

  $sql = 'SELECT SYSDATE() FROM DUAL';
  $res = mysql_query($sql, $con);
  $row = mysql_fetch_array($res);
  print("Database current time: ". $row[0] ."\n");

  mysql_close($con); 
?>

If you run this script, you will get something like this:

Database current time: 2006-07-01 21:34:57

Part:   1  2  3  4  5  6  


Selected Developer Jobs:

More...