用户名:  密码:   
您当前的位置:首页 > 网页设计 >  PHP > 

PHP连接与操作数据库常用代码

上次修改时间: 2024-08-29 17:24:13      来源:网络总结      作者:钢铁长陈
上一页      路径:DSD\Learn\PHP相关\      下一页

PHP连接与操作数据库常用代码

============连接数据库用到的代码========================================
//这里的代码可保存到单的conn.php文件, 在其它文件中用require "admin/conn.php";引用,或Require_once "conn.php";
$servername = "192.168.13.77";
$username = "root";
$password = "root";
$dbname = "ctcms";

$conn = new mysqli($servername, $username, $password, $dbname);

// 检查数据库连接
if ($conn->connect_error) {
    die("数据库连接失败:" . $conn->connect_error);
}

// 设置字符编码为 UTF-8  //这里很重要,没有这句PHP上传到mysql中的是GBK编码,在PHPMYamdin中显示乱码
if (!$conn->set_charset("utf8")) { 
    die("设置字符编码失败: " . $conn->error); 
} 
============================================================================

// 获取地址栏参数
$val = isset($_POST['val']);

===========如需翻页用到的代码============================
// 定义每页显示的数据条数
$records_per_page = 16;

// 获取当前页数
if (isset($_GET['page']) && $_GET['page'] > 0) {
    $page = $_GET['page'];
} else {
    $page = 1;
}

// 计算查询的起始偏移量,即当前页从第多少条数据开始
$offset = ($page - 1) * $records_per_page;

//开始输出数据
$sql = "SELECT * FROM tbcatalog ORDER BY Path ASC, OrderID DESC LIMIT $offset, $records_per_page";
。。。。

//表格底部还要加上如下代码
// 计算总页数
$total_pages_sql = "SELECT COUNT(*) as count FROM tbcatalog";
$total_pages_result = $conn->query($total_pages_sql);
$total_pages_row = $total_pages_result->fetch_assoc();
$total_pages = ceil($total_pages_row["count"] / $records_per_page);
注:这里的$total_pages_sql语句中的where语句和order必须与输出数据的sql一样,但不能为LIMIT子语句,否则分页总数为0

// 显示分页链接
for ($i = 1; $i <= $total_pages; $i++) {
 echo "<a href='?page=" . $i . "'>" . $i . "  </a> ";
}
注:页面如有多个参数或条件还需加上,如:echo "<a href='".$myurl."&page=" . $i . "'>" . $i . "  </a> ";
=============================================================

// 根据val的值判断要执行那条 SQL 插入语句
if ($val=1) {
    $sql = "DELETE t1 FROM cjzsLoginData t1 INNER JOIN cjzsLoginData t2 WHERE t1.mac = t2.mac AND t1.logtime < t2.logtime";
}else{
    $sql = "DELETE t1 FROM cjzsLoginData t1 INNER JOIN cjzsLoginData t2 WHERE t1.mac = t2.mac AND t1.logtime < t2.logtime";
}


// 执行插入操作并检查结果
if ($conn->query($sql) === TRUE) {
    echo "Execute sql OK";
} else {
    echo "Execure sql error:" . $conn->error;
}

 

// 执行多条SQL语句的方法
$sql = "CREATE TABLE cjzsLoginData2 LIKE cjzsLoginData;
  INSERT INTO cjzsLoginData2 SELECT * FROM cjzsLoginData;
  ";
if ($conn->multi_query($sql)) {
    do{
        if ($result = $conn->store_result()){   //判断是否有结果集
            $result->free();   
        }
    }while ($conn->more_results() && $conn->next_result());  //检查是否有下一结果集
    echo "多条语句执行成功";
} else {
    echo "Error:" . $sql . "<br>" . $conn->error;
}

