PDO insert trying to bind wrong number of params - php

I am having trouble figuring out where my insert (using pdo) is failing. I passed it 19 parameters via an array, and then bound 19 values from that same array.
It fails at the bind step with the following error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens'
I was wondering if you guys would be able to figure out why its failing. The code I am using is below:
addevent.php
if(isset($_POST['add_event'])){
$eventDetails = $_POST;
$event_code = htmlspecialchars($eventDetails['ecode']);
$event_title = htmlspecialchars($eventDetails['etitle']);
$location = htmlspecialchars($eventDetails['location']);
$start_date = htmlspecialchars($eventDetails['start_date']);
$end_date = htmlspecialchars($eventDetails['end_date']);
$super_early_date = htmlspecialchars($eventDetails['super_early_date']);
$early_date = htmlspecialchars($eventDetails['early_date']);
$tax_type = htmlspecialchars($eventDetails['tax_desc']);
$tax_rate = htmlspecialchars($eventDetails['tax_rate']);
$is_call_open = htmlspecialchars($eventDetails['is_call_open']);
$domain_name = htmlspecialchars($eventDetails['domain']);
$sold_out_msg = htmlspecialchars($eventDetails['sold_out_msg']);
$group_min = htmlspecialchars($eventDetails['group_discount_min']);
$group_num = htmlspecialchars($eventDetails['group_discount_per']);
//errors array that will be passed to view if there are errors;
$errors = array();
//if there are contents in the error array from previous execution empty error
if(!empty($errors)){ unset($errors); }
//if any of these fields are empty add them to the array
if(empty($event_code)) { array_push($errors, ucwords('event code is required')); }
if(empty($event_title)) { array_push($errors, ucwords('event title is required')); }
if(empty($location)) { array_push($errors, ucwords('location is required')); }
if(empty($start_date)) { array_push($errors, ucwords('start date is required')); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/',$start_date) == 0) { array_push($errors, ucwords('incorrect format for start date, it should be').' yyyy-mm-dd'); }
if(empty($end_date)) { array_push($errors, ucwords('end date is required')); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $end_date) == 0) { array_push($errors, ucwords('incorrect format for end date, it should be').' yyyy-mm-dd'); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $super_early_date) == 0) { array_push($errors, ucwords('incorrect format for super early bird date, it should be').' yyyy-mm-dd'); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $early_date) == 0) { array_push($errors, ucwords('incorrect format for early bird date, it should be').' yyyy-mm-dd'); }
if($tax_type == 'none') { array_push($errors, ucwords('tax type is required')); }
if(empty($tax_rate)) { array_push($errors, ucwords('tax rate is required')); }
if(empty($domain_name)) { array_push($errors, ucwords('domain name is required')); }
if(preg_match('/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/', $domain_name) == 0) { array_push($errors, ucwords('domain name is not valid')); }
if(empty($sold_out_msg)) { array_push($errors, ucwords('sold out message is required')); }
if(!empty($group_min) && empty($group_num)) { array_push($errors, ucwords('group discount (percent) is required')); }
if(!empty($errors)){
$this->set('errors', $errors);
}
else{
//remove the add_event button from the event
$add_event_index = array_pop($eventDetails);
$keys = array_keys($eventDetails);
$addEvent = "INSERT INTO v_events (" . implode(",", $keys) . ") VALUES (";
for($i = 0; $i < sizeof($eventDetails); $i+=1){
if($i == 0) { $addEvent .= "?"; }
else { $addEvent .= ",?"; }
}
$addEvent .= ")";
$success = $this->Cms->query($addEvent, $eventDetails);
if(!$success){
print_r($this->Cms->getError());
}
$this->set('success', ucwords('event succcesfully added!'));
}
}
$this->Cms->query function:
public function query($query, $attributes = array(), $singleResult = 0) {
echo $query;
$stmt = $this->dbc->prepare($query);
if(!empty($attributes)){
echo'<pre>';
print_r($attributes);
echo'</pre>';
foreach($attributes as $values){
if(empty($values) || $values) { $values = 'not provided'; }
if($values == NULL) { $values = '0'; }
echo $stmt->bindParam('?', $values);
echo'<pre>';
$stmt->debugDumpParams();
echo'</pre>';
}
}
$success = $stmt->execute();
return $success;
}

