php查询没有正确执行

时间:2012-03-29 23:46:00

标签: php

如何执行查询,其中一个参数没有周围的引号,如此 -

select * from table where column1 = 'value1' and column2 = value2 //value2 has no ''

现在,在php中使用像

这样的东西
query("select * from table where column1 = ? and column2 = ?",array($value1,$value2)

这是一个例子。并在sql中排除,如此

 select * from table where column1 = 'value1' and column2 = 'value2' //value2 has quotes, this is what i want to ignore / remove

怎么能在php中完成?

4 个答案:

答案 0 :(得分:1)

“”和“”都用于分隔字符串。

http://www.elated.com/articles/creating-php-strings/

P.S。阅读本文 - > http://en.wikipedia.org/wiki/SQL_injection

答案 1 :(得分:0)

怎么样:

query("select * from table where column1 = '?' and column2 = '?'"

可替换地:

query("select * from table where column1 = \"?\" and column2 = \"?\""

它不漂亮,但它有效。

答案 2 :(得分:0)

您可以使用PDO准备好的声明来做到这一点:

<?php
    $sth = $db->prepare('SELECT * FROM users WHERE username = ? AND pass = ?');
    $sth->execute(array('john', '1234'));
    $result = $sth->fetchAll();
?>

答案 3 :(得分:0)

这是一个可以使用的样板,其中还包括用于测试此场景的临时数据库设置。 try构造中的代码执行连接和查询的实际操作。

<?php

/**********************************************************
* CREATES THE SAMPLE DATABASE/TABLE/DATA
/*********************************************************/
/*********************************************************

CREATE DATABASE IF NOT EXISTS scratch
  CHARACTER SET = 'utf8' COLLATE = 'utf8_general_ci';

CREATE TABLE `scratch`.`table1` (
  `column1` varchar(40) NOT NULL DEFAULT '',
  `column2` varchar(40) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `scratch`.`table1` (`column1`, `column2`)
  VALUES ('test1', 'test2');

/*********************************************************/

// connection parameters
$hostname = '127.0.0.1';
$database = 'scratch';
$username = 'root';
$password = 'rootpass';

// connection parameters (mysql specific)
$connectionString  = "mysql:host=${hostname};dbname=${database}";
$connectionOptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');

// query bound parameters
$column1  = 'test1';
$column2  = 'test2';

// sql statement(s)
$sql      = 'SELECT
               `column1`, `column2`
             FROM
               table1
             WHERE
                   `column1` = :column1
               and `column2` = :column2;
';

// tl;dr
try {
  $pdo = new PDO($connectionString, $username, $password, $connectionOptions);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

  $statement = $pdo->prepare($sql);
  $statement->execute(compact('column1', 'column2'));
  $results   = $statement->fetchAll();

  var_dump($results);

  $pdo = $statement = null;
} catch(PDOException $e) {
  echo $e->getMessage();
}