//查询数据并循环输出,1条与多条数据都可用此法
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) { //有结果且结果大于0,先判断$result是一个有效的结果
if ($result && $result->num_rows == 0) { //这里易出错,判断为空不能用单等号,单等号是赋值操作,有结果且结果为0
while ($rs = $result->fetch_assoc()) {
 echo $rs['CatalogName']
}

//多层嵌套查询,第一层查询的
//注:多层嵌套内外层的$result不能同名,否则只会输出一个结果,这里易出错
$sql = "SELECT classid, classname FROM ct_linktype where yesno=1 order by ct_sort";
$resulttype = mysqli_query($conn, $sql);
while ($rowtype = mysqli_fetch_array($resulttype)) { ?>
  <div class="title bd1"><?php print $rowtype["classname"] ?></div>
   <?php  //这里是内部循环根据类id,在横线上面区域输出当前类下有图片的所有链接
   $sql = "SELECT lid, lname, lpic, lurl, target FROM ct_link where classid=" . $rowtype["classid"] . " and lpic<>''";
   $result = mysqli_query($conn, $sql);
   if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_array($result)) {
     echo '<li><a href="' . $row["lurl"] . '" target='. $row["target"].'><img src="admin/up/' . $row["lpic"] . '" alt="' . $row["lname"] . '"> </a></li>';
    }
   }?>
  </div>
 </div>
<?php } ?>


//上传数据
 $update_date = date('Y-m-d H:i:s', time());
 $content = $_POST["content"];
 $sql = "UPDATE ct_notepad
  SET title='$title',
   content='$content',
   update_date='$update_date'
  where nid='$nid'";
 //echo $sql;
 $retval = mysqli_query($conn, $sql);
 if (!$retval) {
  die('无法更新数据: ' . mysqli_error($conn));
 }

//删除一条数据
 $sql="DELETE FROM ct_notepad WHERE nid = $nid";
 $retval = mysqli_query($conn, $sql);
 if (!$retval) {
  die('无法更新数据: ' . mysqli_error($conn));
 } 

//插入一条数据1
  $title = $_POST["title"];
  $content = $_POST["content"];
  $sql = "INSERT INTO ct_notepad " .
   "(title,content, update_date) " .
   "VALUES " .
   "('$title','$content','$update_date')";
  mysqli_select_db($conn, 'ctcms');
  $retval = mysqli_query($conn, $sql);
  if (!$retval) {
   die('无法插入数据: ' . mysqli_error($conn));
  } 
//插入一条数据2
// 准备 SQL 插入语句
 $ver = $_GET['ver'];。。。
 $sql = "INSERT INTO `cjzsLoginData` (`ver`, `cname`, `logtime`)
  VALUES ('$ver', '$cname', NOW())";

 // 执行插入操作并检查结果
 if ($conn->query($sql) === TRUE) {
     echo "数据插入成功";
 } else {
     echo "数据插入失败:" . $conn->error;
 }

===========以下为使用预处理语句防注入方式处理数据,推荐以下方法============================================================================================================
//更新数据
<?php
require 'connMydata.php'; // 数据库连接

if (isset($_POST['link_id'])) {
    $linkId = $_POST['link_id'];
    $sql = "UPDATE links SET click_count = click_count + 1 WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $linkId);
    $stmt->execute();
    $stmt->close();
}
?>

//插入数据,特别是上传的数据中有特殊字符时,如路径中的\
if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {
    $typeflag = trim( $_POST[ 'typeflag1' ] );
    $path = trim($_POST['path']);
    $ltime = date('Y-m-d H:i:s', time());

    // 创建预处理语句,$stmt = $conn->prepare用以创建预处理语句
    $stmt = $conn->prepare("INSERT INTO ct_txtclass1 (typeflag, path, ltime) VALUES (?, ?, ?)");
    if ($stmt === false) {
        die('准备语句失败: ' . $conn->error);
    }

    // 绑定参数,$stmt->bind_param用以给预处理语句绑定参数
    //这里的3个s表上面创建预处理语句里3个参数,s表string,i表integer,d表double,b表blob,双精度,二进制
    $stmt->bind_param('sss', $typeflag, $path, $ltime); 

    // 执行语句
    $retval = $stmt->execute();
    if (!$retval) {
        die('无法插入数据: ' . $stmt->error); //die中输出一条信息并中止脚本运行
    }

    // 关闭语句,与与$conn->close无关,这里只关闭预处理语句
    $stmt->close();
}


//查询数据,注:查询的字串中有特殊字符(如路径中的\)时必须用这种方法,否则无法查询出数据
    // 使用预处理语句防止 SQL 注入
    $stmt = $conn->prepare('SELECT * FROM ct_txtclass1 WHERE path = ?');
    $stmt->bind_param('s', $path);
    $stmt->execute();
    $result = $stmt->get_result();

    // 检查结果是否存在
    if ($result->num_rows == 0) { // 如果不存在,则插入,否则表有相同数据
 echo "数据不存在"; 
    } else {
        echo "数据已存在,请勿重复插入!";
    }

     // 直接输出结果
     if ($result->num_rows > 0) { // 如果不存在,则插入,否则表有相同数据
 while ($row = $result->fetch_assoc()) {
     echo "<li><a href='newlist.html'>".$row['CatalogName']."</a></li>";
 }
     }
    // 关闭语句和连接
    $stmt->close();

