Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $host="localhost";
- $user="root";
- $password="";
- $dbname="pdopost";
- //Set DSN
- $dsn='mysql:host='.$host.';dbname='.$dbname;
- //Create a PDO instance
- $pdo=new PDO($dsn,$user,$password);
- $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ);
- $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
- #PDO QUERY
- //$stmt=$pdo->query('SELECT *from posts');
- // // while($row=$stmt->fetch(PDO::FETCH_ASSOC))
- // // {
- // // echo $row['title'].'<br>';
- // // }
- // while($row=$stmt->fetch())
- // {
- // echo json_encode($row);
- // //echo $row.'<br>';
- // }
- #PREPARED STATEMENTS (prepare & execute)
- //UNSAFE
- // $auther='grave keeper';
- // $id=1;
- // $limit=1;
- //Positional Params
- // $sql='SELECT *From posts WHERE auther=? LIMIT ?'; //LIMIT to one
- // $sql='SELECT *From posts WHERE auther=?';
- // //$sql='SELECT *From posts WHERE auther=? AND id=? ';
- // //$sql='SELECT *From posts WHERE auther=? OR id=? ';
- // $stmt=$pdo->prepare($sql);
- // $stmt->execute([$auther],[$limit]);
- // $stmt->execute([$auther]);
- // //$stmt->execute([$auther,$id]);
- // $posts=$stmt->fetchAll();
- // foreach($posts as $post)
- // {
- // echo json_encode($post);
- // }
- //Named Params
- // $sql='SELECT *From posts WHERE auther=:auther';
- // //$sql='SELECT *From posts WHERE auther=:auther AND id=:id ';
- // //$sql='SELECT *From posts WHERE auther=:auther OR id=:id ';
- // $stmt=$pdo->prepare($sql);
- // $stmt->execute(['auther'=>$auther]);
- // //$stmt->execute([$auther,$id]);
- // $posts=$stmt->fetchAll();
- // //$posts=$stmt->fetch(); --> one item only
- // foreach($posts as $post)
- // {
- // echo json_encode($post);
- // }
- // echo '<br>'.$stmt->rowCount();
- //INSERT DATA
- // $title='post 4';
- // $body='grave keeper post 4';
- // $auther='grave keeper';
- // $sql='INSERT INTO posts(title,body,auther) VALUES(:title,:body,:auther)';
- // $stmt=$pdo->prepare($sql);
- // $stmt->execute(['title'=>$title,'body'=>$body,'auther'=>$auther]);
- // echo "New post added";
- //UPDATE DATA
- // $body='grave keeper updated post 1';
- // $id=1;
- // $sql='UPDATE posts SET body=:body WHERE id=:id';
- // $stmt=$pdo->prepare($sql);
- // $stmt->execute(['body'=>$body,'id'=>$id]);
- // echo "post updated";
- // //DELETE DATA
- // $id=3;
- // $sql='DELETE FROM posts WHERE id=:id';
- // $stmt=$pdo->prepare($sql);
- // $stmt->execute(['id'=>$id]);
- // echo "post deleted";
- //SEARCH DATA
- $search='%keeper%';
- $sql='SELECT * FROM posts WHERE auther LIKE ?';
- $stmt=$pdo->prepare($sql);
- $stmt->execute([$search]);
- $posts=$stmt->fetchAll();
- foreach($posts as $post)
- {
- echo json_encode($post);
- }
- ?>
Add Comment
Please, Sign In to add comment