I am unable to insert de data into mysql using angular. If i want to fetch data in mysql it works ok, but this doesn't work.
I can't see the error. Can you help me?
this is my html form:
<form #suscribir="ngForm">
<div class="modal-body bodycolabora">
<label class="labelmodal">Recibe nuestros correos para estar al tanto de los últimos post y recursos subidos.</label>
<div class="md-form mb-2">
<label class="labelmodal">Tu nombre*</label>
<input class="form-control" type="text" name="nombre" class="input" placeholder="Tu nombre" [(ngModel)]="datos.nombre" required minlength="3" #nameInput="ngModel">
</div>
<div *ngIf="nameInput.invalid && (nameInput.dirty || nameInput.touched)"
class="alert alert-danger">
<div *ngIf="nameInput.errors.required">
Escribe tu nombre.
</div>
<div *ngIf="nameInput.errors.minlength">
Name must be at least 4 characters long.
</div>
</div>
<div class="md-form mb-2">
<label class="labelmodal">Email*</label>
<input class="form-control" type="email" name="email" class="input" placeholder="Tu email" [(ngModel)]="datos.email" required email #emailInput="ngModel">
</div>
<div *ngIf="emailInput.invalid && (emailInput.dirty || emailInput.touched)"
class="alert alert-danger">
<div *ngIf="emailInput.errors.required">
Escribe tu email.
</div>
</div>
<!--Privacidad-->
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="aceptopolitica" name="privacidad" value="acepto" ngModel required #privacidadInput="ngModel">
<label class="labelmodal" class="form-check-label" for="infantil" name="etapa" >Acepto la Política de privacidad</label>
</div>
<div *ngIf="privacidadInput.invalid && (privacidadInput.dirty || privacidadInput.touched)"
class="alert alert-danger">
<div *ngIf="privacidadInput.errors.required">
Acepta la política de privacidad
</div>
</div>
</div>
<div class="modal-footer footercolabora d-flex justify-content-center">
<button (click)="suscriptores()" value="Nuevo suscriptor" type="submit" name="submit" id="submit" class="btn btncolabora" [disabled]="suscribir.invalid">Enviar →</button>
</div>
</form>
In my component.ts i have:
datos={
nombre:null,
email:null
}
constructor(private articulosServicio: ServicioService) {
}
suscriptores() {
this.articulosServicio.suscriptores(this.datos).subscribe(datos => {
if (datos['resultado']=='OK') {
alert(datos['mensaje']);
}
});
In the service.ts:
url='http://xxxxxxxxxxx/'; //
constructor(private http: HttpClient) { }
suscriptores(datos) {
return this.http.post(`${this.url}suscriptores.php`, JSON.stringify(datos));
}
and finally the file.php,
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Content-Type: application/json');
$json = file_get_contents('php://input');
$params = json_decode($json);
require("conexion.php");
$con=retornarConexion();
$email = mysqli_real_escape_string($con, $params->email);
$nombre = mysqli_real_escape_string($con, $params->nombre);
$query= 'INSERT INTO newsletter(email, nombre) VALUES ("' . $email . '","'. $nombre .'")';
if(mysqli_query($con, $query))
{
class Result {}
$response = new Result();
$response->resultado = 'OK';
$response->mensaje = 'datos grabados';
}
else
{
class Result {}
$response = new Result();
$response->resultado = 'OK';
$response->mensaje = 'datos grabados';
}
header('Content-Type: application/json');
echo json_encode($response);
?>
Sorry for all the code but i think you might need id to see the error
Related
I have a form in a plugin I am creatingin wordpress. The form is a simple test form and it has a hidden field and two text fields. If I enter a number into the text fields, it doesn't process it when I hit submit, it takes to me a page that says
It looks like nothing was found at this location. Maybe try a search?
here is the entire plugin showing the form and the action that processes the form.
<?php
/*
plugin name: deano plugin
description: deano test database to insert data into books table
author: Dean-O
*/
$path = preg_replace('/wp-content.*$/', '', __DIR__);
require_once($path.'/wp-load.php');
function deanoinsertdata() {
/**
* Dean-O database insert book function
*/
global $wpdb;
if(isset($_POST['submitbtn'])){
error_log('I am here');
$data=array(
'wp_id'=>$_POST['wp_id'],
'title'=>$_POST['title'],
'author'=>$_POST['author'],
);
$table_name = 'books';
$foundOne = 1;
error_log('table_name = '.$table_name);
error_log('foundOne = '.$foundOne);
/*$wp_idin = $_POST['wp_id'];
$titlein = $_POST['title'];
$authorin = $_POST['author'];
*/
$wp_idin = $data['wp_id'];
$titlein = $data['title'];
$authorin = $data['author'];
error_log('wp_idin = '.$wp_idin);
error_log('titlein = '.$titlein);
error_log('author = '.$authorin);
/*
see if the record is already in the table
*/
$sql = "select * from books";
print $sql;
$results = $wpdb->get_results($sql);
foreach($results as $result) {
if($result->wp_id==$wp_idin && $result->title==$titlein && $result->author==$authorin)
{
$foundOne = 0;
error_log('foundOne = 0');
}
}
//error_log('logged message');
if($foundOne==1) {
error_log('foundOne = 1 before insert');
$resultinsert = $wpdb->insert($table_name,$data);//, $format=NULL);
error_log('insert executed');
error_log('resultinsert = '.$resultinsert);
//wp_redirect( "http://localhost/tadpolewp/deano-plugin--duplicate-records/" );
//exit();
if($resultinsert==1) {
//header('Location: http://localhost/tadpolewp/deano-plugin-successful/');
error_log( 'successful' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-successful/" );
exit();
http://localhost/tadpolewp/deano-plugin-successful/
//error_log('Book saved 1');
//echo "Book Saved 1";
} else {
//header('Location: http://localhost/tadpolewp/deano-plugin-failed/');
error_log( 'failed to save' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-failed/" );
exit();
//error_log('unable to save');
//echo "Unable to Save";
}
} else {
//error_log('Duplicate record found');
//echo "Duplicate recortd found";
//header('Location: http://localhost/tadpolewp/deano-plugin-duplicate-records/');
error_log( 'duplicate record' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-duplicate-records/" );
exit();
}
}
?>
<form role="form" method="post">
<div class="form-group">
<?php
// get current user ID, with default value, if empty
$current_user_id = get_current_user_id();
?>
<input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" />
</div>
<div class="form-group">
<label>Field 1</label><br>
<input id="title" name="title" type="text" placeholder="<?php echo esc_attr( $current_user_id ); ?>" required="">
</div>
<div class="form-group">
<label>Field 2</label><br>
<input id="author" name="author" type="text" placeholder="Primary Author" required="">
</div>
<div class="row justify-content-center">
<div class="col-xs-4 col-sm-4 col-md-4">
<br><input type="submit" value="Submit1" class="btn btn-info btn-block" name="submitbtn">
</div>
</div>
</form>
<?php
}
add_shortcode('deanoputdatain','deanoinsertdata');
?>
The only way I can get the Field 1 or Field 2 to take numbers is to change them to type="number"
Is there a varchar type that I can use?
My database has the field set as a varchar.
Thanks in advance
Dean-O
You should be set action for your form.
For example: 'test.php' or '/'.
It worked well for me. I rewrite your code here:
<form role="form" method="post" action="{your menu slug}">
<div class="form-group">
<?php
// get current user ID, with default value, if empty
$current_user_id = get_current_user_id();
?>
<input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" />
</div>
<div class="form-group">
<label>Field 1</label><br>
<input id="title" name="title" type="text" placeholder="<?php echo esc_attr( $current_user_id ); ?>" required="">
</div>
<div class="form-group">
<label>Field 2</label><br>
<input id="author" name="author" type="text" placeholder="Primary Author" required="">
</div>
<div class="row justify-content-center">
<div class="col-xs-4 col-sm-4 col-md-4">
<br><input type="submit" value="Submit1" class="btn btn-info btn-block" name="submitbtn">
</div>
</div>
</form>
I'm trying to access and use the data from my service and having some issues. I am able to see the data returned just fine in the console from my console.log(data); from the method below:
public getCustomerData() {
this.Service.getCustomers().subscribe((data) => {
console.log(data);
this.customers = data.value;
console.log(this.customers);
var i:number;
for(i = 0; i < this.customers.length; i++ ){
if(this.customers[i].CityName == null || this.customers[i].StateName == null || this.customers[i].ZipCode == null || this.customers[i].Address1 == null){
this.customers[i].Address1 = "";
this.customers[i].CityName = "San Diego";
this.customers[i].StateName = "California";
this.customers[i].ZipCode = "12345";
}
}
})
}
Where I am running into issues is the next line this.customers = data.value;, I am recieving the error Property 'value' does not exist on type 'Customer[]'.
Here is how my data is returned:
Service method:
public getCustomers()
{
let url = "https://rss-staging.carefusion.com/api/odata/Facilities";
const params = new HttpHeaders()
.set('X-Atlas-SecurityKey', '75162FD1-A4E8-40AB-A62A-823932CEAD1F')
return this.http.get<Customer[]>(url, {headers: params})
}
HTML Table:
<div class="row pb-2">
<div class="col-lg-4">
<div class="form-group">
<label for="input1">Name</label>
<input type="text" placeholder="Customer Name" class="form-control" id="input1"
aria-describedby="Text field" name="name" [(ngModel)]="fields.Name"
(ngModelChange)="updateFilters()" />
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<label for="input1">Address</label>
<input type="text" placeholder="Customer Address" class="form-control" id="input1"
aria-describedby="Text field" name="address" [(ngModel)]="fields.Address1"
(ngModelChange)="updateFilters()" />
</div>
</div>
</div>
<div class="row pb-2">
<div class="col-lg-3">
<div class="form-group">
<label for="input1">City</label>
<input type="text" placeholder="City" class="form-control" id="input1" aria-describedby="Text field"
name="city" [(ngModel)]="fields.CityName" (ngModelChange)="updateFilters()" />
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label for="input1">State</label>
<input type="text" placeholder="State" class="form-control" id="input1" aria-describedby="Text field"
name="name" [(ngModel)]="fields.StateName" (ngModelChange)="updateFilters()" />
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label for="input1">Zip Code</label>
<input type="text" placeholder="123456" class="form-control" id="input1" aria-describedby="Text field"
name="name" [(ngModel)]="fields.ZipCode" (ngModelChange)="updateFilters()" />
</div>
</div>
</div>
How can I fix this?
From the code, I can see that you have typecasted the result of the function getCustomers() to customers[]
return this.http.get<Customer[]>(url, {headers: params})
Basically you are returning an array of customers from the http call.
To return correct value, pipe the results and map
import { map } from 'rxjs/operators'
return this.http.get<any>(url, {headers: params}).pipe(
map(data => data.value as Customer[])
)
Your method getCustomers() from the service already return a list of customers, and a list doesn't have a property called value.
You only have to do this, and should works.
this.customers = data;
my php function is not working when im add my text area in form. other all input or working. if im add remark(text area) in form edit function cant show text in that remark. other input is visible but i cant save it again
please help me to fined my error
Code before "html"
<?php
function renderForm($id, $vehicle_type, $duration, $amount,$remarks, $error)
{
?>
my HTML form
<form action="" method="post">
<div class="row">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div class="col-lg-4 col-xs-6" class="form-group">
<label>Vehicle Type <span style="color:red;font-size:8px;"><i class="fa fa-asterisk" aria-hidden="true"></i></span></label>
<select name="vehicle_type" class="form-control">
<option <?php echo ($vehicle_type=='Bicycle')?'selected':'' ?>>Bicycle</option>
<option <?php echo ($vehicle_type=='Bike')?'selected':'' ?>>Bike </option>
<option <?php echo ($vehicle_type=='Cars')?'selected':'' ?>>Cars </option>
<option <?php echo ($vehicle_type=='Truck')?'selected':'' ?>>Truck</option>
<option <?php echo ($vehicle_type=='Others')?'selected':'' ?>>Others</option>
</select>
</div>
<div class="col-lg-4 col-xs-6" class="form-group">
<label>Duration </label> <span style="color:red; font-size:8px; "><i class="fa fa-asterisk" aria-hidden="true"></i></span>
<input type="text" value="<?php echo $duration; ?>" name="duration" class="form-control" maxlength="20" placeholder="Eg: 4 Hrs">
</div>
<div class="col-lg-4 col-xs-6" class="form-group">
<label><i class="fa fa-inr" aria-hidden="true"></i> Amount</label> <span style="color:red;font-size:8px;"><i class="fa fa-asterisk" aria-hidden="true"></i></span>
<input type="number" name="amount" value="<?php echo $amount; ?>" class="form-control" placeholder="00">
</div>
</div>
<div class="row">
<div class="col-lg-4 col-xs-6" class="form-group">
<label>Remarks</label>
<textarea class="form-control" name="remarks" <?php echo htmlspecialchars($remarks); ?> rows="3" placeholder="Enter ..."></textarea>
</div>
<div id="butn" class="col-lg-3 col-xs-3">
<button class="myButton" type="submit" name="submit" value="Submit" class="btn btn-block btn-success btn-lg">SAVE</button>
</div>
</div>
</form>
Code after "html"
<?php
}
// connect to the database
include('connection.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$vehicle_type = mysql_real_escape_string(htmlspecialchars($_POST['vehicle_type']));
$duration = mysql_real_escape_string(htmlspecialchars($_POST['duration']));
$amount = mysql_real_escape_string(htmlspecialchars($_POST['amount']));
$remarks = mysql_real_escape_string(htmlspecialchars($_POST['remarks']));
if ($vehicle_type=='' || $duration=='' || $amount=='' || $remarks=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $vehicle_type, $duration, $amount, $remarks, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE price_normal SET vehicle_type='$vehicle_type', duration='$duration', amount='$amount', remarks='$remarks', WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: pnormal.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM price_normal WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$vehicle_type = $row['vehicle_type'];
$duration = $row['duration'];
$amount = $row['amount'];
$remarks = $row['remarks'];
// show form
renderForm($id, $vehicle_type, $duration, $amount, $remarks,'');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
Take a look at the actual HTML in your browser. You're rendering the "remarks" content as an attribute of the textarea element:
<textarea class="form-control" name="remarks" <?php echo htmlspecialchars($remarks); ?> rows="3" placeholder="Enter ..."></textarea>
It should be the content of that element:
<textarea class="form-control" name="remarks" rows="3" placeholder="Enter ..."><?php echo htmlspecialchars($remarks); ?></textarea>
I have a form which contains several fields including the upload file button that I want to use as an image uploader, (<input type="file" name="image" id="image" class='image'>). Other fields works fine and uploads everything on the database, however, in the image field, the filename of the file I uploaded is giving me this file name:
C:\laragon\tmp\php859A.tmp
... What should I do? Thank you: ) Here are the codes:
this is the form:
<html>
<div class="col-md-offset-4 col-md-4">
<form action="{{ $action }}" method="POST" enctype="multipart/form-data">
<h1> {{ $header }} </h1>
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name" value="{{ $name }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Description</label>
<input type="text" class="form-control" id="description" name="description" placeholder="Description" value="{{ $description }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Price</label>
<input type="number" class="form-control" id="product_price" name="product_price" placeholder="Price" value="{{ $product_price }}">
</div>
<div class="form-group">
<label for="image">SELECT IMAGE TO UPLOAD</label><br>
<input type="file" name="image" id="image" class='image'>
</div>
<div class="col-md-offset-2">
{!! csrf_field() !!}
<button type="submit" class="btn btn-default col-md-5" style="background:#0099ff; color:#f2f2f2;">{{ $button }}</button>
<button type="submit" class="btn btn-default col-md-5" style="background:#f4f4f4; color:#000;">Cancel</button>
</div>
</form>
</div>
</html>
These are my functions Create and Store in the controller:
public function create()
{
$data['action'] = route('beverage_store');
$data['button'] = 'Add';
$data['header'] = 'ADD BEVERAGE';
$data['name'] = old('name');
$data['description'] = old('description');
$data['product_price'] = old('product_price');
$data['image'] = old('image');
return view('layouts.beverages.beverageform',$data);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();
#dd($input);
BeveragesModel::create($input);
return redirect()->route('beverages');
}
:)
Assuming you store the filename only on your database table, then you have to upload image somewhere else. So you could create something like:
private function upload($request)
{
$image_name = '';
if($request->hasFile('image'))
{
$image = $request->file('image');
$image_name = md5(uniqid()) . '.' . $image->getClientOriginalExtension();
$image->move(public_path() . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'beverages' . DIRECTORY_SEPARATOR, $image_name);
}
return $image_name;
}
public function store(Request $request)
{
$image_name = $this->upload($request);
$input = $request->all();
$beverage = BeveragesModel::create($input);
$beverage->image = $image_name;
$beverage->save();
return redirect()->route('beverages');
}
i have a bootstrap one page with a contact form in the end. I would like on submission to focus on that section and not at the beginning of the page.
So, if the message was send, the users will see the OK message, else they will read the error.
here is my code.
Html
<section id="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2 class="heading">Contact</h2>
<div class="row">
<div class="col-md-12">
<?php
$to = 'mail#mail.mm';
$subject = 'Enquiry from the website';
$contact_submitted = 'Your message was submitted and will be responded to as soon as possible. Thank you for contacting us.';
function email_is_valid($email) {
return preg_match('/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i',$email);
}
if (!email_is_valid($to)) {
echo '<p style="color: red;">You must set-up a valid (to) email address before this contact page will work.</p>';
}
if (isset($_POST['contact_submitted'])) {
$return = "\r";
$youremail = trim(htmlspecialchars($_POST['your_email']));
$yourname = stripslashes(strip_tags($_POST['your_name']));
$yourmessage = stripslashes(strip_tags($_POST['your_message']));
$contact_name = "Name: ".$yourname;
$message_text = "Message: ".$yourmessage;
$user_answer = trim(htmlspecialchars($_POST['user_answer']));
$answer = trim(htmlspecialchars($_POST['answer']));
$message = $contact_name . $return . $message_text;
$headers = "From: ".$youremail;
if (email_is_valid($youremail) && !eregi("\r",$youremail) && !eregi("\n",$youremail) && $yourname != "" && $yourmessage != "" && substr(md5($user_answer),5,10) === $answer) {
mail($to,$subject,$message,$headers);
$yourname = '';
$youremail = '';
$yourmessage = '';
echo '<p style="color: blue;">'.$contact_submitted.'</p>';
}
else echo '<p style="color: red;">Please enter your name, a valid email address, your message and the answer to the simple maths question before sending your message.</p>';
}
$number_1 = rand(1, 9);
$number_2 = rand(1, 9);
$answer = substr(md5($number_1+$number_2),5,10);
?>
<form id="contact" action="contact.php" method="post">
<div class="form_settings">
<div class="form-group">
<label for="Name :">Your firstname *</label>
<input type="text" name="your_name" placeholder="Enter your firstname" required="required" class="form-control">
</div>
<div class="form-group">
<label for="Email Address :">Your email *</label>
<input type="email" name="your_email" placeholder="Enter your email" required="required" class="form-control">
</div>
<div class="form-group">
<label for="Message :">Your message for us *</label>
<textarea rows="4" name="your_message" placeholder="Enter your message" required="required" class="form-control"></textarea>
</div>
<p style="line-height: 1.7em;">To help prevent spam, please enter the answer to this question :</p>
<p><span><?php echo $number_1; ?> + <?php echo $number_2; ?> = ?</span><input type="text" name="user_answer" /><input type="hidden" name="answer" value="<?php echo $answer; ?>" /></p>
<p style="padding-top: 15px"><span> </span><input class="submit" type="submit" name="contact_submitted" value="send" /></p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
Thank you very much in advance.
Use AJAX in the html to call php.