Related

How can I define a variable inside a function?

how I can define a variable inside a PHP function and make it reachable from another function? I want to set $error variable to "1".
This how would the code look like:
function checkthename ($name){
if ($name == "TESTTEST"){
echo $error = 0;
}
else {
echo $error = 1;
}
}
function phone ($phone){
if ($name == "TESTTEST"){
echo $error = 0;
}
else {
echo $error = 1;
}
}
etc.
And in end of the code there would be an another function which is checking if there is any $error variable set to 1
function checktheerror($error){
if ($error == 0){
echo "no error in this code";
}
elseif ($error == 1){
echo "there is one or multiple errors";
}
}
Thank you so much for your help!

I need help in form validations of php its complex

I am having problem in form validations the error im getting is something like this
Fatal error: Uncaught Error: Unsupported operand types in C:\xampp\htdocs\LSR\signup.php:22 Stack trace: #0 {main} thrown in C:\xampp\htdocs\LSR\signup.php on line 22
function check_empty_fields($required_fields_array){
$form_errors = array();
foreach($required_fields_array as $name_of_field){
if (!isset($_POST[$name_of_field]) || $_POST[$name_of_field] == NULL) {
$form_errors[] = $name_of_field . "Is a REQUIRED FIELD";
}
}
return $form_errors;
}
function check_min_length($fields_to_check_length){
$form_errors = array();
foreach($fields_to_check_length as $name_of_field => $minimum_length_required){
if(strlen(trim($_POST[$name_of_field])) < $minimum_length_required){
$form_errors[] = $name_of_field . "Is too short must be {$minimum_length_required} characters long";
}
}
return $form_errors;
}
function check_email($data){
$form_errors = array();
$key = "email";
if(array_key_exists($key, $data)){
if($_POST[$key] != null){
$key = filter_var($key, FILTER_SANITIZE_EMAIL);
if (filter_var($_POST[$key], FILTER_VALIDATE_EMAIL) === false) {
$form_errors[] = $key . "is not a valid email address";
}
}
}
return $form_errors;
}
function show_errors($form_errors_array){
$errors .= "<p><ul style='color: red;'>";
foreach($form_errors_array as $the_error){
$errors .="<li>{$the_error}</li>";
}
$errors .= "</ul></p>";
return $errors;
}
Try on http://sandbox.onlinephpfunctions.com/code/c36fd6eb9b3a8e555364d99dd90cd9281100c884
<?php
function check_empty_fields($required_fields_array)
{
if (!is_array($required_fields_array)) {
return array();
}
$form_errors = array();
foreach ($required_fields_array as $name_of_field) {
if (empty($_POST[$name_of_field])) {
$form_errors[] = "'$name_of_field' is a REQUIRED FIELD";
}
}
return $form_errors;
}
function check_min_length($fields_to_check_length)
{
if (!is_array($fields_to_check_length)) {
return array();
}
$form_errors = array();
foreach ($fields_to_check_length as $name_of_field => $minimum_length_required) {
if (isset($_POST[$name_of_field]) && strlen(trim($_POST[$name_of_field])) < $minimum_length_required) {
$form_errors[] ="'{$name_of_field}' is too short must be '{$minimum_length_required}' characters long";
}
}
return $form_errors;
}
function check_email($fields_to_check_email = array('email'))
{
if (!is_array($fields_to_check_email)) {
return array();
}
$form_errors = array();
foreach ($fields_to_check_email as $name_of_field) {
if (isset($_POST[$name_of_field]) && !filter_var($_POST[$name_of_field], FILTER_VALIDATE_EMAIL)) {
$form_errors[] = "'{$name_of_field}' is not a valid email address";
}
}
return $form_errors;
}
function show_errors($form_errors_array)
{
$errors = '';
$errors .= "<p><ul style='color: red;'>";
foreach ($form_errors_array as $the_error) {
$errors .= "<li>{$the_error}</li>";
}
$errors .= "</ul></p>";
return $errors;
}
// Tests...
$_POST = array(
'name' => 'Test',
'null_name' => null,
'empty_name' => '',
'email' => 'test#mail.com',
'invalid_email' => 'test##mail.com',
);
$empty_errors = array();
$empty_errors = check_empty_fields(array('name', 'null_name', 'empty_name', 'undefined_name'));
echo 'Empty errors:', show_errors($empty_errors), "\n";
$min_length_errors = array();
$min_length_errors = check_min_length(array('name' => 4, 'empty_name' => 4));
echo 'Min length errors:', show_errors($min_length_errors), "\n";
$email_errors = array();
$email_errors = check_email(array('email', 'invalid_email'));
echo 'Email errors:', show_errors($email_errors), "\n";

