php使用mysql封装函数删除表数据

时间:2016-07-22
本文章向大家介绍php删除mysql表数据的实例,在本实例中,我们用自己写的封装函数来操作mysql数据库,封装的函数有连接数据库服务器、选择数据库、打开数据库连接和关闭数据库连接等函数,需要的朋友可以参考一下。

php删除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 (); 
} 
} 
/* http://www.manongjc.com/article/1239.html */
function selectdb ($whichdb, $db){ 
try { 

if (!mysql_select_db ($whichdb,$db)){ 
throw new exception ("Sorry, database could not be opened."); 
} 
} catch (exception $e) { 
echo $e->getmessage(); 
} 
} 
function closedatabase ($db){ 
mysql_close ($db); 
} 
$db = opendatabase ("localhost","root",""); 

selectdb ("mydatabase",$db); 
$updatequery = "DELETE FROM mytable WHERE id=2"; 
try { 

if (mysql_query ($updatequery, $db)){ 

echo "Your record has been removed."; 

if ($aquery = mysql_query ("SELECT * FROM mytable WHERE id=2")){ 

echo "<br />" . mysql_num_rows ($aquery);

} else { 

echo mysql_error(); 

} 
} else { 
throw new exception (mysql_error()); 
} 
} catch (exception $e) { 
echo $e->getmessage(); 
} 
closedatabase ($db); 
?>

从上面源码可以看出,我们把mysql_connect封装到opendatabase函数中,如果需要连接mysql服务器,直接调用opendatabase函数即可,同理,

mysql_select_dbmysql_close都分别封装到selectdb和closedatabase函数中,如果需要选择数据库操作和关闭数据库操作,只需要分别调用selectdb和closedatabase函数即可。

上一页 下一页

原文地址:http://www.manongjc.com/article/1239.html