Add Data to MySQL Database from an HTML Form - mysql

HI all i've a basic Web Form for putting data into a mysql database, I created code to report if i was connected to my Database correctly and it was so on completion of the form i tested it and it seems to do what i expected but when i goto my database no data was actually entered?
my form
<form class="form-horizontal" name="myForm" method="POST" action="data.php" onsubmit="return(validate())">
<div class="container-fluid">
<div class="row">
<div class="col-md-5" style=" margin-left:5%">
<div class="form-group" >
<input type="text" class="form-control" name="Name" placeholder="Enter your name!">
</div>
<div class="form-group">
<input type="email" class="form-control" name="Email" placeholder="Enter email">
</div>
<div class="form-group">
<input type="password" class="form-control" name="Pass" placeholder="Enter password">
</div>
</div>
<div class="col-md-5" style="float:right; margin-right:5%">
<div class="form-group">
<input type="number" class="form-control" name="Num" onsubmit="return(phonenumber(myForm.Num))" placeholder="Enter phone no.">
</div>
<div class="form-group">
<input type="text" class="form-control" name="Comment" placeholder="Any comments?">
</div>
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
data.php
<?
define('DB_NAME', 'Demo');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
if( $_POST )
{
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Demo", $con);
$Name1 = $_POST['Name'];
$Email1 = $_POST['Email'];
$Pass1 = $_POST['Pass'];
$Num1 = $_POST['Num'];
$Comment1 = $_POST['Comment'];
$Name = mysql_real_escape_string($Name);
$Email = mysql_real_escape_string($Email);
$Pass = mysql_real_escape_string($Pass);
$Num = mysql_real_escape_string($Num);
$Comment = mysql_real_escape_string($Comment);
$sql = "
INSERT INTO Demo ( `Name`, `Email`, `Password`,`Contact_num`,
`Comment`) VALUES ('$Name1',
'$Email1', '$Pass1', '$Num1','$Comment1'
)";
mysql_query($sql);
mysql_close($con);
}
?>

<?php
$dbhost = "localhost";
$dbuser = "root";
$conn = mysql_connect($dbhost , $dbuser);
mysql_select_db("Demo",$conn);
$Name1 = $_POST['Name'];
$Email1 = $_POST['Email'];
$Pass1 = $_POST['Pass'];
$Num1 = $_POST['Num'];
$Comment1 = $_POST['Comment'];
echo $Name1.$Email1.$Pass1.$Num1.$Comment1; //this is to check whether you are getting all the values or not.
$sql = "INSERT INTO TABLENAME ( `Name`, `Email`, `Password`,`Contact_num`, `Comment`) VALUES ('$Name1',
'$Email1', '$Pass1', '$Num1','$Comment1'
)";
mysql_query($sql);
mysql_close($con);
}
?>
Kindly consider that the Insert Query should have the name of the table, not the database.

Related

how to make wordpress plugin form text field take numbers

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>

contact info not sending to phpmyadmin

