I have file 'class_reg.php' that contains class 'Reg', and some methon 'registration' in it, it recive some input value and insert it into the database via PDO. And I have 'dbconfig.php' file, where I connect to database, include my 'class_reg.php' file and create object '$user'. And I have some 'registration.php' file where I include 'dbconfig.php' file and try to run my method 'registration' but it not work. So here my files:
<?php
class Reg{
public $db;
function __construct($con){
$this->db = $con; //$con содержит подключение к базе данных
}
public function registration($userName, $pass){
try{
$sql = $this->db->prepare("INSERT INTO WebsiteUsers ( userName, pass, fullName, email ) VALUES
( :userName, :pass )");
$sql->bindparam(":userName", $userName);
$sql->bindparam(":pass", $pass);
$sql->execute();
return $sql;
}
catch(PDOException $e){
echo "Error with data :". $e->getMessage();
}
}
public function redirect($url){
header("Location: $url");
}
}
?>
<?php
$user = 'root';
$pass = '8169x5it';
try{
$con = new PDO('mysql:host=localhost; dbname=reg_form', $user, $pass);
}catch (PDOException $e){
echo "POD Error :".$e->getMessage();
}
include_once 'class_reg.php';
$user = new Reg($con);
?>
<?php
require_once 'dbconfig.php';
if(isset($_POST['userName'])){
$form = $_POST;
//var_dump($_POST);
$userName = $form[ 'userName' ];
$pass = md5($form[ 'pass' ]);
if($user->registration($userName, $pass)){
$user->redirect("all_users.php");
}else{
echo "0";
}
}
?>
So, it redirect me to my file 'all_users.php' that display all users I insert to database but data not inserting to database. Could you tell me what I'm doing wrong in my code. Thank you in advance!
Most of your problems have been answered in comments, but I will try to summarize and note a few additional things.
The main problem is invalid SQL as noted in the comment above by @danronmoon You have a mismatch between number of columns specified and number of values provided. If you are not entering full name and email values, remove these column specifications from your insert.
You also have typo when trying to use bindParam()
as noted in comments.
The reason your see "proper" redirect behavior is two-fold:
I don't see where you have configured your PDO object instance to utilize Exception error mode, so no Exception is thrown when there is an error. Thus the Exception handler is not being triggered
Your return from the method should be:
return $sql->execute();
not
return $sql;
as $sql
is just your PDOStatement object (assuming that your fix other problem above and prepare
works properly).