使用pdo将表单值插入mysql数据库

时间:2015-06-04 09:32:19

标签: php mysql pdo

您好我将我的mysql查询更改为pdo。现在的问题是我没有任何pdo经验。我编辑它是如何思考但没有任何作用。没有错误显示。谁能找到错误?谢谢你的阅读。

    <?php
     session_start();

    if(isset($_POST["submit"])){

    $hostname='localhost';
    $username='root';
    $password='';


function generateRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
$randomString = generateRandomString();


         if ($_POST['password'] != $_POST['password_again']) {
            $message['error'] = 'Die eingegebenen Passwörter stimmen nicht überein.';
        } else {
            unset($_POST['password_again']);
            $salt = ''; 
            for ($i = 0; $i < 22; $i++) { 
                $salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1); 
            }
            $_POST['password'] = crypt(
                $_POST['password'],
                '$2a$10$' . $salt
            );

            try {
            $dbh = new PDO("mysql:host=$hostname;dbname=loginsystem",$username,$password);

            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
            $sql = "INSERT INTO user2 (username, password, email, firstname, lastname, phone, town, street, zip, country, code)
            VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."','".$_POST["firstname"]."','".$_POST["lastname"]."','".$_POST["phone"]."','".$_POST["town"]."','".$_POST["street"]."','".$_POST["zip"]."','".$_POST["country"]."','".$_POST[$randomString]."')";
            if ($dbh->query($sql)) {
            echo "New Record Inserted Successfully";
            }
            else{
            echo "Data not successfully Inserted.";
            }

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

            $new = rowCount();
            if ($new == 1) {
                $message['success'] = 'Neuer Benutzer (' . htmlspecialchars($_POST['f']['username']) . ') wurde angelegt, <a href="login.php">weiter zur Anmeldung</a>.';
                header('Location: http://' . $_SERVER['HTTP_HOST'] . '//activation.php');

                // $empfaenger = $_POST['f']['email'];
                // $betreff = "Registration";
                // $from = "From: Webmaster <webmaster@somediashout.de>";
                // $text = "Thank you for your registration. Your code is : " + $randomString;

                // mail($empfaenger, $betreff, $text, $from);



                    $_SESSION = array(
                        'login' => true,
                        'user'  => array(
                            'username'  => $row['username']
                        )
                    );

            } else {

            }

        }
    } 
?>

3 个答案:

答案 0 :(得分:1)

brabus85,

我将代码$new = rowCount()替换为$new = $dbh->rowCount()。同样剪切此代码并粘贴到$dbh = null行之前,我必须用0初始化$ new,所以在try{}语句之前写一下。

请使用以下代码,让我知道您的所见。

<?php
session_start();
// Report all errors
error_reporting(E_ALL);

if(isset($_POST["submit"])){

        $hostname='localhost';
        $username='root';
        $password='';


        function generateRandomString($length = 8) {
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $charactersLength = strlen($characters);
                $randomString = '';
                for ($i = 0; $i < $length; $i++) {
                        $randomString .= $characters[rand(0, $charactersLength - 1)];
                }
                return $randomString;
        }
        $randomString = generateRandomString();


        if ($_POST['password'] != $_POST['password_again']) {
                $message['error'] = 'Die eingegebenen Passwörter stimmen nicht überein.';
        } 
        else {
                unset($_POST['password_again']);
                $salt = ''; 
                for ($i = 0; $i < 22; $i++) { 
                        $salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1); 
                }
                $_POST['password'] = crypt(
                                                                $_POST['password'],
                                                                '$2a$10$' . $salt
                                                                );
                $new = 0;
                try {
                        $dbh = new PDO("mysql:host=$hostname;dbname=loginsystem",$username,$password);

                        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
                        $sql = "INSERT INTO user2 (username, password, email, firstname, lastname, phone, town, street, zip, country, code)
                        VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."','".$_POST["firstname"]."','".$_POST["lastname"]."','".$_POST["phone"]."','".$_POST["town"]."','".$_POST["street"]."','".$_POST["zip"]."','".$_POST["country"]."','".$_POST[$randomString]."')";
                        if ($dbh->query($sql)) {
                                echo "New Record Inserted Successfully";
                        }
                        else{
                                echo "Data not successfully Inserted.";
                        }
                        $new = $dbh->rowCount();
                        $dbh = null;
                }
                catch(PDOException $e)
                {
                        echo $e->getMessage();
                }


                if ($new == 1) {
                        $message['success'] = 'Neuer Benutzer (' . htmlspecialchars($_POST['f']['username']) . ') wurde angelegt, <a href="login.php">weiter zur Anmeldung</a>.';
                        //header('Location: http://' . $_SERVER['HTTP_HOST'] . '//activation.php');

                        // $empfaenger = $_POST['f']['email'];
                        // $betreff = "Registration";
                        // $from = "From: Webmaster <webmaster@somediashout.de>";
                        // $text = "Thank you for your registration. Your code is : " + $randomString;

                        // mail($empfaenger, $betreff, $text, $from);



                        $_SESSION = array(
                                'login' => true,
                                'user'  => array(
                                        'username'  => $row['username']
                                 ));
                } else {

                }
        }
}