//防注入多层嵌套查询
    <?php 
    // 准备并执行第一个查询
    $stmt = $conn->prepare('SELECT CatalogName,FatherPath,AllPath FROM ct_txtclass WHERE FatherPath = ?');
    $stmt->bind_param('s', $fPath);
    $stmt->execute();
    $result = $stmt->get_result();

    // 直接输出结果
    if ($result->num_rows > 0) {
 while ($row = $result->fetch_assoc()) {
     $AllPath=$row['AllPath'];
     echo "<div class='mlc1l1 bd1 title'>".$row['CatalogName']."<span><a href='newmore.html'>更多>></a></span></div>";
     //以外层查询内容作为条件再查询
     if (!empty($AllPath)){
  $stmt1 = $conn->prepare('SELECT typeflag,title,ltime FROM ct_txthtml WHERE typeflag = ? limit 5');
  $stmt1->bind_param('s', $AllPath);
  $stmt1->execute();
  $result1 = $stmt1->get_result();
      
  // 直接输出结果
  if ($result1->num_rows > 0) {
      while ($row1 = $result1->fetch_assoc()) {
   echo "<li><a href='newcontent.html'>".$row1['title']."</a><span>".$row1['ltime']."</span></li>";
      }   
  }else{
      echo "<li>当前分类下没有数据</li>";
  }
  // 关闭语句和连接
  $stmt1->close();
     }
 }
    } else {
 echo "<p>没有找到相关分类</p>";
    }
    // 关闭语句和连接
    $stmt->close();
?>

将防注入查询数据的代码写到单独的fun.php文件中
//不需在函数单元引用数据连接文件,,只需要调用函数的单元有用require "connMydata.php"引入就可以了
function getlinkhtml($path) {
    global $conn; //注:这里必须将$conn声明为全局

    $sql = "SELECT CatalogName,Path,AllPath FROM ct_txtclass WHERE Path = ?";
    if ($stmt = $conn->prepare($sql)){
        $stmt->bind_param('s', $path);
        $stmt->execute();
        $result = $stmt->get_result();

        if($result->num_rows > 0){
            $row = $result->fetch_assoc();
            $stmt->close();          
            return "<a href='list.php?path=" . htmlspecialchars($row['Path']) . "'>" . htmlspecialchars($row['CatalogName']) . "</a>&nbsp;>&nbsp\n";
        }
    }
    return "";  //如没有结果返回空
}

list.php中调用
require_once "admin/fun.php"; //引入文件
<?php echo getlinkhtml($fPath); ?>
========================================================================
一次删除多条数据的PHP代码, 主要是表单里第一列为checkbox,name为ids[]数组,PHP代码里用POST接收这个数组
// 处理删除多个记录操作
if (isset($_POST['ids']) && is_array($_POST['ids'])) {
    $ids = $_POST['ids'];
    
    // 确保 IDs 是整数,并构建 SQL 删除语句
    $ids = array_map('intval', $ids);   // 将数组$ids中的每个元素用intval函数转换为整数,防止SQL注入攻击,array_map函数用于将一个函数应用于数组中的每个元素。
    $ids_list = implode(',', $ids);   // 将数组$ids转换为字符串,用逗号分隔,用于SQL查询。
    print_r($ids);
   
    // 构建 SQL 删除语句
    // $sql = "DELETE FROM cjzsLoginData3 WHERE lid IN ($ids_list)";
   
    // if ($conn->query($sql) === TRUE) {
    //     echo "记录删除成功";
    // } else {
    //     echo "删除失败: " . $conn->error;
    // }
} else {
    echo "没有选中的记录";
}
//表单
<!-- //注意这里的form而不是from,这里出错没提示,提交没数据,手动易输错误 -->
    <form id="deleteForm" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <table border="1">
            <?php for ($i=0; $i < 10; $i++) { ?>           
            <tr><td><input type='checkbox' name='ids[]' value='<?php echo $i ?>'></td><td>7.6</td><td>aa</td><td>bb</td></tr>
            <?php } ?>
        </table>
        <button type="submit">提交</button>
    </form>