<?PHP function db_connect($host,$user,$pwd,$name,$charset) { $link = Mysqli
<?PHP
function db_connect($host,$user,$pwd,$name,$charset)
{
$link = Mysqli_connect($host,$user,$pwd);
if (!$link) {
return false;
}
if (!mysqli_select_db($link,$name)) {
return false;
}
mysqli_set_charset($link,$charset);
return $link;
}
function db_insert($link,$table,$data)
{
$keys = join(',', array_keys($data));
$values = implode(',', parse_value(array_values($data)));
$sql = "insert into $table($keys) values($values)";
//echo $sql;die;
$result = mysqli_query($link, $sql);
if ($result && mysqli_affected_rows($link)) {
//返回本次插入的id(该表有自增的id字段)
return mysqli_insert_id($link);
}
return false;
}
function db_delete($link,$table,$where)
{
$sql = "delete from $table where $where";
$result = mysqli_query($link,$sql);
if ($result && mysqli_affected_rows($link)) {
return true;
}
return false;
}
function db_update($link,$table,$set,$where)
{
if (is_array($set)) {
$set = join(',', parse_set($set));
}
$sql = "update $table set $set where $where";
$result = mysqli_query($link, $sql);
if ($result && mysqli_affected_rows($link)) {
return true;
}
return false;
}
function db_select($link,$table,$fields, $where=null, $orderby=null)
{
if (is_array($fields)) {
$fields = implode(',',$fields);
}
$sql = "select $fields from $table";
if ($where) {
$sql .= " where $where";
}
if ($orderby) {
$sql .= " order by $orderby";
}
$result = mysqli_query($link,$sql);
if ($result && mysqli_affected_rows($link)) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
return $data;
}
return false;
}
//辅助函数1:对字符类型进行处理
function parse_value($data)
{
if (is_string($data)) {
$data = '\'' . $data . '\'';
} else if (is_array($data)) {
$data = array_map('parse_value', $data);
} else if (is_null($data)) {
$data = 'null';
}
return $data;
}
//辅助函数2:对数组进行遍历
function parse_set($set)
{
foreach ($set as $key => $value) {
$data[] = $key . '=' . parse_value($value);
}
return $data;
}
--结束END--
本文标题: PHP对Mysql操作的自定义函数
本文链接: https://lsjlt.com/news/47905.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0