0

我是 PHP 编码的新手,我在以下代码中找不到错误...你能帮帮我吗?

致命错误:不能在 C:\wamp\www\membre\inscription_post.php 第 14 行调用堆栈 # 时间记忆函数位置 1 0.0006 682688 {main}( ) ..\inscription_post.php:0 中使用 PDOStatement 类型的对象作为数组

<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$mem = $bdd -> query('SELECT * FROM membres');

while ($data = $mem -> fetch())
{
    if($mem['pseudo'] == $_POST['pseudo'])
    {
        echo "Pseudo existant";
    }
    else
    {
        $pass_hache = sha1($_POST['pass']);
        $req = $bdd->prepare('INSERT INTO membres (pseudo, pass, email, date_inscription) VALUES(?, ?, ?, CURDATE())');
        $req->execute(array($_POST['pseudo'], $pass_hache, $_POST['email']));
        header('Location: inscription.php');
        echo "Membre ajouté";
    }
}
$mem -> closeCursor();

?>

membres表结构如下

id(=INT, primary key), 
pseudo (VARCHAR(255)), 
pass (VARCHAR(255)), 
date_inscription (date)

感谢您的帮助

4

3 回答 3

2

像这样的东西

<?php
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$bdd = new PDO($dsn,'root','', $opt);

$stm = $bdd->prepare('SELECT 1 FROM membres WHERE pseudo=?');
$stm->execute(array($_POST['pseudo']));
$row = $stm->fetch();
if ($row) {
    echo "Pseudo existant";
} else {
    $pass_hache = sha1($_POST['pass']);
    $sql = 'INSERT INTO membres VALUES(NULL, ?, ?, ?, CURDATE())';
    $req = $bdd->prepare($sql);
    $req->execute(array($_POST['pseudo'], $pass_hache, $_POST['email']));
    header('Location: inscription.php');
}

插入查询可能是错误的,取决于表架构

于 2013-03-04T15:20:28.357 回答
2
if($mem['pseudo'] == $_POST['pseudo'])
    ^^^--- should be $data instead

但这是糟糕的代码。您基本上是在购买杂货店(您的members桌子)的全部内容,将其全部带回家,然后扔掉所有东西,除了您想要的一根巧克力棒。本质上,您应该在数据库中执行此操作

SELECT * FROM members WHERE pseudo=...
于 2013-03-04T15:22:54.330 回答
0

if($mem['pseudo'] == $_POST['pseudo'])应该if($data['pseudo'] == $_POST['pseudo'])像您从 as 中读取每一行$mem一样$data。然而,这似乎不是做你想做的事情的最佳选择——为什么不$_POST['pseudo']直接在数据库中搜索而不是遍历它们呢?

于 2013-03-04T15:21:05.223 回答