I have a permissions table and I want the ability to check each multiple boxes and a modal window opens with the input fields to edit the permission name. Once I submit I want to update the database with the new names of each input.
Here is what I have so far...
For each box checked I out put this in the modal:
<div class="form-group">
<label>Permission Name</label>
<input class="del-'+row.id+' form-control" id="name['+row.name+']" type="text" name="name['+row.id+']" value="'+row.name+'" >
<input class="del-'+row.id+' form-control" id="id['+row.name+']" type="hidden" name="id['+row.id+']" value="'+row.id+'" >
</div>
Here is what the JS code looks like for the above:
$("#editModalForm").append('<div class="form-group"><label>Permission Name</label><input class="del-'+row.id+' form-control" id="name['+row.name+']" type="text" name="name['+row.id+']" value="'+row.name+'" ><input class="del-'+row.id+' form-control" id="id['+row.name+']" type="hidden" name="id['+row.id+']" value="'+row.id+'" ></div>');
Here is the PHP code when I submit the form:
//Update permission level names
$permissionId = $_POST['id'];
if($permissionDetails['name'] != $_POST['name']) {
$permission = trim($_POST['name']);
$previousName = $permissionDetails['name'];
//Validate new name
if (permissionNameExists($permission)) {
$errors[] = lang("ACCOUNT_PERMISSIONNAME_IN_USE", array($permission));
} elseif (minMaxRange(1, 50, $permission)) {
$errors[] = lang("ACCOUNT_PERMISSION_CHAR_LIMIT", array(1, 50));
} else {
if (updatePermissionNames($permissionId, $permission)) {
$successes[] = lang("PERMISSION_NAME_UPDATE", array($previousName, $permission));
} else {
$errors[] = lang("SQL_ERROR");
}
}
}
Here is the function that updates the database:
//Change a multiple permission level names
function updatePermissionNames($id, $name) {
global $mysqli,$db_table_prefix;
$i = 0;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."permissions
SET name = ?
WHERE
id = ?
LIMIT 1");
foreach($id as $ids) {
$stmt->bind_param("si", $name, $ids);
$result = $stmt->execute();
}
$stmt->close();
return $result;
}
I am not really sure what I am doing wrong here so I am hoping someone can help me out. If you have any examples that would be great. Again, I want to know how I can update each value?
if you want to get value of input with name="id['+row.id+']"
you should do use
$arrID = $_POST['id']
foreach($arrID as $key => $value){
echo $key;
echo $value;
}
because input id[1] is array when post to server, itn't string.
Related
Is there a way to convert left and right single quotes into apostrophes when a form is submitted and before validation begins?
The reason I ask is that my form works on all platforms just how I want it, however iPhone users at times use the wrong character and input a left or right single quotation instead. As my form verifies the entered data and must be exact, the left single quote is being seen as a error compared to the apostrophe in the DB table and not accepting the information.
If I could have those characters convert when the user submits to apostrophes then all would work even on the iPhones. any insight would be gratefully appreciated, I have tried a few items like htmlspecialchar but didn't seem to assist.
Also I should note that when using the iPhone and entering the coorect apostrophe in the smart keyboard layout on ios11 I was able to successfully pass validation of the form. It seems this is a known issue of apples but they have yet to rectify this, I am sure the solution would be beneficial to many in the community I hope, if we can find the answer that is.
The form field in question is:
<input type="text" name="last_name" id="last_name" value="<?php echo htmlspecialchars(stripslashes(isset($fields['last_name'])) ? $fields['last_name'] : '') ?>" >
how can I set this form field to convert left and right single quotes into apostrophes on form submit using php or jquery?
UPDATE
#fubar you are my savior tonight. the first solution worked great. But how would I add teh second option instead?
function cv(&$fields, &$errors) {
// Check args and replace if necessary
if (!is_array($fields)) $fields = array();
if (!is_wp_error($errors)) $errors = new WP_Error;
// Check for form submit
if (isset($_POST['submit'])) {
// Get fields from submitted form
$fields = cv_get_fields();
// Validate fields and produce errors
if (cv_validate($fields, $errors)) {
// If successful, display a message
$Id=$fields['login'];
$First=$fields['first_name'];
$Last=$fields['last_name'];
global $wpdb;
$user = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM users WHERE login = %s", $Id ) );
$userquery = $wpdb->get_results($user->login);
$Id=$fields['login'];
if ( !username_exists ($Id)) {
$Id=$fields['login'];
$access = $wpdb->get_row( $wpdb->prepare( "SELECT access FROM table WHERE ID = %s", $Id ) );
foreach ($access as $accessquery) {
if ($accessquery == lvl2) {
$_SESSION['mem_data']=$fields;
header("Location: https://example.com/lvl2-register/");
}
if ( is_null ($accessquery)) {
$_SESSION['mem_data']=$fields;
header("Location: https://example.com/lvl1-register/");
}
}
}
elseif ( username_exists ($Id)) {
header("Location: https://example.com/already-registered/");
}
}
}
// Santitize fields
cv_sanitize($fields);
// Generate form
cv_display_form($fields, $errors);
}
function cv_sanitize(&$fields) {
$fields['login'] = isset($fields['login']) ? sanitize_user($fields['login']) : '';
$fields['first_name'] = isset($fields['first_name']) ? sanitize_text_field($fields['first_name']) : '';
$fields['last_name'] = isset($fields['last_name']) ? sanitize_text_field($fields['last_name']) : '';
}
function cv_display_form($fields = array(), $errors = null) {
// Check for wp error obj and see if it has any errors
if (is_wp_error($errors) && count($errors->get_error_messages()) > 0) {
// Display errors
?>
<div class="step1-form" style="display:block;margin:0 auto;text-align:left;max-width:1080px;">
<?php
foreach ($errors->get_error_messages() as $key => $val) {
?><p>
<?php echo $val; ?>
</p><?php
}
?><?php
}
// Display form
?>
</div>
<div class="step1-form" style="display:block;margin:0 auto;text-align:left;max-width:1080px;">
<h1 class="til-postheader entry-title">User Registration: Step 1 of 2</h1>
<h4>Prior to registering for this website you must first verify Your Membership.<h4>
<div id="login" style="max-width:175px;width:100%;margin:10px;">
<form action="" method="post">
<div>
<label for="first_name">First Name:</label><br>
<input type="text" name="first_name" id="first_name" value="<?php echo (isset($fields['first_name']) ? $fields['first_name'] : '') ?>" >
</div>
<br>
<div>
<label for="last_name">Last Name:</label><br>
<input type="text" name="last_name" id="last_name" value="<?php echo htmlspecialchars(stripslashes(isset($fields['last_name'])) ? $fields['last_name'] : '') ?>" >
</div>
<br>
<div>
<a data-fancybox data-src="#ID" href="javascript:;" style="outline:none;border:0px;text-decoration:none;" tabindex="-1"><span style="width:21px;float:right;color:#ffffff;background:#0a4b73;text-align:center;line-height:21px;border-radius:50%;" tabindex="-1">?</span></a><label for="login">Member ID:</label><br>
<input type="text" name="login" id="login" value="<?php echo (isset($fields['login']) ? $fields['login'] : '') ?>" >
</div>
<br>
<input type="submit" name="submit" value="Verify Membership">
</form>
</div>
<?php
}
function cv_get_fields() {
return array(
'login' => isset($_POST['login']) ? $_POST['login'] : '',
'first_name' => isset($_POST['first_name']) ? $_POST['first_name'] : '',
'last_name' => isset($_POST['last_name']) ? $_POST['last_name'] : '',
);
}
function cv_validate(&$fields, &$errors) {
// Make sure there is a proper wp error obj
// If not, make one
if (!is_wp_error($errors)) $errors = new WP_Error;
// Validate form data
// Define $Card $First $Last $PIN
$Id=$fields['login'];
$First=$fields['first_name'];
$Last=$fields['last_name'];
// $Lastname = htmlspecialchars_decode(stripslashes($fields["last_name"]));
$Lastname = '‘ ‘ - ’ ’';
$Lastname = str_replace(['‘', '’'], "'", html_entity_decode(stripslashes($fields["last_name"])));
global $wpdb;
$result = $wpdb->get_row( $wpdb->prepare( 'SELECT distinct ID, First, Last, FROM table WHERE ID = %s AND First = "%s" AND Last = "%s", $Id, $First, $Lastname ) );
if ( is_null ( $result ) ) {
$errors->add('non_member', 'The information entered does not match our records.');
}
if (empty($fields['login']) || empty($fields['first_name']) || empty($fields['last_name'])) {
$errors->add('field', '');
}
// If errors were produced, fail
if (count($errors->get_error_messages()) > 0) {
return false;
}
$Id=$fields['login'];
global $wpdb;
$accessno = $wpdb->get_row( $wpdb->prepare( "SELECT distinct access FROM table WHERE ID = %s", $Id ) );
foreach ($accessno as $noquery) {
if ( $noquery == NO) {
header ('Location: https://example.com/access-denied/');
}
}
// Else, success!
return true;
}
// The callback function for the [cv] shortcode
function cv_cb() {
$fields = array();
$errors = new WP_Error();
// Buffer output
ob_start();
// Custom verification, go!
cv($fields, $errors);
// Return buffer
return ob_get_clean();
}
add_shortcode('cv', 'cv_cb');
This would convert the single quote, both raw and encoded into apostrophes.
$value = '‘ ‘ - ’ ’';
$value = str_replace(['‘', '’'], "'", html_entity_decode($value));
If you want to apply this to all POST data, you could use:
$_POST = array_map(function ($value) {
return str_replace(['‘', '’'], "'", html_entity_decode($value));
}, $_POST);
Edit
If you replace the following line:
// Get fields from submitted form
$fields = cv_get_fields();
With:
// Get fields from submitted form
$fields = array_map(function ($value) {
return str_replace(['‘', '’'], "'", html_entity_decode($value));
}, cv_get_fields());
And then you can remove the following:
$Lastname = '‘ ‘ - ’ ’';
$Lastname = str_replace(['‘', '’'], "'", html_entity_decode(stripslashes($fields["last_name"])));
I am writing a simple login validation. (I know people say I shouldn't deal with passwords in plaintext, because it's dangerous, however, I am doing this for a school assignment where we do not need to use any security.) The issue I am having here is that I can't get the message for login to be successful. I am getting a login failure. I inserted a couple of users and passwords into a database table. What I need to do is to get the value from the "name" column and the "pwd" (password) column from my database table and allow a successful login (in Javascript) if the user's input has a match with the user and password in the database table.
Here is my form code:
<form method="post" action="login.php" onsubmit="validateForm()" id="loginForm" name="loginForm">
Name:<br>
<input type="text" name="personName"><br>
Password:<br>
<input type="password" name="pswd"><br>
<input type="submit" name="submit" id="submit" value="Login" />
</form>
Javascript:
<script>
function validateForm()
{
var n = document.loginForm.personName.value;
var p = document.loginForm.pswd.value;
//The var below is what I need help on.
var name = "<?php echo $row['name']; ?>";
//The var below is what I need help on.
var ps = "<?php echo $row['pwd']; ?>";
if ((n == name) && (p == ps))
{
alert ("Login successful!");
return true;
}
else
{
alert ("Login failed! Username or password is incorrect!");
return false;
}
}
</script>
PHP code (I have an empty while statement just in case I need it):
<?php
function validateLogin()
{
//I hid this information from here.
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$dbc = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($dbc->connect_error)
{
die("Connection failed: " . $dbc->connect_error);
}
$n = $_POST["personName"];
$p = $_POST["pswd"];
$query = "SELECT `name`, `pwd` FROM `chatApp`";
$result = $dbc->query($query);
$numRows = mysql_num_rows($result);
$count = 1;
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
}
}
else
{
echo "0 results";
}
$dbc->close();
}
if(array_key_exists('loginForm',$_POST))
{
validateLogin();
}
?>
Right now, I have a dialog box that pops up when an Add button is clicked. There are 2 inputs inside that will be inserted into the database upon submit. There is a dropdown list and an input box. I do not want the submit on the dialog box to be able to work if a value that is already existing in the database, is entered into the input box. So basically, I do not want there to be any duplicate records in the Supp_ID columns. How can I do this? Here is what I have so far.
Dialog Form:
<div id="dialog-form" title="Add Supplier ID">
<p class="validateTips">All form fields are required.</p>
<!-- Dialog box displayed after add row button is clicked -->
<form >
<fieldset>
<label for="mr_id">MR_ID</label>
<select name="mr_id" id="mr_id_dialog" class="text ui-widget-content ui-corner-all" value="300">
<?php foreach($user1->fetchAll() as $user2) { ?>
<option>
<?php echo $user2['MR_ID'];?>
</option>
<?php } ?>
</select><br><br>
<label for="supplier_id">Supplier ID</label>
<input type="text" name="supp_id" id="supplier_id" class="text ui-widget-content ui-corner-all" value="99">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
JavaScript:
$("document").ready(function() {
$('#submit').submit(function() {
processDetails();
return false;
});
});
function processDetails() {
var errors = '';
// Validate Supp ID
var supplier = $("#supplier_id [name='supp_id']").val();
if (supplier == "null" || supplier == "") { // check for empty value
errors += ' - Please enter a different Supplier ID\n';
}
// MORE FORM VALIDATIONS
if (errors) {
errors = 'The following errors occurred:\n' + errors;
alert(errors);
return false;
} else {
// Submit form via Ajax and then reset the form
$("#submit").ajaxSubmit({success:showResult}).resetForm();
return false;
}
}
function showResult(data) {
if (data == 'save_failed') {
alert('ERROR. Your input was not saved.');
return false;
} else if (data == 'save_failed_duplicate') {
alert('ERROR. Input data already exists.');
return false;
} else {
alert('SUCCESS. Your input data has been saved.');
return false;
}
}
Insert.php
<?php
$MR_ID = $_POST['MR_ID'];
$Supp_ID = $_POST['Supp_ID'];
$host="xxxxxxxx";
$dbName="xxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$check_sql = "SELECT Supp_ID FROM Stage_Rebate_Index WHERE Supp_ID = '$Supp_ID'";
$check_sql_query = sqlsrv_query($check_sql, $dbh);
if (sqlsrv_num_rows($check_sql_query) > 0) {
echo "save_failed_duplicate";
#sqlsrv_close($dbh);
return;
} else {
if (sqlsrv_num_rows($check_sql_query) == 0) {
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, '$Supp_ID')";
if (#sqlsrv_query($sql, $dbh)) {
echo "success";
#sqlsrv_close($dbh);
return;
} else {
echo "save_failed";
#sqlsrv_close($dbh);
return;
}
}
}
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($MR_ID, $Supp_ID));
echo json_encode($result);
?>
I always use ON DUPLICATE KEY UPDATE in case I want to update a timestamp or something.
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, '$Supp_ID') ON DUPLICATE KEY UPDATE `MR_ID` = `MR_ID`";
Basically, it attempts to insert the record, but if the key exists, it updates whatever data you need. In the above example, it simply updates the MR_ID with the original MR_ID.
Here is a previous question similar to this one: Link
Here is the link the Mysql manual: Link
Use the IGNORE keyword in your SQL statement.
$sql = "INSERT IGNORE INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, '$Supp_ID')";
You will need to modify your response to check the number of rows affected instead of whether the query failed.
See: http://php.net/manual/en/pdostatement.rowcount.php
I'm new to this and I have trouble understanding how all things works.
I have a php/html page and a login form in it. The login submit button executes a php file (let's say check_user.php) in which theoretically it checks the user and password i put in the form in a database. If it finds them I want the php file (check_user.php) to return to the main page the name of the user and his "class" (like supervisor, operator etc) in order to use them for further active change of main page content (like hide/show menus, enable/disbale elements etc). The problem is that the php returns with echo a text as I understand....How can I process this text to be stored in variables (one or more then one) to be usable in the main page? I understand how to pass variables to a php file, but i don't understand how to process the result of the php, except changing the content of an element in the mane page.
Maybe I need a callback function, I need to use JSON....
PS: I want to do this without $_SESSION
my code is here:
main page:
<div id="show2">
<?php
$userErr = $passErr = "";
$user = $pass = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"])) {
$userErr = "User name is required";
}
else {
$user = test_input($_POST["user"]);
if (!preg_match("/^[a-zA-Z ]*$/",$user)) {
$userErr = "Only letters and white space allowed";
}
}
if (empty($_POST["pass"])) {
$passErr = "Password is required";
}
else {
$pass = test_input($_POST["pass"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>LOGIN INFORMATION:</h2>
<form method="post" action="check_user.php">
User: <input type="text" name="user" value="<?php echo $user;?>">
<span class="error">* <?php echo $userErr;?></span>
<br><br>
Password: <input type="password" name="pass" value="<?php echo $pass;?>">
<span class="error">* <?php echo $passErr;?></span>
<br><br>
<input type="submit" name="submit" value="Login">
</form>
</div>
check_user.php:
<?php
if ($_POST["user"] == "xxx" And $_POST["pass"] == "yyyy") {
$name = "John Legend"; /*here I assign value from database*/
$class = "Supervisor"; /*here I assign value from database*/
echo .... ; /*here I don't know what to echo. I want to echo $name and $class and use them as variables (not as text) in the main page*/
}
else {
echo "error";
}
?>
the implementation for database is not done, but the example still apply to any value I assign to the variables I want the php to echo
No matter what I type in (even the correct captcha), I always get missmatched output. I've tried echoing the values (they are supposed to match if you type in the right code). and I always get something like this:
6952304285049
-1247767175
I am using jquery-1.10.2.min.js (and have this linked in my header along with the realperson.js file)
http://gfishdesigns.com/COMP2920/_COMPLETED/Assignment%202/SignUp.php
Here's my code (im doing some other validating as well):
<?php
include 'Header.php';
include 'Database.php';
?>
<script type="text/javascript">
$(function() {
$('#defaultReal').realperson();
});
</script>
<h1>Sign Up</h1>
<?php
if ($_POST){
$username = $_POST['username'];
$password = $_POST['password'];
$check = '';
//validate CAPTCHA
function rpHash($value) {
$hash = 5381;
$value = strtoupper($value);
for($i = 0; $i < strlen($value); $i++) {
$hash = (($hash << 5) + $hash) + ord(substr($value, $i));
}
return $hash;
}
if (rpHash($_POST['defaultReal']) == $_POST['defaultRealHash']) { ?>
<p class="accepted">You have entered the "real person" value correctly and the form has been processed.</p>
<?php
//if username is not blank
if($username != ''){
//check if username exists already
$query = "SELECT username FROM tbl_user;";
$result = mysql_query($query) or die(mysql_error());
while ($record = mysql_fetch_row($result))
{
foreach($record as $field)
{
if($field == $username){
//if user exists, dont let them add same user
$error_message_username = 'username already used; choose a unique name';
}
else{
$check = 'pass';
}
}
}
}else{
$error_message_username = 'username cannot be blank';
}
//if password is not blank
if($password != ''){
$error_message_password = '';
// encrypt password
$encrypted_password = md5($password);
if($check == 'pass'){
//set username and password into database
$query = "INSERT INTO tbl_user VALUES('','".$username."','".$encrypted_password."');";
$result = mysql_query($query) or die(mysql_error());
}
}else{
$error_message_password = 'password cannot be blank';
}
} else { ?>
<p class="rejected">You have NOT entered the CAPTCHA value correctly and the form has been rejected.</p>
<?php
echo rpHash($_POST['defaultReal']) . '<br/>';
echo $_POST['defaultRealHash'];
}
}
?>
<form method="post" action="SignUp.php">
<p>
E-Mail:
<input type="text" class="required email" id="username" name="username">
<?php
if ( $error_message_username != '' ) {
print "$error_message_username";
}
?>
</p>
<p>
Password:
<input type="text" name="password">
<?php
if ( $error_message_password != '' ) {
print "$error_message_password";
}
?>
</p>
<p>
CAPTCHA:
<input type="text" id="defaultReal" name="defaultReal">
</p>
<p>
<button class="mybutton" type="submit" value="Sign Up">Sign Up</button>
</p>
</form>
Well said Craig Jacobs, it is the same problem which you pointed out. I also faced the same thing and solved by making changes shown below:
function rpHash($value) {
$hash = 5381;
$value = strtoupper($value);
for($i = 0; $i < strlen($value); $i++) {
$hash = (leftShift32($hash, 5) + $hash) + ord(substr($value, $i));
}
return $hash; }
function leftShift32($number, $steps) {
$binary = decbin($number);
$binary = str_pad($binary, 32, "0", STR_PAD_LEFT);
$binary = $binary.str_repeat("0", $steps);
$binary = substr($binary, strlen($binary) - 32);
return ($binary{0} == "0" ? bindec($binary) :
-(pow(2, 31) - bindec(substr($binary, 1))));
}
if (isset($_POST['submit'])) {
.....
if (rpHash($_POST['defaultReal']) != $_POST['defaultRealHash']) {
echo "Invalid contact request, please try again with correct verification code...";
exit;
}
.....
.....
}
Hope it will help someone else too.
There are two versions of the php rpHash function provided, one for 32-bit and one for 64-bit PHP. Run phpinfo and make sure you are using the correct version of the function as provided on this page http://keith-wood.name/realPerson.html. The bitwise functions as used here will return different values on 32 and 64 bit machines. See this page: http://www.php.net/manual/en/language.operators.bitwise.php