A function to open a connection to mysql
<?php
function opendatabase ($host,$user,$pass) {
try {
if ($db = mysql_connect ($host,$user,$pass)){
return $db;
} else {
throw new exception ("Sorry, could not connect to mysql.");
}
} catch (exception $e) {
echo $e->getmessage ();
}
}
function closedatabase ($db){
mysql_close ($db);
}
$db = opendatabase ("localhost","root","");
try {
if (!mysql_select_db ("mydatabase",$db)){
throw new exception ("Sorry, database could not be opened.");
}
$myquery = "INSERT INTO mytable (id,title,myvalue) VALUES (0,'Blue',20)";
if (mysql_query ($myquery, $db)){
echo "We were successful.";
} else {
throw new exception (mysql_error());
}
} catch (exception $e) {
echo $e->getmessage();
}
closedatabase ($db);
?>
Related examples in the same category