PHP - Avoiding nested if statements - cleaner way to code this

Assume that I am creating a registration form. I have code like the below and it is hard to manage because of all the nested if statements.
I want to know the cleanest and easiest to follow way to write code that functions similarly to what I have below.
EDIT: People have told me that I can move the empty($_POST['email']) to the validation functions. I can't do that because I need to know 1) whether user has posted data or not, and 2) whether the data user posted is valid.
For example, when the user first goes to the registration page, they have not posted any data so $_POST['email'] will generate PHP warnings because they don't exist. That's why I check whether data has been posted before I validate.
Does this make sense?
function validate_email($str) {
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
function validate_password($str) {
$str = trim($str);
if(strlen($str) < 5 || strlen($str) > 70) {
return false;
} else {
return $str;
}
}
$email = false;
$password = false;
$errorMessage = false;
if(!empty($_POST['email'])) {
$email = validate_email($_POST['email']);
if($email) {
if(!empty($_POST['password'])) {
$password = validate_password($_POST['password']);
if($password) {
createNewUser($email,$password);
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "Email address is invalid";
}
} else {
$errorMessage = "Email address is invalid";
}
if($errorMessage) echo $errorMessage;
Whenever you have nested if()s you can flip the logic "inside out":
if (A)
if (B)
if (C)
final()
change to:
if (!A) return
if (!B) return
if (!C) return
final()
In your case instead of returning you could throw an exception.
try {
validateAndCreateNewUser();
}
catch(ValidationError $e) {
display($e->getMessage());
}
You don't need the empty checks at that point, move them to the validation functions.
For example:
function validate_email($str) {
if(empty($str)) {
return false;
}
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
$email = validate_email($_POST['email']);
if($email) {
// your code
}
This is a bit cleaner:
function validate_email($str) {
if (empty($str)) return false;
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
function validate_password($str) {
if (empty($str)) return false;
$str = trim($str);
if(strlen($str) < 5 || strlen($str) > 70) {
return false;
} else {
return $str;
}
}
$email = false;
$password = false;
$errorMessage = false;
$email = validate_email($_POST['email']);
if($email) {
$password = validate_password($_POST['password']);
if($password) {
createNewUser($email,$password);
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "Email address is invalid";
}
if($errorMessage) echo $errorMessage;

php birthday validation function

I am trying to add a birthday validation function in my php script to make sure users are 18+. But I am stuck on how to add it in my if statement.
This is what is taken from the input fields:
$ydob = ($_POST['ydob']);
$mdob =($_POST['mdob']);
$ddob = ($_POST['ddob']);
$dob = $ddob."-".$mdob."-".$ydob;
The function:
function validateDOB($dob){
list($ydob,$mdob,$ddob) = explode("-",$dob);
$year_diff = date("Y") - $ydob;
$month_diff = date("m") - $mdob;
$day_diff = date("d") - $ddob;
if ($day_diff < 0 || $month_diff < 0) {
$year_diff--;
return $year_diff;
} }
This block is to check if all details are entered correctly. So my question is how would I add the function here to validate if the user is over 18.
if((!$username) || (!$country) || (!$dob) || (!$email) || (!$password)){
$error_message = "You did not submit the following required information!<br /><br />";
if(!$username){
$error_message .= "Enter a User Name";
} else if(!$country){
$error_message .= "Enter a Country";
} else if(!$dob){
$error_message .= "Enter a D.O.B";
} else if(!$email){
$error_message .= "Enter a Email Address";
} else if(!$password){
$error_message .= "Enter a Password";
}
} else {
....}
Thank you so much.
Ray
There's a much easier way to do it:
function validateDOB($date)
{
$minAge=strtotime("-18 YEAR");
$entrantAge= strtotime($date);
if ($entrantAge < $minAge)
{
return false;
}
return true;
}
And then:
if(validateDOB($date))
{
echo "Welcome";
}
else
{
echo "Sorry, you are too young";
}
EDIT: To convert your date from European date format to MySQL format, you can do this:
$ymd = DateTime::createFromFormat('d-m-Y', $dmy)->format('Y-m-d');
You can do that before you pass it through to the function, or you could do it inside the function. Up to you.
You have to add in your else statement:
else {
if(validateDOB($dob) <18)
{
$error_message .= "Not old enough<br />";
}
}
$date = '2010-11-05 18:55:21';
if (strtotime($date) !== false)
{
...
}
This Function returns True only if it is a valid date (also leap year) and also throw FALSE if it is not meeting your Application's minimum age requirement. Find Me On Best Social Network Fun n Enjoy ( http://www.myfne.com/ravinder )
function checkDOB($minage="-18 YEAR")
{
if(checkdate( $_POST["dob_month"] , $_POST["dob_day"] , $_POST["dob_year"])==TRUE){
return true;
}
$date=$_POST["dob_month"]."-".$_POST["dob_day"]."-".$_POST["dob_year"];
$minAge=strtotime($minage);
$entrantAge= strtotime($date);
if ($entrantAge > $minAge)
{
return true;
}
return false;
}

help with array

What am i doing wrong here? The username string is less than 2 chars but it still dont set error[]?
Register:
$errors = array();
$username = "l";
validate_username($username);
if (empty($errors)) {
echo "nothing wrong here, inserting...";
}
if (!empty($errors)) {
foreach ($errors as $cur_error)
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
function validate_username($username) {
$errors = array();
if (strlen($username) < 2)
$errors[] = "Username too short";
else if (strlen($username) > 25)
$errors[] = "Username too long";
return $errors;
}
It's because you are not assigning the return value of validate_username() to any variable.
Try
$errors = validate_username($username);
Change validate_username($username); to $errors = validate_username($username);
Your function is affecting a local variable named errors, not the global errors that you may have been expecting.
Further, your code can be cleaned up a little bit as follows
$username = "l";
$errors = validate_username($username);
// No errors
if ( empty($errors) ) {
echo "nothing wrong here, inserting...";
}
// Errors are present
else {
foreach ( $errors as $cur_error ) {
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
}
function validate_username($username) {
$errors = array();
$len = strlen($username);
if ( $len < 2 ) {
$errors[] = "Username too short";
} elseif ( $len > 25 ) {
$errors[] = "Username too long";
}
return $errors;
}
you're not returning it the right way, you need:
$errors = validate_username($username)
you forgot to assign $errors
$errors = validate_username($username);
**//TRY THIS INSTEAD**
$errors = array();
$username = "l";
**$errors = validate_username($username);**
if (empty($errors)) {
echo "nothing wrong here, inserting...";
}
if (!empty($errors)) {
foreach ($errors as $cur_error)
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
function validate_username($username) {
$errors = array();
if (strlen($username) < 2)
$errors[] = "Username too short";
else if (strlen($username) > 25)
$errors[] = "Username too long";
return $errors;
}

Categories