年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1950|回复: 0

PDO预处理语句并执行示例

[复制链接]
  • TA的每日心情

    2024-10-15 10:05
  • 签到天数: 372 天

    [LV.9]以坛为家II

    发表于 2016-1-11 11:59:12 | 显示全部楼层 |阅读模式
    [PHP] 纯文本查看 复制代码
    <?php
        // 设置错误异常捕捉
    // 	$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    	
    	
    	try{
    		$dsn = "mysql:host=localhost;dbname=bookstore";
    		$pdo = new PDO($dsn, "root", "****");
    	}catch(PDOException $e){
    		echo "数据库连接失败:".$e->getMessage();
    		exit;
    	}
    	
    	try{
    		// 准备好语句,数据库预编译
    		$sql = "insert into books(bookname, publisher, author, price) values(?, ?, ?, ?)";
    		$stream = $pdo->prepare($sql);
    		// 绑定参数
    		$stream->bindParam(1, $bookname);
    		$stream->bindParam(2, $publisher);
    		$stream->bindParam(3, $author);
    		$stream->bindParam(4, $price);
    		// 给变量赋值
    		$bookname = "book".rand(10, 99);
    		$publisher = "Publisher".rand(100, 999);
    		$author = "Author".rand(10, 99);
    		$price = rand(50, 150);
    		// 执行语句
    		$stream->execute();
    	}catch(PDOException $e){
    		echo $e->getMessage();
    	}

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-12-5 02:54 , Processed in 0.043421 second(s), 18 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表