数据未插入数据库

时间:2014-07-13 14:39:09

标签: php mysql

嘿伙计们我正在使用这段代码,将数据从FORM插入我的数据库,但实际上它不起作用,我的代码看起来像:

<?php

class WebsiteUsers {
public $username = null;
public $email = null;
public $phone = null;
public $message = null;

public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['email'] ) ) $this->email = stripslashes( strip_tags( $data['email'] ) );
if( isset( $data['phone'] ) ) $this->phone = stripslashes( strip_tags( $data['phone'] ) );
if( isset( $data['message'] ) ) $this->message = stripslashes( strip_tags( $data['message'] ) );
}

public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}

public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";

$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->bindValue( "phone", $this->phone, PDO::PARAM_STR );
$stmt->bindValue( "message", $this->message, PDO::PARAM_STR );
$stmt->execute();

$valid = $stmt->fetchColumn();

if( $valid ) {
$success = true;
}

$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}

public function message() {
$correct = false;
try {
$con = new PDO( DB_HOST, DB_USER, DB_PASS );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO user(name, email, phone, message) VALUES(:name, :email, :phone, :message)";

$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "email", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "phone", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "message", $this->username, PDO::PARAM_STR );
$stmt->execute();
return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
}catch( PDOException $e ) {
return $e->getMessage();
}
}

}

?>

和我的index.php看起来像:

<?php if( !(isset( $_POST['send'] ) ) ) { ?>

HTML FORM

<?php 
} else {
    $WebsiteUsers = new WebsiteUsers();
    $WebsiteUsers->storeFormValues( $_POST );
    if( $WebsiteUsers->message() ) {
        echo "Sprava bola odoslana";    
    } else {
        echo "Sprava nebola odoslana";    
    }
}

?>

当我提交表格时,它说Sprava bola odoslana但它不输入任何东西到DB也不显示任何错误,有人可以帮我解决吗?

1 个答案:

答案 0 :(得分:0)

您的INSERT sql中有一个参数:name,但您的第一个$stmt->bindValue()username的绑定值。

除此之外,你不应该在另一个方法中调用构造函数。您的代码可能会运行两次。