Connecting to the MySQL server with PHP

In PHP (on the UNIX server or on the IIS server) you should use the following lines of code to connect to the MySQL server:

$conn = @mysqli_connect("","userid","password","mdb_userid");

if (!$conn) {
    /* Use your preferred error logging method here */
    error_log('Connection error: ' . mysqli_connect_errno());
    echo "Failed to connect to MySQL: " . mysqli_connect_error();

if ($result = mysqli_query($conn, "SELECT * FROM table")) {
	printf("Select returned %d rows.\n", mysqli_num_rows($result));
	echo "Result set order...";
	while ($row = $result->fetch_assoc()) {
		echo $row['field1'].' '.$row['field2'];


In all cases, the hostname is ‘’, and your database is called ‘mdb_username’ (for example, the user ID aaa001 would have a database ‘mdb_aaa001’).

For security reasons, you should ensure you use a different password for your SQL Server login than you do for other University systems.

For more information and a reference of all the commands available, go to the MySQL documentation page.

The following example shows a PDO connection that will currently work on the web server ‘’ only:

$db = new PDO(';dbname=mdb_userid;charset=utf8','userid','mysql_password');
$stmt = $db->query("SELECT * FROM table");
$row_count = $stmt->rowCount();
echo 'Number of Rows selected '. $row_count .'<p>';
echo "While loop ....<p>";
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['col1'].' '.$row['col2'] .'<p>';
echo "Foreach loop ....<p>";
foreach($db->query('SELECT * FROM table') as $row) {
    echo $row['col1'].' '.$row['col2'] .'<p>';

Comments are closed.