PHP:mysql数据库的条件

时间:2013-03-04 15:17:38

标签: php

我在PHP编码方面很新,我在下面的代码中找不到错误......你能帮帮我吗?

  

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

<?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)

感谢您的帮助

3 个答案:

答案 0 :(得分: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');
}

插入查询可能是错误的,取决于表模式

答案 1 :(得分:2)

if($mem['pseudo'] == $_POST['pseudo'])
    ^^^--- should be $data instead

但这是糟糕的代码。你基本上是买了一个杂货店的全部内容(你的members桌子),把它全部带回家,然后除了你想要的一块巧克力棒之外扔掉一切。您应该在DB中执行此操作,基本上是

SELECT * FROM members WHERE pseudo=...

答案 2 :(得分:0)

当您从if($mem['pseudo'] == $_POST['pseudo'])读取每一行if($data['pseudo'] == $_POST['pseudo'])时,

$mem应为$data。但是,这似乎不是做你想要做的事情的最佳选择 - 为什么不直接在数据库中搜索$_POST['pseudo']而不是循环遍历它们?