I am creating a user settings page allowing members to update their information. The information displays, however once changed doesn't update on the database, although no errors are produced and the success page is displayed. I have tried echoing the array and it appears to be blank meaning it's not parsing any of the new data.
<?php
include ("storescripts/init.php");
protect_page();
if (empty($_POST) === false) {
$required_fields = array('mem_email','mem_first_name','mem_last_name');
foreach ($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) == true) {
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
if (empty($errors) === true) {
if (filter_var($_POST['mem_email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'A valid email address is required';
} else if(user_exists($_POST['mem_email']) === 1 && $member_data['mem_email'] !== $_POST['mem_email']) {
$errors[] = 'Sorry, the email \'' . htmlentities($_POST['mem_email']) . '\' is already in use';
}
}
}
if (empty($_POST) === false && empty($errors) === true) {
$update_data = array(
'mem_first_name' => $_POST['mem_first_name'],
'mem_last_name' => $_POST['mem_last_name'],
'mem_email' => $_POST['mem_email'],
'allow_email' => ($_POST['allow_email']) ? 1 : 0);
update_user($session_member_id, $update_data);
header('Location: settings.php?success=1');
die();
}
include ("includes/overall/head.php");
?>
<?php include ("includes/overall/template_header.php");?>
<div id="mainDivShort">
<h1>User Settings</h1>
<div id="divBreak"></div>
<?php include ("includes/overall/column_left.php");?>
<div id="middleContent">
<?php if (isset($_GET['success']) && isset($_GET['success'])) {
echo 'Your details have been updated';
} else {
if (empty($errors) === false) {
echo output_errors($errors);
}?>
<form action="" method="post">
<ul>
<li>First Name*: <br> <input type="text" name="mem_first_name"
value="<?php echo $member_data['mem_first_name'];?>">
</li>
<li>Last Name*: <br> <input type="text" name="mem_last_name"
value="<?php echo $member_data['mem_last_name'];?>">
</li>
<li>Email*: <br> <input type="text" name="mem_email"
value="<?php echo $member_data['mem_email'];? >">
</li>
<li>
<input type="checkbox" name="allow_email" <? php if ($member_data['allow_email'] == 1) { echo 'checked="checked"'; } ?>> Would you like to receive an email about news and promotions?
</li>
<li><input type="submit" value="Update">
</li>
</ul>
</form>
<?php }?>
</div>
<?php include ("includes/overall/column_right.php");?>
</div>
<?php include ("includes/overall/template_footer.php");?>
And my update_user function
function update_user($mem_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `members` SET " . implode(', ', $update) . " WHERE `mem_id`= $mem_id");
}
do you receive the correct data in your update_user function ?
try this
function update_user($mem_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
$sql = "UPDATE `members` SET " . implode(', ', $update) . " WHERE `mem_id`= $mem_id";
echo $sql; exit();
//mysql_query("UPDATE `members` SET " . implode(', ', $update) . " WHERE `mem_id`= $mem_id");
}
Fire this $sql output in your db to check if you have sql errors or any other db errors
Related
I have had to modify some php code to suit my needs and my forms page is now spitting out this
"Warning: Missing argument 11 for cash_payment(), called in
/.../wp-content/plugins/inkappointmentpro/ink-admin/apt-form.php
on line 66 and defined in
/.../wp-content/plugins/inkappointmentpro/ink-admin/appointments-form/getway/paypal-page.php
on line 26"
when submitting the form.
Here are the two files in question. Can someone please help? I'm not a programmer, just a guy who manages to fuddle his way through this stuff usually.
paypal-page.php
<?php
/**
* Paypal Transaction
* # gateway_sandbox
* */
function gateway_sandbox() {
if (isset($_POST['submit'])) {
$db_obj = new Apt_DB();
if (file_exists($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_sandbox.php")) {
include_once($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_sandbox.php");
}
}
}
/**
* Paypal Transaction
* # gateway_paypal
* */
function gateway_paypal() {
if (isset($_POST['submit'])) {
$db_obj = new Apt_DB();
if (file_exists($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_response.php")) {
include_once($db_obj->dir . "ink-admin/appointments-form/getway/paypal/paypal_response.php");
}
}
}
function cash_payment($sr_apt_id, $sr_apt_time, $sr_apt_date, $sr_apt_persion_name, $sr_apt_email, $sr_apt_phone, $sr_msg, $sr_apt_message, $sr_apt_ugs, $sr_apt_lawnarea, $sr_data_rand) {
global $wpdb;
$db_obj = new Apt_DB();
$apt_service = $db_obj->tbl_service;
$appointment_data = $db_obj->tbl_appointment_data;
$sql_srdata = $wpdb->get_row("SELECT * FROM $apt_service Where service_id='$sr_apt_id'", ARRAY_N);
$cr_code = get_option('apt_currency_code');
$price = $sql_srdata[2] . ' ' . $cr_code . ' - Pay Cash Later';
$priceshow = $sql_srdata[2] . '' . $cr_code;
$apt_txn_booking_date = date("F j, Y, g:i A");
$apt = new AptService();
if (isset($_POST['submit'])) {
$sql_val = $wpdb->get_row("SELECT * FROM $appointment_data Where apt_data_rand='$sr_data_rand'");
if (!$sql_val) {
$apt->insert_data_frontend($sr_apt_id, $sr_apt_date, $sr_apt_persion_name, $sql_srdata[1], $sr_apt_time, $price, $sr_apt_email, $sr_apt_phone, $sr_msg, $sr_apt_message, $sr_apt_ugs, $sr_apt_lawnarea, $sr_data_rand, $apt_txn_booking_date, 'cash');
echo '<p>Your appointment request has be submitted successfully. We will email or phone you with confirmation.</br>Thank you for choosing Saskatoon ProLawn.</p>';
/**
* Send transaction notification to admin or client
*/
$transaction_details = '';
$personname = $sr_apt_persion_name;
$servicename = $sql_srdata[1];
$aptime = $sr_apt_time;
$aptdate = $sr_apt_date;
$aptmessage = $sr_apt_message;
$aptugs = $sr_apt_ugs;
$aptlawnarea =$sr_apt_lawnarea;
$aptemail = $sr_apt_email;
$url = site_url();
$adminurl = str_replace('http://', '', $url);
$transaction_details .= "Hello $personname,\r";
$transaction_details .= "\r";
$transaction_details .= "Your appointment request has been received, below are the details of your request. \r \r";
$transaction_details .= "Service Name: $servicename \r";
$transaction_details .= "Appointment Date: $aptdate\r";
$transaction_details .= "Appointment Time: $aptime\r";
$transaction_details .= "Contact Phone: $aptphone\r";
$transaction_details .= "Address: $aptmessage\r";
$transaction_details .= "Underground Sprinklers Present: $aptugs\r";
$transaction_details .= "Lawn Area to be Done: $aptlawnarea\r \r";
$transaction_details .= "Thanks for choosing Saskatoon ProLawn.\r";
$transaction_details .= "When I confirm the date and time, I will send another email or contact you at the phone number provided. Please add us \r \r";
$transaction_details .= "Warm Regards,\r";
$transaction_details .= "Shane\r \r";
$transaction_details .= "$adminurl\r";
$subject = __("Your Appointment Request Has Been Received", 'appointment');
$filecontent = $transaction_details;
$admin_email = get_option('admin_email');
$headers = 'From: ' . $admin_email . ' <' . $aptemail . '>' . "\r\n" . 'Reply-To: ' . $admin_email;
$header = 'From: ' . $aptemail . ' <' . $admin_email . '>' . "\r\n" . 'Reply-To: ' . $aptemail;
//mail($to_admin, $subject, $filecontent, $headers);
wp_mail($aptemail, $subject, $filecontent, $headers); //email to user
wp_mail($admin_email, $subject, $filecontent, $header); //email to admin
} //refresh value if end
} //submit data if end
}
//function end
apt-form.php
<?php
add_shortcode('ink-appointments-form', 'ink_appoitment');
function ink_appoitment() {
?>
<script>
jQuery.noConflict();
jQuery(function () {
jQuery("#aptcal").datepicker();
jQuery("#aptcal").datepicker("option", "minDate", 0);
});
</script>
<?php
$db_obj = new Apt_DB();
global $wpdb;
$cpt_true = false;
$apt_service = $db_obj->tbl_service;
$check_apt = isset($_POST['chk_apt']) ? $_POST['chk_apt'] : null;
$cpt_apt = isset($_POST['apt_cpt']) ? $_POST['apt_cpt'] : null;
if ($check_apt != $cpt_apt) {
$cpt_true = true;
}
$msg = '';
$captcha_details = '';
$is_captcha_on = get_option('cpt_enable');
if ($_SERVER["REQUEST_METHOD"] == "POST" && $is_captcha_on == 'on') {
$recaptcha = $_POST['g-recaptcha-response'];
if (!empty($recaptcha)) {
$secret = get_option('apt_recaptcha_private');
$secret = empty($secret) ? 'Google secret key' : $secret;
$captcha_data = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $_POST['g-recaptcha-response']);
$response = json_decode($captcha_data, TRUE);
if ($response['success']) {
$captcha_details = true;
} else {
$captcha_details = false;
$error = array_search("invalid-input-secret", $response['error-codes']);
if ($error == 0) {
$msg = "Please enter correct reCAPTCHA key.";
} else {
$msg = "Please re-enter your reCAPTCHA.";
}
}
} else {
$captcha_details = false;
$msg = "Please re-enter your reCAPTCHA.";
}
}
$blank_data = "";
if ((isset($_POST['submit']) && $is_captcha_on != 'on' && $cpt_true == false ) || (isset($_POST['submit']) && $captcha_details == true)) {
$_POST['time'];
if (($_POST['time'] == 'notavi') || ($_POST['service_select'] == 'notavi')) {
echo "<p>Please Insert All data.</p>";
$blank_data = true;
} else {
$blank_data = false;
echo $badUrl = (isset($_POST['sr_price'])) ? $_POST['sr_price'] : null;
if (get_option('apt_paypal') == "sandbox") {
gateway_sandbox();
} elseif (get_option('apt_paypal') == "paypal") {
gateway_paypal();
} elseif (get_option('apt_paypal') == "cash") {
$datechange = $_POST['aptcal'];
$dateformat = explode('/', $datechange);
$newaptdate = $dateformat[1] . '/' . $dateformat[0] . '/' . $dateformat[2];
cash_payment($_POST['service_select'], $_POST['time'], $newaptdate, $_POST['fname'], $_POST['aptemail'], $_POST['aptphone'], $_POST['aptmessage'], $_POST['aptugs'], $_POST['aptlawnarea'], $_POST['random']);
}
}
}
if (isset($_GET['paypal-trans'])) {
ink_apt_trans_display();
} else {
$ruri = $_SERVER['REQUEST_URI'];
$sname = $_SERVER['SERVER_NAME'];
$fullpath = 'http://' . $sname . $ruri;
update_option('return_apt_url', $fullpath);
$br = new AptService();
$iechk = $br->ink_browser();
if ((!isset($_POST['submit'])) || ($check_apt != $cpt_apt) || ($captcha_details == false) || ($blank_data == true)) {
?>
<div class="ink-container">
<div class="inkappointment_wrapper">
<div class="inkappointment_form_top">
</div>
<div class="inkappointment_form_wrapper">
<form method="post" action="" id="ink-form" name="ink-form" class="ink-form" >
<header id="ink-header" class="ink-info">
</header>
<ul class="inkappform">
<li class="textheading"><h2><span class="msg_text"><?php echo get_option('apt_form_head'); ?></span></h2></li>
<li class="textfname"><input type="text" name="fname" id="fname" class="inktext inklarge inkrequired" placeholder="Name" maxlength="100" />
<label id="apt_error"> </label>
</li>
<li class="textaptemail"><input type="email" name="aptemail" id="aptemail" class="inktext inklarge inkrequired" placeholder="Email" maxlength="100" /></li>
<li class="textaptphone"><input type="text" name="aptphone" id="aptphone" class="inktext inklarge" placeholder="Contact Number" maxlength="12” /></li>
<li class="textfixdate"><span class="fix_date"><?php echo get_option('apt_fix_date'); ?></span></li>
<li class="select_item"><select id="service_select" name="service_select" class="inktext inklarge inkrequired" >
<option value="noavi">Select Service</option>
<?php
$showts = $wpdb->get_results("SELECT * FROM $apt_service ", ARRAY_A);
foreach ($showts as $timerow) {
?>
<option value="<?php echo $timerow['service_id']; ?>"><?php echo $timerow['service_name']; ?></option>
<?php } ?> </select></li>
<li class="textaptcal"><input type="text" name="aptcal" id="aptcal" class="dateField inktext inklarge" placeholder="Select Date" /></li>
<li class="select_item"><select id="time" name="time" class="inktext inklarge inkrequired">
<option value="notavi">Select Time</option> </select></li>
<li class="textfixdate"><span class="fix_date">Do you have underground Sprinklers?</span></li>
<li class="textfixdate"><span class="fix_date"><input type="radio" name="aptugs" id="aptugs" value="yes" checked>Yes <input type="radio" name="aptugs" id="aptugs"” value="no">No</span></li>
<li class="textfixdate"><span class="fix_date">Area Required</span></li>
<li class="textfixdate"><span class="fix_date"><input type="radio" name="aptlawnarea" id="aptlawnarea" value="frontback" checked>Front+Back <br> <input type="radio" name="aptlawnarea" id="aptlawnarea" value="front">Front Only <br> <input type="radio" name="aptlawnarea" id="aptlawnarea" value=“back”>Back Only</span></li>
<li class="textfixdate"><span class="fix_date"><?php echo get_option('apt_custom_msg'); ?></span></li>
<li class="textaptmessage"><textarea name="aptmessage" id="aptmessage" class="inktext inklarge inkrequired" maxlength="255" rows="3" cols="50" placeholder="Address (required)" ></textarea></li>
<?php if ($is_captcha_on === 'on') { ?><li>
<div class="g-recaptcha-div"><div class="g-recaptcha" data-sitekey="<?php
if (get_option('apt_recaptcha_public')) {
echo get_option('apt_recaptcha_public');
} else {
echo 'Google Public Key';
}
?>"></div>
</div>
<span class='msg'><?php echo $msg; ?></span>
</li>
<?php } ?>
<li class="submit_bg">
<input type="hidden" name="random" id="random" value="<?php echo rand(); ?>"/>
<input type="submit" name="submit" id="submit" class='ink-submit inkrequired' value="Book Appointment"/> </li>
</ul>
</form>
</div>
<div class="inkappointment_form_bottom">
</div>
</div>
</div>
<?php
} //submit not set
}
}
you have missing one parameter for the following function: cash_payment()
Function Definition having 11 parameters:
function cash_payment($sr_apt_id, $sr_apt_time, $sr_apt_date, $sr_apt_persion_name, $sr_apt_email, $sr_apt_phone, $sr_msg, $sr_apt_message, $sr_apt_ugs, $sr_apt_lawnarea, $sr_data_rand) {}
Function calling 10 parameters:
cash_payment($_POST['service_select'], $_POST['time'], $newaptdate, $_POST['fname'], $_POST['aptemail'], $_POST['aptphone'], $_POST['aptmessage'], $_POST['aptugs'], $_POST['aptlawnarea'], $_POST['random']);
If you don't have any 11th parameters of any values against parameters than pass the empty string but no of parameters in definition is always equal to no of parameters of calling a function.
I think this error comes due to missing argument in cash_payment function, please check all fields of this function.
cash_payment($_POST['service_select'], $_POST['time'], $newaptdate, $_POST['fname'], $_POST['aptemail'], $_POST['aptphone'], $_POST['aptmessage'], $_POST['aptugs'], $_POST['aptlawnarea'], $_POST['random']);
}
Please try to echo all fields and check if you found any of null value.
I need to add a option in the Admin page where a admin can Select a user and add points to them, however I write the name and how many points to add, enter it and it shows up with no errors but saying it has been successfully added, but the points have not been added to that user...
Here's my code for the page with the form:
if (empty($_POST) === false) {
$required_fields = array('username', 'add');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
}
if (empty($errors) === false) {
if (user_exists($_POST['username']) === true) {
$errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' doesn\'t exist';
}
}
?>
<?php
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
echo 'The points have succesfully been added to the user!';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$addpoints = array(
'username' => $_POST['username'],
'add' => $_POST['add']
);
addpoints($addpoints);
header('Location: addthepoints352346.php?success');
exit();
} else if (empty($errors) === false) {
echo output_errors($errors);
}
?>
<h1>Admin Access Only</h1>
<p>Add points to a user</p>
<form action="" method="post">
<ul>
<li>
Username*:<br>
<input type="text" name="username">
</li>
<li>
How many points to add*:<br>
<input type="text" name="add">
</li>
<li>
<input type="submit" value="Add">
</li>
</ul>
</form>
<?php
}
include 'includes/overall/footer.php';
?>
And also another page with the function where it actually sends it to the mysql database:
function addpoints($addpoints) {
mysql_query("UPDATE `users` SET `points` = `points` + '$add' WHERE `username` = '$username'");
}
I literally have no idea what it is, to help I have added a couple of photos
update your function as follows.
function addpoints($addpoints) {
mysql_query("UPDATE users SET points = points +".$addpoints['add']." WHERE username = ".$addpoints['$username'].")";
}
I am copying a youtube video tutorial for private messaging. The rest of the tutorial works fine, but as soon as I add this function to my site, my entire site goes blank and nothing is shown? No errors or anything, just a white screen? Have I done something wrong here? Here is the function:
<?php
function fetch_user_ids($usernames){
foreach ($usernames as &$name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
$names = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$names[$row['username']] = $row['userid'];
}
return $names;
}
?>
Here is the script to send the information:
<?php
if (isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if (empty($_POST['to'])){
$errors[] = 'You must enter atleast one name.';
}else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
}else{
$usernames = explode(',', $_POST['to']);
foreach ($usernames as &$name){
$name = trim($name);
}
$user_ids = fetch_user_ids($usernames);
if (count($user_ids) !== count($usernames)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($usernames, array_keys($user_ids)));
}
}
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty';
}
if (empty($_POST['body'])){
$errors[] = 'You body must have some text!';
}
if (empty($errors)){
//Send message
}
}
if (isset($errors)){
if (empty($errors)){
echo '<div class="msg success">Your message has been sent ! return</div>';
}else{
foreach ($errors as $error){
echo '<div class="msg error">', $error, '</div>';
}
}
}
?>
<form action="" method="POST">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" />
</div>
<div>
<textarea name="body" rows="10" cols="110"></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</form>
If I take away the "function" part, I can print the data, so it must be something to do with the function element?
I would suggest changing the !== to != and seeeing if that works, it could be interpreting it has a number and not as a bool
Make it simpler. Inside foreach, get rid of &$name and replace it with $name. Also check if your database is returning nothing.
foreach ($usernames as $name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
// Check if the query itself is failing or not here:
if(!$result) die("Failed to perform query");
$names = array();
// Check if the database is returning any rows or not:
print_r(mysql_num_rows($result));
while($row = mysql_fetch_assoc($result)){
$names[$row['username']] = $row['userid'];
}
return $names;
I am new to PHP and I have problem to select values which have space between for eg TRANSGENDER FtM, if I use TRANSGENDER-MtF then am able to save it. And same with name input, here is the code:
<?php
include_once 'core/init.php';
$general->logged_out_protect();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css" >
<title>Settings</title>
</head>
<body>
<div class="nav-bar" style="box-shadow:0 0 5px 0 rgba(0, 0, 0, 0.4);" >
<?php include 'includes/menu.php'; ?>
</div><!-- NAV BAR DIV closes here -->
<div id="main-wrap" style=" box-shadow:0 0 5px 0 rgba(0, 0, 0, 0.4);">
<div id="container">
<?php
if (isset($_GET['success']) && empty($_GET['success'])) {
echo '<h3>Your details have been updated!</h3>';
} else{
if(empty($_POST) === false) {
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
if (ctype_alpha($_POST['first_name']) === false) {
$errors[] = 'Please enter your First Name with only letters!';
}
}
if (isset($_POST['last_name']) && !empty ($_POST['last_name'])){
if (ctype_alpha($_POST['last_name']) === false) {
$errors[] = 'Please enter your Last Name with only letters!';
}
}
if (isset($_POST['gender']) && !empty($_POST['gender'])) {
$allowed_gender = array('undisclosed', 'Male', 'Female');
if (in_array($_POST['gender'], $allowed_gender) === false) {
$errors[] = 'Please choose a Gender from the list';
}
}
if (isset($_POST['trans']) && empty($_POST['trans'])) {
$allowed_trans = array(
"--Undisclosed--",
"Transperson",
"Transgender",
"Transsexual MtF",
"Transsexual FtM",
"Transvestite MtF",
"Transvestite FtM",
"Intergender",
"Intersexual");
if (in_array($_POST['trans'], $allowed_trans) === false) {
$errors[] = 'Please choose a Trans from the list if Any';
}
}
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif' );
$a = explode('.', $name);
$file_ext = strtolower(end($a)); unset($a);
$file_size = $_FILES['myfile']['size'];
$path = "avatars";
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Image file type not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
} else {
$newpath = $user['image_location'];
}
if(empty($errors) === true) {
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name']) && $_POST['use_default'] != 'on') {
$newpath = $general->file_newpath($path, $name);
move_uploaded_file($tmp_name, $newpath);
}else if(isset($_POST['use_default']) && $_POST['use_default'] === 'on'){
$newpath = 'avatars/default_avatar.png';
}
$first_name = htmlentities(trim($_POST['first_name']));
$last_name = htmlentities(trim($_POST['last_name']));
$gender = htmlentities(trim($_POST['gender']));
$bio = htmlentities(trim($_POST['bio']));
$trans = htmlentities(trim($_POST['trans']));
$image_location = htmlentities(trim($newpath));
$users->update_user($first_name, $last_name, $gender, $bio, $image_location, $user_id, $trans);
header('Location: settings.php?success');
exit();
} else if (empty($errors) === false) {
echo '<p>' . implode('</p><p>', $errors) . '</p>';
}
}
?>
<h2>Settings.</h2> <p><b>Note: Information you post here is made viewable to others.</b></p>
<hr />
<form action="" method="post" enctype="multipart/form-data">
<div id="profile_picture">
<h3>Change Profile Picture</h3>
<ul>
<?php
if(!empty ($user['image_location'])) {
$image = $user['image_location'];
echo "<img src='$image'>";
}
?>
<li>
<input type="file" name="myfile" />
</li>
<?php if($image != 'avatars/default_avatar.png'){ ?>
<li>
<input type="checkbox" name="use_default" id="use_default" /> <label for="use_default">Use default picture</label>
</li>
<?php
}
?>
</ul>
</div>
<div id="personal_info">
<h3 >Change Profile Information </h3>
<ul>
<li>
<h4>First name:</h4>
<input type="text" name="first_name" value="<?php if (isset($_POST['first_name']) ){echo htmlentities(strip_tags($_POST['first_name']));} else { echo $user['first_name']; }?>">
</li>
<li>
<h4>Last name: </h4>
<input type="text" name="last_name" value="<?php if (isset($_POST['last_name']) ){echo htmlentities(strip_tags($_POST['last_name']));} else { echo $user['last_name']; }?>">
</li>
<li>
<h4>Gender:</h4>
<?php
$gender = $user['gender'];
$options = array("undisclosed", "Male", "Female");
echo '<select name="gender">';
foreach($options as $option){
if($gender == $option){
$sel = 'selected="selected"';
}else{
$sel='';
}
echo '<option '. $sel .'>' . $option . '</option>';
}
?>
</select>
</li><br>
<li>
<h4>Trans:</h4>
<?php
$trans = $user['trans'];
$options = array("--Undisclosed--",
"Transperson",
"Transgender",
"Transsexual MtF",
"Transsexual FtM",
"Transvestite MtF",
"Transvestite FtM",
"Intergender",
"Intersexual");
echo '<select name="trans">';
foreach($options as $option){
if($trans == $option){
$sel = 'selected="selected"';
}else{
$sel="";
}
echo '<option '. $sel .'>' . $option . '</option>';
}
?>
</select>
</li><br>
<li>
<h4>Bio:</h4>
<textarea name="bio"><?php if (isset($_POST['bio']) ){echo htmlentities(strip_tags($_POST['bio']));} else { echo $user['bio']; }?></textarea>
</li>
</ul>
</div>
<div class="clear"></div>
<hr />
<span>Update Changes:</span>
<input type="submit" value="Update">
</form>
</div><!-- Container DIV closes here -->
</div><!-- Main Wrap DIV closes here -->
</body>
</html>
<?php
}
In relation to your screenshot, the problem is that your validation on "First name" is working correctly! I would first suggest that in order to make this change, you should change the form to read "First name(s):" to make it clear that any number of first names are allowed in this field. Ideally you should do this with the field name too.
Your code is thus:
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
if (ctype_alpha($_POST['first_name']) === false) {
$errors[] = 'Please enter your First Name with only letters!';
}
}
The function your code uses is ctype_alpha, which does not permit spaces. You could change this to:
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
// Remove spaces from intermediate variable, to permit them
$firstNames = str_replace(' ', '', $_POST['first_name']);
if (ctype_alpha($firstNames) === false) {
$errors[] = 'Please enter your first name(s) with only letters!';
}
}
The error i got was:
Notice: Undefined index: visible in C:\xampp\htdocs\introducingphp\includes\validation_function.php on line 22
It should not happen since i already instantiated all the variables including visible
Validation_function.php
<?php
$errors = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
// * presence
// use trim() so empty spaces don't count
// use === to avoid false positives
// empty() would consider "0" to be empty
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
// * string length
// max length
function has_max_length($value, $max) {
return strlen($value) <= $max;
}
function validate_max_lengths($fields_with_max_lengths) {
global $errors;
// Expects an assoc. array
foreach($fields_with_max_lengths as $field => $max) {
$value = trim($_POST[$field]);
if (!has_max_length($value, $max)) {
$errors[$field] = fieldname_as_text($field) . " is too long";
}
}
}
// * inclusion in a set
function has_inclusion_in($value, $set) {
return in_array($value, $set);
}
?>
new_page.php (the page that has the one-page submit form that does validation)
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
// Can't add a new page unless there is a subject as a parent
if (!$current_subject) {
// subject ID was missing or invalid or
//subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("menu_name", "position", "visible",
"content");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 60);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// perform Create
//add the subject_id
$subject_id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
//escape content
$content = mysql_prep($_POST["content"]);
// 2. Perform database query
$query .= "INSERT INTO pages (";
$query .= " subject_id, menu_name, position, visible,
content";
$query .= ") VALUES (";
$query .= " {$subject_id}, '{$menu_name}', {$position},
{$visible}, '{$content}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Page Created.";
redirect_to("manage_content.php?subject=" .
urlencode($current_subject["id"]));
}else {
// Failure
$_SESSION["message"] = "Page creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<?php include("header.php"); ?>
<div id="main">
<div id="navigation">
<?php echo navigation($current_subject, $current_page); ?>
</div>
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Page</h2>
<form action="new_page.php?subject=<?php echo
urlencode($current_subject["id"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="" />
</p>
<p>Position:
<select name="position">
<?php
$page_set =
find_all_pages_for_subject($current_subject["id"], false);
$page_count = mysqli_num_rows($page_set);
for($count=1; $count <= ($page_count + 1); $count++) {
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible
<input type="radio" name="visible" value="0" /> NO
<input type="radio" name="visible" value="1" /> Yes
</p>
<p>Content:<br />
<textarea name="content" rows="20" cols="80"></textarea>
</p>
<input type="submit" name="submit" value="Create Page" />
</form>
<br />
<a href="manage_content.php?subject=<?php echo
urlencode($current_subject["id"]); ?>">Cancel</a>
</div>
</div>
<?php include("includes/footer.php"); ?>
You probably have a typo on the input HTML field. You can use:
if (isset($_POST[$field])) {
on validate_presences() function to be sure that the value exists.
When you try to do trim($_POST[$field]); you assume, the field exists in the $_POST array - for visible it does not in this case. You could move the trim to has_presence()
function has_presence($value) {
return isset($value) && trim($value) !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Now when you will only have the trim if the variable exists.
Okay, marking the radio check button makes it work now. Thanks for all your inputs guys. It has helped me a great deal.