1准备工作

首先,确保你的环境中已安装:

  • PHP 7.0+
  • MySQL/MariaDB
  • Web服务器(Apache/Nginx)

2数据库连接代码

// config.php
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "连接成功";
} catch(PDOException $e) {
    echo "连接失败: " . $e->getMessage();
}
?>

3创建测试表

CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(30) NOT NULL,
    email VARCHAR(50) NOT NULL,
    reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

4实际演示

下面是一个简单的用户注册表单示例:

// register.php
prepare($sql);
        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':email', $email);
        $stmt->execute();
        echo "注册成功!";
    } catch(PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}
?>

5查询数据示例

prepare($sql);
    $stmt->execute();
    
    // 设置结果集为关联数组
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    
    foreach($stmt->fetchAll() as $row) {
        echo "ID: " . $row["id"]. " - 用户名: " . $row["username"]. " - 邮箱: " . $row["email"]. "
";
    }
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>
Posted on 2024-03-08 16:38  北边村的富少  阅读(10)  评论(0编辑  收藏  举报