[英]SQL query works in phpMyAdmin but not in php using PDO
I have a simple sql query that I would like to execute using PDO like so: 我有一个简单的SQL查询,想使用PDO执行,如下所示:
try {
//connect to server
$dbh = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME, DBUSER, DBPASS);
//check if username is valid
$q="SELECT COUNT(*), first FROM users WHERE email='".$_POST['email']."'";
echo $q;
$stmt=$dbh->prepare($q);
$stmt->execute();
$f=$stmt->fetch();
echo $f[0];
echo $f[1];
catch (PDOException $e) {
echo "There was an internal error resetting your password.";
die();
}
The output for echo $q is to following: echo $ q的输出如下:
SELECT COUNT(*) first FROM users WHERE email='ahg44@cornell.edu'
When I copy and paste this into the SQL tab of phpmyadmin the query successfully returns the tuple I am looking for. 当我将其复制并粘贴到phpmyadmin的SQL选项卡中时,查询成功返回了我要查找的元组。 However, it does not return anything in the php code.
但是,它不会在php代码中返回任何内容。
Additionally, when I call: $stmt->debugDumpParams(); 另外,当我打电话时:$ stmt-> debugDumpParams(); after the query, this is printed:
查询后,将输出:
SQL: [64] SELECT COUNT(*), first FROM users WHERE email='ahg44@cornell.edu' Params: 0
At first I thought it was an error with the reading the POST variable so I hard coded: 起初,我认为读取POST变量是错误的,因此我进行了硬编码:
$q="SELECT COUNT(*), first FROM users WHERE email='ahg44@cornell.edu'";
in place of the original query but this got me the same results. 代替原始查询,但这得到了相同的结果。
Additionally, if I change the query to something simple like: 另外,如果我将查询更改为简单的内容,例如:
$q="SELECT COUNT(*), first FROM users
the code works fine. 该代码工作正常。
The weird thing is the this query worked perfectly yesterday so I must have made a minor error while cleaning up my code today. 奇怪的是,该查询昨天完美地工作了,所以我今天在清理代码时一定犯了一个小错误。 I have a hunch the problem has something to do with escape characters but I've been searching online for a while and haven't found a solution.
我直觉这个问题与转义字符有关,但我已经在线搜索了一段时间,但没有找到解决方案。 thanks!
谢谢!
Although the PHP you pasted in your question looks correct, tt looks like you are actually missing a comma in the code that is executing.. 尽管您粘贴在问题中的PHP看起来正确,但是tt看起来您实际上在执行的代码中缺少逗号。
This line: 这行:
SQL: [64] SELECT COUNT(*) first FROM users WHERE email='ahg44@cornell.edu'
shows no comma after COUNT(*)
, so first
is becoming the alias for the COUNT(*)
column, rather than being selected as a separate column. 在
COUNT(*)
之后不显示逗号,因此first
成为COUNT(*)
列的别名,而不是被选择为单独的列。
You're using PDO incorrectly. 您使用的PDO错误。 You should be using prepared statements, like so:
您应该使用准备好的语句,如下所示:
$q = "SELECT COUNT(*), first FROM users WHERE email = ?";
$stmt = $dbh->prepare( $q);
$stmt->execute( array( $_POST['email']));
$f = $stmt->fetch();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.