print('<pre> Message :: ');
print_r($message);
print('</pre>');

print('<pre> POST values from submitted form :: ');
print_r($_POST);
print('</pre>');

print('<pre> ACTIVE SESSION :: ');
print_r($_SESSION);
print('</pre>');

?>

检查数组格式的措辞:

  1. 消息
  2. 提交表单中的POST值
  3. ACTIVE SESSION
  4. 希望您能够很好地理解,并让我从这个解决方案中了解更多信息。

    谢谢!

答案 1 :(得分:1)

brabus85,

第一个答案检查是否存在任何错误。请在第一个答案时替换以下代码。

此代码包含您问题的完整解决方案。

<?php
session_start();

if(isset($_POST["submit"])){

        $hostname='localhost';
        $username='root';
        $password='';


        function generateRandomString($length = 8) {
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $charactersLength = strlen($characters);
                $randomString = '';
                for ($i = 0; $i < $length; $i++) {
                        $randomString .= $characters[rand(0, $charactersLength - 1)];
                }
                return $randomString;
        }
        $randomString = generateRandomString();


        if ($_POST['password'] != $_POST['password_again']) {
                $message['error'] = 'Die eingegebenen Passwörter stimmen nicht überein.';
        } 
        else {
                unset($_POST['password_again']);
                $salt = ''; 
                for ($i = 0; $i < 22; $i++) { 
                        $salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1); 
                }
                $_POST['password'] = crypt(
                                                                $_POST['password'],
                                                                '$2a$10$' . $salt
                                                                );
                $new = 0;
                try {
                        $dbh = new PDO("mysql:host=$hostname;dbname=loginsystem",$username,$password);

                        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
                        $sql = "INSERT INTO user2 (username, password, email, firstname, lastname, phone, town, street, zip, country, code)
                        VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."','".$_POST["firstname"]."','".$_POST["lastname"]."','".$_POST["phone"]."','".$_POST["town"]."','".$_POST["street"]."','".$_POST["zip"]."','".$_POST["country"]."','".$randomString."')";

                        if ($dbh->query($sql)) {
                                echo "New Record Inserted Successfully";
                        }
                        else{
                                echo "Data not successfully Inserted.";
                        }
                        $new = $dbh->lastInsertId();
                        $dbh = null;
                }
                catch(PDOException $e)
                {
                        echo $e->getMessage();
                }


                if ($new > 0) {
                        $message['success'] = 'Neuer Benutzer (' . htmlspecialchars($_POST['f']['username']) . ') wurde angelegt, <a href="login.php">weiter zur Anmeldung</a>.';
                        header('Location: http://' . $_SERVER['HTTP_HOST'] . '//activation.php');

                        // $empfaenger = $_POST['f']['email'];
                        // $betreff = "Registration";
                        // $from = "From: Webmaster <webmaster@somediashout.de>";
                        // $text = "Thank you for your registration. Your code is : " + $randomString;

                        // mail($empfaenger, $betreff, $text, $from);



                        $_SESSION = array(
                                'login' => true,
                                'user'  => array(
                                        'username'  => $row['username']
                                 ));
                } else {

                }
        }
}
?>

如果您对此有任何疑问或疑虑,请与我们联系。

谢谢!

答案 2 :(得分:0)

尝试使用此代替$dbh->query()

$sth=$dbh->prepare($sql);
$sth->execute();