用户工具

站点工具


已恢复为旧版 (2025/12/11 13:46)
数据库

php处理数据库的函数

首先使用mysql作为主要使用类型。

后续有sqlite 和其他类型的数据库

mysql时间处理 日期格式转化为时间戳(秒数) unix_timestamp('20220-9-26')

数据库连接

1. 使用mysql_connect

<?php
$con=mysql_connect("localhost" ,"root","password")
if($con){
  mysql_select_db("db_name",$con);
  $sql="select * from table_name where id=1";
  $result=mysql_query($sql);
  while($row=mysql_fetch_row($result)){
      echo  "$row";
  }
}else{
  die("无法连接数据库".mysql_error());
}
mysql_close($con);
?> 

2. 使用mysqli

<?php
  $con=new mysqli("localhost","root","password","db_name");
  if(!mysqli_connect_error()){
  $sql="select * from table_name where id=1";
  $result=$con->query($sql);
  while($row=$result->fetch_row($result)){
      echo  "$row";
  }
}else{
  die("无法连接数据库".mysql_error());
}

3. 使用PDO

<?php
$mysql_conf = array(
  'host'    => '127.0.0.1:3306', 
  'db'      => 'test', 
  'db_user' => 'root', 
  'db_pwd'  => 'joshua317', 
  );
$pdo = new PDO("mysql:host=" . $mysql_conf['host'] . ";dbname=" . $mysql_conf['db'], $mysql_conf['db_user'], 
$mysql_conf['db_pwd']);//创建一个pdo对象
$pdo->exec("set names 'utf8'");
$sql = "select * from user where name = ?";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(1, 'joshua', PDO::PARAM_STR);
$rs = $stmt->execute();
if ($rs) {
  // PDO::FETCH_ASSOC 关联数组形式
  // PDO::FETCH_NUM 数字索引数组形式
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      var_dump($row);
  }
}
 $pdo = null;//关闭连接
?>

查询数据

修改数据

新增数据

删除数据

修改表

创建表

删除表

/home/minxuanbm4ipnyxlu3ann/wwwroot/dokuwiki/data/pages/数据库.txt · 最后更改: 2026/05/02 09:33 由 216.73.216.142