在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
PDO使用dns进行连接,我采用new ClassName()方式(其实大同小异,形式罢了)。 尝试先插入,然后查询,在查询遍历每一条的时候插入。 1 <?php 2 $dsn = 'mysql:dbname=stuphp;host=127.0.0.1'; 3 $user = 'root'; 4 $password = 'admin'; 5 6 try { 7 $dbh = new PDO ( $dsn, $user, $password ); 8 } catch ( PDOException $e ) { 9 echo 'Connection failed: ' . $e->getMessage (); 10 } 11 $dbh->query ( 'set names utf8' ); // 是我的mysql数据库也是utf8编码的 。但是就是不行。必须这么写才行。 12 13 //插入一条记录 14 $username = 'leaves'; 15 $password = 's&^*&B324'; 16 $mark = '我是好人'; 17 $pstmt = $dbh->prepare ( 'INSERT INTO TUSER(USERNAME,PASSWORD,MARK) VALUES(:username,:password,:mark)' ); 18 $pstmt->bindParam ( ':username', $username ); 19 $pstmt->bindParam ( ':password', $password ); 20 $pstmt->bindParam ( ':mark', $mark ); 21 $pstmt->execute (); 22 print_r ( $pstmt->errorInfo () ); 23 24 $sql = 'SELECT USERNAME,PASSWORD,MARK FROM TUSER'; 25 $result = $dbh->query ( $sql ); 26 27 $row = $result->fetchObject (); 28 $dbh->beginTransaction(); 29 while ( $row ) { 30 $username = $row->USERNAME; 31 $password = $row->PASSWORD; 32 $mark = $row->MARK; 33 34 echo $username . "\t"; 35 echo $password . "\t"; 36 echo $mark . "<br/>"; 37 38 39 //------------------中途尝试插入 40 $pstmt = $dbh->prepare ( 'INSERT INTO TU22SER(USERNAME,PASSWORD,MARK) VALUES(:username,:password,:mark)' ); 41 $pstmt->bindParam ( ':username', $username ); 42 $pstmt->bindParam ( ':password', $password ); 43 $pstmt->bindParam ( ':mark', $mark ); 44 $pstmt->execute (); 45 print_r ( $pstmt->errorInfo () ); 46 //上面的查询不会成功。原因是在查询没有结束的时候不允许你继续插入,就好像别人在存钱,你在取钱一样。 47 //下面是异常信息 48 /* 49 * Array ( [0] => HY000 [1] => 2014 [2] => Cannot execute queries while 50 * other unbuffered queries are active. Consider using 51 * PDOStatement::fetchAll(). Alternatively, if your code is only ever going 52 * to run against mysql, you may enable query buffering by setting the 53 * PDO_MYSQL_ATTR_USE_BUFFERED_QUERY attribute. ) 54 */ 55 56 $row = $result->fetchObject (); 57 } 58 59 60 //插入一条记录,下面的代码能执行,无错 61 // $username = 'leaves'; 62 // $password = 's&^*&B324'; 63 // $mark = '我是好人'; 64 // $pstmt = $dbh->prepare ( 'INSERT INTO TUSER(USERNAME,PASSWORD,MARK) VALUES(:username,:password,:mark)' ); 65 // $pstmt->bindParam ( ':username', $username ); 66 // $pstmt->bindParam ( ':password', $password ); 67 // $pstmt->bindParam ( ':mark', $mark ); 68 // $pstmt->execute (); 69 // print_r ( $pstmt->errorInfo () ); 70 ?> |
2022-08-15
2022-08-17
2022-11-06
2022-08-17
2022-07-18
请发表评论