Advertisement
LrdArc

PHP - SQL Query | intip.in/pdo

Jan 5th, 2015
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.84 KB | None | 0 0
  1. <php
  2. // configuration
  3. $db_user = 'root';
  4. $db_pass = 'password';
  5. $db_name = 'namaDB';
  6.  
  7. // connect to database
  8. $dsn = 'mysql:dbname=' . $db_name . ';charset=utf8;host=localhost';
  9. try {
  10.         $dbh = new PDO( $dsn, $db_user, $db_pass );
  11. } catch ( PDOException $e ) {
  12.         echo 'Connection failed: ' . $e->getMessage();
  13. }
  14.  
  15.  
  16. // Fetch [single result]
  17. $sth = $dbh->prepare( "SELECT * FROM user WHERE user_id=?" );
  18. $sth->execute( array( $_SESSION['user_id'] ) );
  19. $f = $sth->fetch( PDO::FETCH_OBJ );
  20. echo $f->name;
  21.  
  22.  
  23. // Row [multiple result]
  24. $sth = $dbh->prepare( "SELECT * FROM movies WHERE genre=? AND year=?" );
  25. $sth->execute( array( $_GET['genre'], $_GET['year'] ) );
  26. while ( $f[] = $sth->fetch( PDO::FETCH_ASSOC ) );
  27. if ( empty( $f[count( $f ) - 1] ) ) unset( $f[count( $f ) - 1] );
  28. foreach ( $f as $r ) {
  29.     echo $r['title'];
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement