Advertisement
Guest User

Untitled

a guest
Jun 15th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Ostico
  5. * Date: 12/02/16
  6. * Time: 11.18
  7. */
  8. $user = "admin";
  9. $pass = "admin";
  10. $host = "mysql";
  11. $db = "test";
  12. $con = new PDO( "mysql:host=" . $host , $user, $pass );
  13. $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  14. $con->query( "CREATE DATABASE IF NOT EXISTS test" );
  15. $con->query( "USE test" );
  16. $con->query( "CREATE TABLE IF NOT EXISTS MyGuests (
  17. id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  18. name VARCHAR(30) NOT NULL
  19. )" );
  20.  
  21. try {
  22. $con->query( "INSERT INTO MyGuests VALUES ( 8, 'name1' ), ( 9, 'name2' ), ( 10, 'name3' ) " );
  23. } catch ( Exception $e ){}
  24.  
  25.  
  26. echo "// Wrong Code Below --------------";
  27.  
  28. $sth = $con->prepare('SELECT id
  29. FROM MyGuests
  30. WHERE id IN ( :id )');
  31.  
  32. foreach( array( 8, 9 ) as $k => $v ){
  33. $sth->bindValue( ':id', $v );
  34. }
  35.  
  36. $sth->execute( );
  37.  
  38. var_dump( $sth->fetchAll() );
  39. var_dump( $sth->rowCount() );
  40.  
  41.  
  42. echo "// Wrong code Below -----------------";
  43.  
  44. $sth = $con->prepare('SELECT id
  45. FROM MyGuests
  46. WHERE id IN ( :id )');
  47.  
  48. $sth->execute( array( 'id' => implode( ", ", array( 8, 9 ) ) ) );
  49.  
  50. var_dump( $sth->fetchAll() );
  51. var_dump( $sth->rowCount() );
  52.  
  53.  
  54. echo "// Right code Below -----------------";
  55.  
  56. $ids = array( 8, 9 );
  57.  
  58. $place_holders = implode( ',', array_fill( 0, count($ids), '?' ) );
  59.  
  60. $sth = $con->prepare("
  61. SELECT id
  62. FROM MyGuests
  63. WHERE id IN ( $place_holders )
  64. ");
  65.  
  66. $sth->execute( array( 8, 9 ) );
  67.  
  68. var_dump( $sth->fetchAll() );
  69. var_dump( $sth->rowCount() );
  70.  
  71.  
  72. echo "// Right code Below -----------------";
  73.  
  74. $ids = array( 8, 9 );
  75.  
  76. $place_holders = implode( ',', array_fill( 0, count($ids), '?' ) );
  77.  
  78. $sth = $con->prepare("
  79. SELECT id
  80. FROM MyGuests
  81. WHERE id IN ( $place_holders )
  82. ");
  83.  
  84. foreach( $ids as $k => $v ){
  85. $sth->bindValue( $k + 1, $v, PDO::PARAM_STR );
  86. }
  87.  
  88. $sth->execute( );
  89. var_dump( $sth->fetchAll() );
  90. var_dump( $sth->rowCount() );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement