PDA

View Full Version : Basic mySQL connection



kyle
28th July 2006, 12:06 AM
Hi,

Here is how to connect to mySQL



<?php

$hostname = ''; // hostname of the server with mySQL ( localhost )
$username = ''; // your username to access your database
$password = ''; // your password to access your database
$database = ''; // your database name for example username_database

$link = mysql_connect($hostname, $username, $password) or die (mysql_error());

if ($link)
{
mysql_select_db($database, $link);
}

?>


Ok now we have a connection to the database, lets add a row to a table we already created in phpMyadmin



<?php

$sql = "INSERT INTO table (field1, field2, field3) VALUES ('value1','value2','value2')";

$query = mysql_query ($sql, $link);

if ($query)
{
echo 'row inserted';
} else {
echo 'failed to insert new row<br/>mySQL said:<br/><br/>' . mysql_error($link);
exit;
}

?>


Please note this code has not been tested, and was written as a guide line ...

yveslebeau
18th October 2006, 02:57 PM
Don't forget to close your connection



<?
mysql_close();
?>


Can cause troubles sometimes :D