PHP使用PDO实现增删改查

时间:2019-09-04
本文章向大家介绍PHP使用PDO实现增删改查,主要包括PHP使用PDO实现增删改查使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。


/////php操作pdo实现查询

header( "Content-type: text/html; charset=utf-8" );
$dbms = 'mysql';
$user = 'root';
$pwd = '12345678';
$dbName = 'ceshi';
$host = 'localhost';
$charset = 'utf8';
$dsn = "$dbms:host=$host;dbname=$dbName;charset=$charset";
try {
$pdo = new PDO( $dsn, $user, $pwd );
} catch ( Exception $e ) {
echo $e->getMessage();
}

//查询
$sql = "select * from dunling_chat where id=? ";
//准备sql模板
$stmt = $pdo->prepare( $sql );
$id = '1';
//绑定参数
$stmt->bindValue( 1, $id );
//执行预处理语句
$stmt->execute();
//推荐这种方式来获取查询结果
while ( $row = $stmt->fetch() ) {
echo $row[ 'id' ] . "
";
echo $row[ 'nicheng' ] . "
";
echo $row[ 'content' ] . "
";
echo $row[ 'time' ] . "
";
}
//释放查询结果
$stmt = null;
//关闭连接
$pdo = null;

?>

?

?

?

/////php操作pdo实现更新
header( "Content-type: text/html; charset=utf-8" );
$dbms = 'mysql';
$user = 'root';
$pwd = '12345678';
$dbName = 'ceshi';
$host = 'localhost';
$charset = 'utf8';
$dsn = "$dbms:host=$host;dbname=$dbName;charset=$charset";
try {
$pdo = new PDO( $dsn, $user, $pwd );
} catch ( Exception $e ) {
echo $e->getMessage();
}

//更新
$sql = "update dunling_chat set nicheng=? where id=?";
//准备sql模板
$stmt = $pdo->prepare( $sql );
$name = 'one';
$age = 1;
//绑定参数
$stmt->bindValue( 1, $name );
$stmt->bindValue( 2, $age );
//执行预处理语句
$stmt->execute();
$affect_row = $stmt->rowCount();
if ( $affect_row ) {
echo '更新成功' . '
';
} else {
echo '更新失败' . '
';
}
//释放查询结果
$stmt = null;
//关闭连接
$pdo = null;

?>

?

?

////php操作pdo实现插入
$dbms = 'mysql';
$user = 'root';
$pwd = '12345678';
$dbName = 'ceshi';
$host = 'localhost';
$charset = 'utf8';
$dsn = "$dbms:host=$host;dbname=$dbName;charset=$charset";
try {
$pdo = new PDO( $dsn, $user, $pwd );
} catch ( Exception $e ) {
echo $e->getMessage();
}

//插入
$sql = "insert into dunling_chat(nicheng,content) values(?,?)";
//准备sql模板
$stmt = $pdo->prepare( $sql );
$nicheng = 'two';
$content = 000;
//绑定参数
$stmt->bindValue( 1, $nicheng );
$stmt->bindValue( 2, $content );
//执行预处理语句
$stmt->execute();
$insert_id = $pdo->lastInsertId();
if ( $insert_id ) {
echo '新增成功' . '
';
} else {
echo '新增失败' . '
';
}
//释放查询结果
$stmt = null;
//关闭连接
$pdo = null;

?>

?

?


////php操作pdo实现删除
header("Content-type: text/html; charset=utf-8");
$dbms = 'mysql';
$user = 'root';
$pwd = '12345678';
$dbName = 'ceshi';
$host = 'localhost';
$charset = 'utf8';
$dsn="$dbms:host=$host;dbname=$dbName;charset=$charset";
try{
$pdo=new PDO($dsn,$user,$pwd);
}
catch(Exception $e)
{
echo $e->getMessage();
}

//删除
$sql = "delete from dunling_chat where id=?";
//准备sql模板
$stmt = $pdo->prepare($sql);
$id = 11;
//绑定参数
$stmt->bindValue(1,$id);
//执行预处理语句
$stmt->execute();
$affect_row = $stmt->rowCount();
if($affect_row)
{
echo '删除成功'.'
';
}
else
{
echo '删除失败'.'
';
}
//释放查询结果
$stmt = null;
//关闭连接
$pdo = null;

?>

?

$flag 上一页 下一页