本文展示一個簡單的 link_mysql 函數,封裝連線、查詢、關閉等常用操作,支援讀/寫/刪/改區分(雖實際邏輯相同),適合中小型專案快速引用。
<?php
$str_sql_read = "select count(*) as num from userinfo";
$str_sql_del = "delete from userinfo where id = 1";
$res = link_mysql("read", $str_sql_read);
$res_del = link_mysql("delete", $str_sql_del);
echo $res_del . "<br/>";
while ($row = mysql_fetch_assoc($res)) {
echo "<font style='font-size:25px;color:red;'>" . $row['num'] . "</font><br/>";
}
?>
<?php
function link_mysql($opt, $str_sql) {
$con = mysql_connect("localhost", "root", "root") or die('Not connected : ' . mysql_error());
mysql_set_charset("gbk", $con);
mysql_select_db("website", $con);
switch ($opt) {
case "read":
case "update":
case "delete":
case "insert":
$res = mysql_query($str_sql);
break;
}
mysql_close();
return $res;
}
?>
mysqli 或 PDO。die(),方便上層捕獲處理。utf8mb4。此範例僅供理解封裝概念,實際專案請採用成熟的資料庫抽象層(如 PDO、Medoo、Eloquent 等)。