· 10 years ago · Jun 15, 2016, 08:48 AM
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 (
17id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
18name VARCHAR(30) NOT NULL
19)" );
20
21try {
22 $con->query( "INSERT INTO MyGuests VALUES ( 8, 'name1' ), ( 9, 'name2' ), ( 10, 'name3' ) " );
23} catch ( Exception $e ){}
24
25
26echo "// Wrong Code Below --------------";
27
28$sth = $con->prepare('SELECT id
29 FROM MyGuests
30 WHERE id IN ( :id )');
31
32foreach( array( 8, 9 ) as $k => $v ){
33 $sth->bindValue( ':id', $v );
34}
35
36$sth->execute( );
37
38var_dump( $sth->fetchAll() );
39var_dump( $sth->rowCount() );
40
41
42echo "// 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
50var_dump( $sth->fetchAll() );
51var_dump( $sth->rowCount() );
52
53
54echo "// 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
68var_dump( $sth->fetchAll() );
69var_dump( $sth->rowCount() );
70
71
72echo "// 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
84foreach( $ids as $k => $v ){
85 $sth->bindValue( $k + 1, $v, PDO::PARAM_STR );
86}
87
88$sth->execute( );
89var_dump( $sth->fetchAll() );
90var_dump( $sth->rowCount() );