I am facing issues connecting to database or creating database connection. My localhost is not sending any data to the database, it doesn't show any errors either. Could you help me? All of the files were originally downloaded, I changed a few stuff, didn't work originally.
My database name is amazon and the table name is contact_form_info. Below is my connection and html file.
get_response.php
<?php //temp
require 'config.php';
$conn = Connect();
$contactname = $_POST['name'];
$contactEmail = $_POST['Email'];
$contactMessage = $_POST['Message'];
$query = "INSERT INTO contact_form_info ('nome', 'email', 'message') VALUES ('$contactname', '$contactEmail', '$contactMessage')";
// $stmt = $conn->prepare($query);
// $stmt->bind_param("sss", $_POST['contactname'], $_POST['contactEmail'], $_POST['contactMessage']);
/* Execute the statement */
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo "Obrigado por nos contactar. <br>";
printf("rows inserted: %d\n", $stmt->affected_rows);
} else {
echo "Erro ao inserir dados";
}
/* close statement */
$stmt->close();
$conn->close();
?>
config.php
function Connect()
{
$host = "localhost";
$userName = "username";
$password = "password";
$dbName = "amazon";
// Create database connection
$conn = new mysqli($host, $username, $password, $dbName) or die($conn->connect_error);
return $conn;
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
html form
<form name="contactForm" id="contactForm" method="post" action="">
<fieldset>
<div class="row">
<div class="six columns mob-whole">
<label for="contactname">Nome <span class="required">*</span></label>
<input name="contactname" type="text" id="contactname" placeholder="Nome" value="" />
</div>
<div class="six columns mob-whole">
<label for="contactEmail">Email <span class="required">*</span></label>
<input name="contactEmail" type="text" id="contactEmail" placeholder="Exemplo#host.com" value="" />
</div>
</div>
<div class="row">
<div class="twelve columns">
<label for="contactMessage">Message <span class="required">*</span></label>
<textarea name="contactMessage" id="contactMessage" placeholder="Mensagem" rows="10" cols="50" ></textarea>
</div>
</div>
<div>
<button class="submit full-width">Enviar</button>
<div id="image-loader">
<img src="images/loader.gif" alt="" />
</div>
</div>
</fieldset>
</form>

How to connect my Login/Register for with MySQL database?

I started coding my website that we are gonna use to run business with my friend but i dont know how to connect my Login/Register page to mySQL database(running on xampp control panel with Apache server and MySQL server).
Any solution would be helpful. Thank you.
Login:
<link rel="stylesheet" type="text/css" href="loginstyle.css">
<form action="action_page.php">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
Register:
<link rel="stylesheet" type="text/css" href="registerstyle.css">
<form action="action_page.php">
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<hr>
<p>By creating an account you agree to our Terms & Privacy.</p>
<button type="submit" class="registerbtn">Register</button>
</div>
<div class="container signin">
<p>Already have an account? Sign in.</p>
</div>
</form>
You will need to add PHP
Connect.php
<?php
/* Database connection settings */
$host = '';
$user = '';
$pass = '';
$db = '';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
?>
Add This to a different page with the extension to .php and Change action File to Login.php
Login.Php
session_start();
include("db.php");
if (isset($_POST['uname']) && isset ($_POST['pse'])) {
$username = $mysqli->escape_string($_POST['pse']);
$result = $mysqli->query("SELECT * FROM TABLE WHERE username='$username'");
if ( $result->num_rows == 0 ){
$_SESSION['message'] = "User with that email doesn't exist!";
echo '<script language="javascript">';
echo 'alert("'.$_SESSION['message'].'")';
echo '</script>';
}
else {
$user = $result->fetch_assoc();
if ( password_verify($_POST['Password'], $user['password']) ) {
$_SESSION['email'] = $user['email'];
$_SESSION['active'] = $user['active'];
$_SESSION['logged_in'] = true;
header("location: System/index.php");
}
else {
$_SESSION['message'] = "You have entered wrong password!";
echo '<script language="javascript">';
echo 'alert("'.$_SESSION['message'].'")';
echo '</script>';
}
}
}
?>
Add This to a different page with the extension to .php and Change action File to Register.php
Register.php
<?php
session_start();
include("db.php");
if (isset($_POST['email']) && isset ($_POST['psw']) && isset ($_POST['psw-repeat'])){
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$password-repeat= $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$result = $mysqli->query("SELECT * FROM TABLE WHERE email='$email'") or die($mysqli->error());
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
header("location: error.php");
}
if( $password !== $password-repeat){
$_SESSION['message'] = 'Password dont match';
header("location: error.php");
}
else {
$sql = "INSERT INTO TABLE( email, password)"
. "VALUES ('$first_name','$last_name','$email','$password', '$hash')";
header("location: index.php");
}
?>

contact form set focus on submission

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.

Having an issue inputting values into DB with PDO

So this is the PHP code that processes the form info and it supposed to send data into the DB. It is successful every time and shoots me a success message but when I look in database I see a new row but no actual data from the form.
REMINDER: the db connection is working, except it's sending blank values to fill up the table as opposed to the form data.
Here is the HTML form to be handled by the PHP code in dealer.php:
<form action="dealer.php" method="POST">
<div class="form-group">
<label for="company">Company Name</label>
<input type="text" class="form-control" id="company" name="company" placeholder="Company Name">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" id="location" name="location" placeholder="Location">
</div>
<div class="form-group">
<label for="founded">Founded</label>
<input type="text" class="form-control" id="founded" name="founded" placeholder="Founded">
</div>
<div class="form-group">
<label for="employees"># of Employees</label>
<input type="text" class="form-control" id="employees" name="employees" placeholder="# of employees">
</div>
<div class="form-group">
<label for="employees"># of Employees</label>
<input type="text class="form-control" id="sales" name="sales" placeholder="2014 sales">
</div>
<div class="radio">
<label><p>Is the company traded publicly?</p>
<input type="radio" name="optionsRadios" name="public" id="Yes" value="Yes">
Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" name="public" id="No" value="No">
No
</label>
</div>
<div class="form-group">
<label class="sr-only" for="gross_2014">Gross Revenue</label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="text" class="form-control" id="gross_2014" name="gross_2014" placeholder="Gross Revenue">
<div class="input-group-addon">.00</div>
</div>
</div>
<div class="form-group">
<label class="sr-only" for="net_2014">Net Revenue</label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="text" class="form-control" id="net_2014" name="net_2014" placeholder="Net Revenue">
<div class="input-group-addon">.00</div>
</div>
</div>
<div class="form-group">
<label class="sr-only" for="growth_2014">Growth(%)</label>
<div class="input-group">
<div class="input-group-addon">%</div>
<input type="text" class="form-control" id="growth_2014" name="growth_2014" placeholder="Growth %">
<div class="input-group-addon">.00</div>
</div>
</div>
<textarea class="form-control" rows="3"></textarea>
<div class="form-group">
<p class="help-block" id="customer" name="customer">Customer profile info... </p>
</div>
<textarea class="form-control" rows="3"></textarea>
<div class="form-group">
<p class="help-block" id="products" name="products">Info about product offerings.</p>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
And here are the contents of dealer.php that process the HTML form above:
<?php
$servername = "XX.XXX.XXX.XX";
$username = "smartkrawl";
$password = "Bondurant15!";
$dbname = "smartkrawl";
class companyInfo{
public $name;
public $location;
public $founded;
public $employees;
public $sales;
public $gross_2014;
public $net_2014;
public $growth_2014;
public function __construct($name,$location,$founded,$employees,$sales,$gross_2014, $net_2014, $growth_2014) {
$this->name = $name;
$this->location = $location;
$this->founded = $founded;
$this->employees = $employees;
$this->sales = $sales;
$this->gross_2014 = $gross_2014;
$this->net_2014 = $net_2014;
$this->growth_2014 = $growth_2014;
}
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO companyInfo (name, location, founded, employees, sales, gross_2014, net_2014, growth_2014)
VALUES ('$name', '$location', '$founded', '$employees', '$sales', '$gross_2014', '$net_2014', '$growth_2014')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
You didn't get the POST values in your php code, that's why the columns of the row are empty. The variables are not set.
I don't think you should use a class just to handle a form, it's unnecessary.
Since you getting this data from a form, it's good to security the use of prepared statements to insert the data. You're already using PDO, so you can just use the prepared statements without problem.
You can read about PDO Prepared Statements on PHP Manual (http://php.net/manual/en/pdo.prepared-statements.php)
I modified your code and now should be working.
<?php
$name = $_POST['company'];
$location = $_POST['location'];
$founded = $_POST['founded'];
$employees = $_POST['employees'];
$sales = $_POST['sales'];
$gross_2014 = $_POST['gross_2014'];
$net_2014 = $_POST['net_2014'];
$growth_2014 = $_POST['growth_2014'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("INSERT INTO companyInfo (name, location, founded, employees, sales, gross_2014, net_2014, growth_2014) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$sql->bindValue(1, $name);
$sql->bindValue(2, $location);
$sql->bindValue(3, $founded);
$sql->bindValue(4, $employees);
$sql->bindValue(5, $sales);
$sql->bindValue(6, $gross_2014);
$sql->bindValue(7, $net_2014);
$sql->bindValue(8, $growth_2014);
$exec = $sql->execute();
if($exec) {
echo "New record created successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
By the way, in your HTML code, there's a quote missing on this line after the type attribute.
<input type="text class="form-control" id="sales" name="sales" placeholder="2014 sales">
Replace by
<input type="text" class="form-control" id="sales" name="sales" placeholder="2014 sales">
And there's a field on the form that you didn't set on your PHP code, which is the optionsRadios radio. I didn't put that radio in the code because you didn't put it on the original code. So, if you want to put it there, just add it on the PHP like any other field.