[Tutorial] Connecting to a MySQL DB

Example of PHP code.

Moderator: Moderators

[Tutorial] Connecting to a MySQL DB

Postby shorty114 on Sat Feb 19, 2005 4:41 pm

This tutorial shows how to connect to a MySQL database. It print_r's the row information.

Code: Select all
<?php

// CHANGE THESE VALUES

// the host (most likely localhost)
$host = 'localhost';
// the username
$user = 'username';
// the password
$pass = 'password';
// the database name
$db = 'some_db';
// the table you want to SELECT data from
$tbl = 'a_table';

// END CONFIG

// Connect to $host with $user and $pass
$link = @mysql_connect($host, $user, $pass);

// Did it fail?
if (!$link) die('Could not connect to database: '.mysql_error()); // Add mysql_error for info

// Select the database $db
if (!@mysql_select_db($db)) die('Could not select database: '.mysql_error());

// query the DB and SELECT all from $tbl
$query = @mysql_query("SELECT * FROM `{$tbl}`");

// Did it fail?
if (!$query) die('Could not query database: '.mysql_error());

echo '<pre>';

// Fetch the rows
while ($row = mysql_fetch_array($query))
{
// dump the $row array info
print_r($row);
}

echo '</pre>';

// Free the $query result
@mysql_free_result($query);

// Close the conn
@mysql_close($link);

/*
Notes:
- the @ before the function names suppresses any warnings/errors. the if (!$<variable>) block checks if the function didn't succeed, and then makes the appropriate errors.
- mysql_error return the last error made by a mysql_* function. It's very useful for debugging.
*/

?>


That's it.

Further references:
PHP Manual section on MySQL
PHP Manual (very useful)
shorty114
Registered User
Registered User
 
Posts: 99
Joined: Wed Dec 15, 2004 10:45 pm
Location: Lost...

Postby shorty114 on Sat Feb 19, 2005 4:42 pm

If anyone has any suggestions, please post them here.
shorty114
Registered User
Registered User
 
Posts: 99
Joined: Wed Dec 15, 2004 10:45 pm
Location: Lost...

Postby eve4ever on Thu Mar 10, 2005 3:12 pm

Install.php
inserted all requested fields and shows up.......

I get an error:Could not connect to database: Client does not support authentication protocol requested by server; consider upgrading MySQL client

Have downloaded the lates mysql and apache!Php4.x!

What does this error mean.and what can i do about it
eve4ever
Registered User
Registered User
 
Posts: 1
Joined: Thu Mar 10, 2005 3:10 pm

Postby PostBot on Thu Mar 10, 2005 3:25 pm

For latest mySQL you should use PHP 5 and mySQLi functions. Or change to mySQL 4.0
Do NOT pm me, I don't visit this forum anymore, don't own it, don't provide any support and don't moderate.
User avatar
PostBot
Moderator
Moderator
 
Posts: 10659
Joined: Sat Aug 02, 2003 3:52 pm
Location: Mars

Postby shorty114 on Sun Apr 24, 2005 2:17 am

Install.php?
shorty114
Registered User
Registered User
 
Posts: 99
Joined: Wed Dec 15, 2004 10:45 pm
Location: Lost...


Return to PHP Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest

cron