· 8 years ago · Jul 27, 2018, 12:28 PM
1php query not excuting correctly
2select * from table where column1 = 'value1' and column2 = value2 //value2 has no ''
3
4query("select * from table where column1 = ? and column2 = ?",array($value1,$value2)
5
6select * from table where column1 = 'value1' and column2 = 'value2' //value2 has quotes, this is what i want to ignore / remove
7
8<?php
9 $sth = $db->prepare('SELECT * FROM users WHERE username = ? AND pass = ?');
10 $sth->execute(array('john', '1234'));
11 $result = $sth->fetchAll();
12?>
13
14<?php
15
16/**********************************************************
17* CREATES THE SAMPLE DATABASE/TABLE/DATA
18/*********************************************************/
19/*********************************************************
20
21CREATE DATABASE IF NOT EXISTS scratch
22 CHARACTER SET = 'utf8' COLLATE = 'utf8_general_ci';
23
24CREATE TABLE `scratch`.`table1` (
25 `column1` varchar(40) NOT NULL DEFAULT '',
26 `column2` varchar(40) NOT NULL DEFAULT ''
27) ENGINE=InnoDB DEFAULT CHARSET=utf8;
28
29INSERT INTO `scratch`.`table1` (`column1`, `column2`)
30 VALUES ('test1', 'test2');
31
32/*********************************************************/
33
34// connection parameters
35$hostname = '127.0.0.1';
36$database = 'scratch';
37$username = 'root';
38$password = 'rootpass';
39
40// connection parameters (mysql specific)
41$connectionString = "mysql:host=${hostname};dbname=${database}";
42$connectionOptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
43
44// query bound parameters
45$column1 = 'test1';
46$column2 = 'test2';
47
48// sql statement(s)
49$sql = 'SELECT
50 `column1`, `column2`
51 FROM
52 table1
53 WHERE
54 `column1` = :column1
55 and `column2` = :column2;
56';
57
58// tl;dr
59try {
60 $pdo = new PDO($connectionString, $username, $password, $connectionOptions);
61 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
62 $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
63
64 $statement = $pdo->prepare($sql);
65 $statement->execute(compact('column1', 'column2'));
66 $results = $statement->fetchAll();
67
68 var_dump($results);
69
70 $pdo = $statement = null;
71} catch(PDOException $e) {
72 echo $e->getMessage();
73}