我正在尝试从旧的MySQL库转换为PDO。
为了使用旧的MySQL代码读取数据,我使用:
$ assoc = mysql_fetch_assoc($ exeqr);
使用PDO,我试图用foreach
像我在我的代码上使用PDO一样,但是它没有用......
你能看到错在哪里吗?
我的OLD ode使用MySQL:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$query = "SELECT * FROM users where email= '$autEmail'";
$exeqr = mysql_query($query) or die(mysql_error());
$assoc = mysql_fetch_assoc($exeqr);
if(mysql_num_rows($exeqr) == 1 )
{
if($autEmail == $assoc['email'] && $autpass == $assoc['pass'])
{
$_SESSION['assoc'] = $assoc;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
我尝试使用PDO转换的新代码:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$searchEmail = $pdo->prepare("SELECT * FROM users where email=:email");
$searchEmail->bindValue(":email,$autEmail");
$searchEmail->execute;
$num_rows = $searchEmail->fetchColumn();
$result = $searchEmail->fetch(PDO::FETCH_OBJ);
if($num_rows == 1)
{
if($autEmail == $result['email'] && $autpass == $result['pass'])
{
$_SESSION['result'] = $result;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
答案 0 :(得分:3)
警告:PDOStatement :: bindValue()需要至少2个参数,1在$ searchEmail-&gt; bindValue(&#34;:email,$ autEmail&#34;)中给出;
您需要移动"
,目前它包括变量以及参数名称,导致您没有传入变量以绑定到所述参数(这就是为什么你得到的错误告诉你你没有通过足够的论据。)
$searchEmail = $pdo->prepare("SELECT * FROM users where email = :email");
$searchEmail->bindValue(":email", $autEmail);
注意:未定义的属性:PDOStatement :: $ execute in $ searchEmail-&gt; execute;
您已忘记()
中的execute()
括号,因此PHP正在寻找名为execute
的PDO类的属性,而不是函数调用。
$searchEmail->execute();
(感谢Prix)
修改强>
您现在的问题是如何替换它:
$assoc = mysql_fetch_assoc($exeqr);
...与PDO等效。 In the manual, there is an example:
$assoc = $searchEmail->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
注意: fetchAll()
用于获取多个结果。如果您只期望一个结果(您可能会这样,但是您不限制查询,以便返回多个结果),那么您应该只使用fetch()
:< / p>
$assoc = $searchEmail->fetch(PDO::FETCH_ASSOC);