摘要:exec():执行一条sql语句,并返回其受影响的记录,如果没有受影响的记录则返回0。【注意:exec()对select查询语句没有作用】
1、exec创建数据表
<?php try{ $pdo=new PDO('mysql:host=localhost;dbname=test','root','root'); $sql=<<<EOF CREATE TABLE IF NOT EXISTS test_pdo( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, username CHAR(16) NOT NULL UNIQUE, password CHAR(32) NOT NULL, email VARCHAR(32) NOT NULL ); EOF; $res=$pdo->exec($sql); var_dump($res); }catch(PDOException $e){ echo $e->getMessage(); }
2、exec执行插入insert语句
<?php try{ $pdo=new PDO('mysql:host=localhost;dbname=test','root','root'); $sql='INSERT test_pdo(username,password,email) VALUES ("testuser","'.md5('123456').'","testuser@qq.com")'; $res=$pdo->exec($sql); echo $res; }catch(PDOException $e){ echo $e->getMessage(); }
3、exec执行多条数据插入
<?php
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
$sql='INSERT test_pdo(username,password,email)
VALUES
("testuser1","'.md5('123456').'","testuser1@qq.com"),
("testuser2","'.md5('123456').'","testuser2@qq.com"),
("testuser3","'.md5('123456').'","testuser3@qq.com")';
$res=$pdo->exec($sql);
echo '受影响的记录的条数为:'.$res;
}catch(PDOException $e){
echo $e->getMessage();
}
4、exec获取最后插入数据的ID号
<?php try{ $pdo=new PDO('mysql:host=localhost;dbname=test','root','root'); $sql='INSERT test_pdo(username,password,email) VALUES ("testuser4","'.md5('123456').'","testuser4@qq.com")'; $res=$pdo->exec($sql); echo '受影响的记录的条数为:'.$res.'<br>'; echo '最后插入的ID号为'.$pdo->lastInsertId(); }catch(PDOException $e){ echo $e->getMessage(); }
5、exec执行update语句
<?php try{ $pdo=new PDO('mysql:host=localhost;dbname=test','root','root'); $sql='update test_pdo set username="update_name" where id=1'; $res=$pdo->exec($sql); echo '受影响的记录的条数为:'.$res; }catch(PDOException $e){ echo $e->getMessage(); }
6、exec执行delete语句
<?php try{ $pdo=new PDO('mysql:host=localhost;dbname=test','root','root'); $sql='delete from test_pdo where id=1'; $res=$pdo->exec($sql); echo '受影响的记录的条数为:'.$res; }catch(PDOException $e){ echo $e->getMessage(); }