i have a simple form and this is in the admin side and i want to save it to the database but the form is not submitting
function actions_add_form_list() {
?>
<form action="<?php echo admin_url( 'admin.php' ); ?>" method="POST">
<input type="text" name="api_key" placeholder="...">
<input type="text" name="list id" placeholder="...">
<input type="submit" name="add-key" value="...">
</form>
<?php
function test_plugin_capture() {
if (isset( $_POST['add-key'] ) ) {
global $wpdb;
$tablename=$wpdb->prefix.'custom_api';
$data=array(
'api_key' => $_POST['api_key'],
'list_id' => $_POST['list_id'],
);
$wpdb->insert( $tablename, $data);
}
}
}
`
Related
I'm using a form, inside which contains a div with a pair of input field which is added dynamically.
VIEW:
<?php echo form_open_multipart('location/add'); ?>
<div>
<input type="text" name="title[]"/>
<div id="infoMessage"><?php echo form_error('title[]'); ?></div>
</div>
<div>
<input type="text" name="desc[]"/>
<div id="infoMessage"><?php echo form_error('desc[]'); ?></div>
</div>
<div>
<input type="text" name="link[]"/>
<div id="infoMessage"><?php echo form_error('link[]'); ?></div>
</div>
<input type="submit" name="" value="enter">
<?php echo form_close(); ?>
Now, Initially I don't want validation for this 3 input fields but I want the backend validation for all the input fields that are going to add dynamically(by clicking on +) on pressing submit button.
CONTROLLER:
public function add()
{
$this->form_validation->set_rules('title[]','Title','required');
$this->form_validation->set_rules('desc[]','Description','required');
$this->form_validation->set_rules('link[]','Link','required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('test');
}
else
{
....
}
}
You can use custom callback validation function
EX:
public function add()
{
$this->form_validation->set_rules('title', 'Title', 'callback_title_validate');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('test');
}
else
{
//....
}
}
function title_validate($title){
foreach($title as $key=>$value){
if($title[$key]==null || $title[$key]==false){
$this->form_validation->set_message('title_validate', 'The Title field is Required.');
return FALSE;
}
}
return TRUE;
}
Once again i'm turning to the stack community to try and solve my problem.
I'm using Slim, Twig and RedBean together to create a backend app for my website (long story short, i'm using Slim to be able to connect an API and an application to it).
(Note: I'm relatively new to RedBean so i'm not yet at ease with it)
However, i'm getting a strange exception error from a try and catch when trying to update a user.
The following points however work:
- Add user
- Delete user
When i update my user, it gives me the message "This email is already in use" which is normal since i'm it's the account's email. However, i cannot get passed the error...
Here is exception file (Models/Validation/Users.php):
class Users extends SimpleModel {
public function update() {
$firstname = trim($this->bean->firstname);
$lastname = trim($this->bean->lastname);
$email = trim($this->bean->email);
if(isset($this->bean->firstname)){
$firstname = trim($this->bean->firstname);
if(empty($firstname)) {
throw new ValidationException( 'You have to provide a firstname.' );
}
}
if(isset($this->bean->lastname)){
$lastname = trim($this->bean->lastname);
if(empty($lastname)) {
throw new ValidationException( 'You have to provide a lastname.' );
}
}
if(isset($this->bean->email)){
$email = trim($this->bean->email);
if(empty($email)) {
throw new ValidationException( 'You have to provide an email.' );
}
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new ValidationException( 'Not a valid email.' );
}
$searchUser = R::findOne( 'Users', ' email = ? ', [ $email ] );
if(!empty($searchUser)){
$equal = $this->bean->equals($searchUser);
} else {
$equal = FALSE;
}
if(!empty($searchUser) && !$equal) {
throw new ValidationException( 'This email already exists.' );
}
}
}
And the update call:
public function update( $id, $entry ) {
try {
$user = R::load( $this->config->getTable('users'), 'id = ? ', [ $id ] );
if(array_key_exists('firstname',$entry)) $user->firstname = $entry['firstname'];
if(array_key_exists('lastname',$entry)) $user->lastname = $entry['lastname'];
if(array_key_exists('email',$entry)) $user->email = $entry['email'];
(!empty($entry['password'])) ? $user->password = password_hash($entry['password'], PASSWORD_BCRYPT) : null;
R::store($user);
} catch(ValidationException $e) {
$this->errors[] = $e->getMessage();
return FALSE;
}
}
The put controller:
Class PutController extends Controllers\Controller {
public function updateRecord() {
$user = new Users($this->configManager('Database'));
$this->data['user'] = $this->app->request->post();
$password = trim($this->app->request->post('password'));
$passwordConfirm = trim($this->app->request->post('password-confirm'));
if((!empty($password) || !empty($passwordConfirm)) && ($password != $passwordConfirm)){
$this->app->errors += ["Password and the confirmation are different"];
return;
}
$user->update($this->args['id'], $this->app->request->post());
$this->app->errors += $user->getErrors();
}
}
And finally the route:
$this->app->group('/update/:id', function () {
// Display the page to update a user
$this->app->map('/', function ($id) {
$data = new Users\GetController( 'updateView', ['id' => $id] );
$data->send("Users/update.template.html");
})->via('GET');
// Post request to update a user
$this->app->map('/', function ($id) {
$data = new Users\PutController( 'updateRecord', ['id' => $id] );
if(!empty($this->app->errors)) {
$this->app->flashNow("errors", $this->app->errors);
$data->send("Users/update.template.html");
} else {
$this->app->flash("success", "Successfully updated the user.");
$this->app->redirect('../');
}
})->via('POST', 'PUT');
});
And last but not least, the twig form:
<form action="" method="POST">
<div class="form-group">
<label for="firstname">Firstname</label>
<input value="{{user.firstname}}" type="text" class="form-control" id="firstname" name="firstname" placeholder="Firstname">
</div>
<div class="form-group">
<label for="lastname">Lastname</label>
<input value="{{user.lastname}}" type="text" class="form-control" id="lastname" name="lastname" placeholder="Lastname">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input value="{{user.email}}" type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password">New password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<div class="form-group">
<label for="password-confirm">Confirm your password</label>
<input type="password" class="form-control" id="password-confirm" name="password-confirm" placeholder="Password">
</div>
<input type="submit" value="Submit" class="btn btn-default">
</form>
I have no idea how to get past this error. I've tried adding freeze(true) but it did not work.
Same thing for debug, i set it to true/false and nothing changed.
If anybody has tips on how to solve this, i would be extremely greatful !
Thank you!
I actually solved my problem on my own with Davide's comment that sparked an idea.
It was a silly mistake: The equals() function from RedBean actually checks for the bean's type and that's where the problem was.
One of my bean had the type 'Users' (with capital) and the other 'users' (no capital) which was causing the exception.
Thanks to Davide for the spark! :)
I am working on a website where i need to insert & fetch user data into the database. I have created a custom template where i am able to fetch the data but when i try to insert it shows me the alert box with the error msg "object Object".
Customized template code is as follows:
<?php
/*
Template Name: Customers
*/
get_header(); ?>
<div id="primary">
<div id="content" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php
if (is_user_logged_in()):?>
<form type="post" action="" id="newCustomerForm">
<label for="name">Name:</label>
<input name="name" type="text" />
<label for="email">Email:</label>
<input name="email" type="text" />
<label for="phone">Phone:</label>
<input name="phone" type="text" />
<label for="address">Address:</label>
<input name="address" type="text" />
<input type="hidden" name="action" value="addCustomer"/>
<input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>
<br/><br/>
<?php
global $wpdb;
$customers = $wpdb->get_results("SELECT * FROM customers;");
echo "<table>";
foreach($customers as $customer){
echo "<tr>";
echo "<td>".$customer->name."</td>";
echo "<td>".$customer->email."</td>";
echo "<td>".$customer->phone."</td>";
echo "<td>".$customer->address."</td>";
echo "</tr>";
}
echo "</table>";
else:
echo "Sorry, only registered users can view this information";
endif;
?>
<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: newCustomerForm,
success:function(data){
jQuery("#feedback").html(data);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
}
</script>
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div><!-- #primary -->
In functions.php i have added the following code:
/*
Following function recieves data from the user
*/
wp_enqueue_script('jquery');
function addCustomer(){
global $wpdb;
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address = $_POST['address'];
if($wpdb->insert('customers',array(
'name'=>$name,
'email'=>$email,
'address'=>$address,
'phone'=>$phone
))===FALSE){
echo "Error";
}
else {
echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id;
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
Thanks in advance.
In your ajax function you didn't include/send which action should be invoked that you registered using add_action and that is addCustomer, here is an example
var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: newCustomerForm + '&action=' + addCustomer, // <==
success:function(data){
jQuery("#feedback").html(data);
},
error: function(errorThrown){
alert(errorThrown);
}
});
I have a view with a username, password and a submit button. This view is called login.ctp, so the way I had it previous to CakePHP was I had a <div> at the top of the page and in that <div> the login would be visible through out all the pages so basically you can log in from anywhere, I was using AJAX. My issue now is that I do not know how to do it in CakePHP because some of the other views have a <form> tag, and I think it needs a <form> tag for the login too? so they conflict..Also, so two things
How can I place that div back at the top of the page and make it work with my login function in the UsersController ?
How can I do it so that the <forms> do not conflict?
related code
<?php
class UsersController extends AppController {
var $uses = array("User");
var $components = array('Auth', 'Session');
function index()
{
$this->set('users', $this->User->find('all'));
$this->layout = 'master_layout';
}
function beforeFilter() {
$this->Auth->allow('add');
}
function add() {
if (!empty($this->data)) {
//pass is hashed already
//->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your were registered!.');
$this->redirect(array('action' => 'index'));
}
}
$this->layout = 'master_layout';
}
//IF THE DATABASE IS SET UP CORRECTLY CAKE AUTHENTICATES AUTOMATICALLY NO
//LOGIC IS NEEDED FOR LOGIN http://book.cakephp.org/view/1250/Authentication
function login() {
$this->layout = 'master_layout';
$this->data['User']['password'] = '';
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
?>
This is pretty simple. If you want to form to repeat across more than just one page, you should use an element. Create the loginform.ctp file in the app/views/elements folder and just put a <?php echo $this->element('loginform'); ?> wherever you want it. In your loginform.ctp file, you should have something like this:
<div id="loginform">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('email', array('label' => 'Email')) ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
As long as you specify which controller and action the form is for, Cake will take care of it so that the forms do not conflict.
If that doesn't work, try just the html:
<form id="UserLoginForm" method="post" action="/users/login" accept-charset="utf-8"><div style="display:none;"><input type="hidden" name="_method" value="POST" /></div><ul>
<li><div class="input text required"><label for="UserEmail">Email</label><input name="data[User][email]" type="text" class="field text large" maxlength="255" value="" id="UserEmail" /></div></li>
<li><div class="input password"><label for="UserPassword">password</label><input type="password" name="data[User][password]" class="field text large" value="" id="UserPassword" /></div></li>
<li><div class="submit"><input type="submit" value="Submit" /></div></li>
</ul>
</form>
Fatal error: Can't use function return
value in write context in line 3,
In which cases such errors get triggered?
My program:
//QUERY VARIABLE
$query="select * form user where user_name='$user_name' and user_password='sha($user_password)'";
//ESTABLISHING CONNECTION
$result=mysqli_query($dbc,$query)or die('Error Querying Database');
while($row=mysqli_num_rows($result)==1)
{
//SET COOKIE
setcookie('user_name',$row['user_name']);
setcookie('user_id',$row['id']);
$query="select * form user";
$result=mysqli_query($dbc,$query)or die('Error Querying Database');
$page_url='http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/index.php';
header('Location'.$page_url);
}
//TERMINATING CONNECTION
mysqli_close($dbc);
}
else
{
$error_msg='Please type both user name and password correctly to login';
}
//}
}
else
{
$page_url='http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/register.php';
header('Location'.$page_url);
}
}
if($output_form)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Mismatch - Log In</title>
<link rel="stylesheet" href="stylesheets/style.css" media="all" />
</head>
<body class="body_style">
<?php
echo('<label class="signin_label">'.$error_msg.'</label>');
?>
<h2>Mismatch - Where Matches Happen...</h2>
<fieldset>
<legend>Mismatch - Log In</legend>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>"><!--Self Referencing Form-->
<label class="signin_label">USER NAME</label>
<input type="text" name="user_name" title="Enter Your Account User Name" class="signin_textbox" value="<?php if(!empty($_POST['user_name']))$_POST['user_name']; ?>" /><br />
<label class="signin_label">PASSWORD</label>
<input type="password" name="user_pwd" title="Enter Your Account Password" class="signin_textbox" value="" /><br />
</fieldset>
<input type="submit" name="login_submit" title="Click To Log In" value="Log In" class="button" />
<?php
}
?>
</body>
</html>
Try changing
if(!isset($_COOKIE(user_id)))
to
if(!isset($_COOKIE['user_id']))
^^ ^^
$_COOKIE is an associative array.
Try to look here
Weird PHP error: 'Can't use function return value in write context'
Maybe it helps!
I've tidied up your code here:
<?php
//CLEAR THE ERROR MESSAGE
$error_msg = '';
//CHECK TO SEE IF COOKIE IS SET
if ( ! isset($_COOKIE['user_id']))
{
$output_form = TRUE;
if (isset($_POST['login_submit']))
{
//GRAB DATA
$user_name = $_POST['user_name'];
$user_password = $_POST['user_pwd'];
if ( ! empty($user_name) && ! empty($user_password))
{
//DATABASE CONNECTION VARIABLE
$dbc = mysqli_connect('localhost','root','','mismatch') or die('Error Connecting To Database');
//QUERY VARIABLE
$query = 'SELECT id FROM `user` WHERE user_name = \''.mysql_real_escape_string($user_name).'\' and user_password = \''.sha($user_password).'\'';
//ESTABLISHING CONNECTION
$result = mysqli_query($dbc,$query) or die('Error Querying Database');
if (mysql_num_rows($result)) {
$row = mysql_fetch_assoc($result);
//SET COOKIE
setcookie('user_name', $user_name);
setcookie('user_id', $row['id']);
header('Location: /index.php');
die();
}
else {
$error_msg = 'Please type both user name and password correctly to login';
}
//TERMINATING CONNECTION
mysqli_close($dbc);
}
else {
$error_msg = 'Please type both user name and password correctly to login';
}
}
else {
header('Location: /register.php');
die();
}
}
if ($output_form)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Mismatch - Log In</title>
<link rel="stylesheet" href="stylesheets/style.css" media="all" />
</head>
<body class="body_style">
<?php
echo '<label class="signin_label">'.$error_msg.'</label>';
?>
<h2>Mismatch - Where Matches Happen...</h2>
<fieldset>
<legend>Mismatch - Log In</legend>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"><!--Self Referencing Form-->
<label class="signin_label">USER NAME</label>
<input type="text" name="user_name" title="Enter Your Account User Name" class="signin_textbox" value="<?php if(!empty($_POST['user_name'])) echo $_POST['user_name']; ?>" /><br />
<label class="signin_label">PASSWORD</label>
<input type="password" name="user_pwd" title="Enter Your Account Password" class="signin_textbox" value="" /><br />
</fieldset>
<input type="submit" name="login_submit" title="Click To Log In" value="Log In" class="button" />
</body>
</html>
<?php
}
?>
Some problems I can remember finding:
$_COOKIE(user_id) instead of $_COOKIE['user_id']
No escaping on MySQL input
Big problem with your while() clause. I've replaced this with an if and mysql_fetch_assoc()
SQL queries said form not FROM
There were some others too that I've probably forgotten about.
Enjoy!