Saving information to mysql table - php

So I want to create an html form and save it to a databas in WordPress
First I created the form which I put on this page here
<form action="addperson.php" method="post">
<label>First Name:</label>
<input type="text" name="firstname"/><br>
<label>Last Name:</label>
<input type="text" name="lastname"/><br>
<label>Email:</label>
<input type="text" name="email"/><br>
<input type="submit" name=submit value="Submit"/>
</form>
Then, in public html-->wp-content-my theme I created a file called addperson.php
In this file I put the following code :
<?php
//Block 1
$user = "user"; //Enter the user name
$password = "password"; //Enter the password
$host = "host"; //Enter the host
$dbase = "database"; //Enter the database
$table = "table"; //Enter the table name
//Block 2
$firstname= $_POST['firstname_entered'];
$lastname= $_POST['lastname_entered'];
$email= $_POST['email_entered'];
//Block 3
$connection= mysql_connect ($host, $user, $password);
if (!$connection){
die ('Could not connect:' .
mysql_error());
}
mysql_select_db($database, $connection);
//Block 4
$username_table= mysql_query( "SELECT username FROM $table WHERE username= '$username'" ) or die("SELECT Error: ".mysql_error());
//Block 5
mysql_query("INSERT INTO $table (column1, column2, column3) VALUES (value1, value2, value 3)");
//Block 6
echo 'You have been added.';
//Block 7
mysql_close($connection);
?>
Then I created a database and a table email_list like so:
CREATE TABLE IF NOT EXISTS
email_list (first_name VARCHAR(50),
last_name VARCHAR(50), email VARCHAR
(50));
Next, I entered info into formhere
It saved absolutely nothing.
Where am I going wrong?

Look at your HTML.
<input type="text" name="firstname"/>
<input type="text" name="lastname"/>
<input type="text" name="email"/>
And after submiting form, that data will be under firstname, lastname, email keys in $_POST array.
So you probably should change this
$firstname = $_POST['firstname_entered'];
$lastname = $_POST['lastname_entered'];
$email = $_POST['email_entered'];
to this
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
You should also consider enabling errors displaying in php to get more info about your potentials mistakes.
// Put this on top of your php file
ini_set('display_errors', '1');

Related

Register Form PHP not inserting values into DB, just reloading the page

I really can not find what am I doing wrong in my registration form, unfortunately the page is just reloading instead of inserting values from form to my DB table.
Register.php
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}
}
?>
Connection.php
<?php
$conn = mysqli_connect("localhost","root","","KBHestate");
if(!$conn){
die("Connection error: " . mysqli_connect_error());
}
Register Form
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="firstName" value="" placeholder="First Name">
<input type="text" name="lastName" value="" placeholder="Surname">
<input type="text" name="email" value="" placeholder="Email">
<input type="text" name="phone" value="" placeholder="Phone">
<input type="password" name="password" value="" placeholder="Password">
<button type="submit" name="submit">Submit</button>
</form>
Please make sure the following line has no problem when it is interpreted by the PHP:
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
On the other hand, please make sure that the password field is wide enough to store the $hasPassword data
Your code looks fine, it should work. I am hoping you are having Register form in the same file Register.php
But as you mentioned it's just reload the page that means there must be a exception/error from mysql query that is not handled in your code.
You have not shared your table structure. So, I am answering you based on the common mistake.
Like one of your table column width is varchar(10) and you are trying to pass data of length 20 char.
So, i suggest you to add below code in your Register.php as the else condition for if($result). So, it will display the error if any.
else {
echo("Error description: " . $conn->error);
}
Now your Register.php code will be look like below:
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}else {
echo("Error description: " . $conn->error);
}
}
?>

Insert data from html form

im new to HTML and PHP. I am trying to create a form which loads my new users details into a database hosted by my web hosting company.
my form code (HTML) is :
<h1>Create Your GoSense Account</h1>
<form method:"POST" action:"newuserform.php" >
<div class="namef">
Name: <input type="text" style="width:200px" name="Name"
placeholder="First Name"><br></br> </div>
<div class="surnamef">
Surname: <input type="text" style="width:178px" name="Surname"
placeholder="Last Name"><br></br></div>
<div class="emailf">
Email: <input type="text" style="width:202px" name="Email"
placeholder="Email"><br></br> </div>
<div class="passwordf">
Password: <input type="text" style="width:170px" name="Password"
placeholder="Password"><br></br></div>
<input type="submit" style="font-size: 300px" name=""
value="Submit">
</form>
my PHP code stored in newuserform.php is:
<?php
define('DB_NAME','gosensec_useraccounts');
define('DB_USER','MyUsername');
define('DB_PASSWORD','myPassword');
define('DB_HOST','***.**.**.**');
$Name = filter_input(INPUT_POST,'Name');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
$db_selected = mysql_select_db (DB_NAME, $link) ;
$VALUE = $_POST['Name'];
$VALUE = $_POST['Surname'];
$VALUE = $_POST['Email'];
$VALUE = $_POST['Password'];
$sql = " INSERT INTO Users (Name) VALUES ('$VALUE')";
$sql = " INSERT INTO Users (Surname) VALUES ('$VALUE')";
$sql = " INSERT INTO Users (Email) VALUES ('$VALUE')";
$sql = " INSERT INTO Users (Password) VALUES ('$VALUE')";
mysql_close()
?>
I have doubled checked the connection parameters with my db host company and they advised that it is correct so my next step is to question my code ? Can anyone pick any errors that could be causing the data to insert into my DB ?
Many Thanks
There are multiple mistakes.
1- Assign each variable to a specific name:
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
2- insert all values into a single row not multiple rows.Also concatnate the variables as variables not as strings inside quotes!
$sql = "INSERT INTO Users (Name,Surname,Email,Password) VALUES ('" .$Name. "','". $Surname ."','". $Email ."','" .$Password. "')";
3- Do not forget to execute sql command:
$link->query($sql)
4- To close the connection use mysql_close($link)
finally: Do not forget to prevent SQL INJECTION by filtering values. Also try mysqli instead of the discontinued mysql API.

Data won't pass from HTML form to Database

I'm new to PHP and I'm not sure what I'm doing wrong. I can open the html form and give the data but when I hit submit it shows me the php code and the database is (obviously) not updated. I have tried inserting values to the table manually through phpMyAdmin and it works. I have looked online but me syntax looks fine (to me). Am I doing some different wrong? If the mistake is not too obvious is there an efficient way to debug (ie see the errors)?
I have this HTML code
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Hotel Start Page</title>
</head>
<body>
<form action="customerCreate.php" method="post">
<fieldset><legend>Enter your information in the form below:</legend>
<header align="center"> <b>Customer Sign Up</b></header>
<p><b>Surname: </b><input type="text" name="surname" size="30" maxlength="40"/></p>
<p><b>Name: </b><input type="text" name="name" size="30" maxlength="40"/></p>
<p><b>E-mail: </b><input type="text" name="email" size="30" maxlength="40"/></p>
<p><b>Telephone: </b><input type="text" name="tel" size="30" maxlength="10"/></p>
<p><b>Password: </b><input type="password" name="passwd" size="30" maxlength="10"/></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Create Account"/></div>
</form>
</body>
This PHP code
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$db = 'my_hotel';
$conn = new mysqli($host,$username,$password,$db);
if ($conn->connect_error) {
die("Connection Error: " .$conn->connect_error);
}
$sname = $_POST['surname'];
$name = $_POST['name'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$passwd = $_POST['passwd'];
$sql = "INSERT INTO Customer (sname, name, email, tel, passwd) VALUES
(?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss",$sname,$name,$email,$tel,$passwd);
$stmt->execute();
$cid = "SELECT cid FROM Customers WHERE sname='$sname' AND passwd='$passwd' ";
$result = $conn->query($cid);
$row = $result->fetch_assoc();
echo "Customer Added.<br>";
echo "Your Customer ID is ".$row['cid'];
$stmt->close();
$conn->close();
?>
And this table in a database called My_hotel in phpMyAdmin
CREATE TABLE Customer (
cid INT AUTO_INCREMENT,
sname VARCHAR(15),
name VARCHAR(15),
email VARCHAR(15),
tel VARCHAR(15),
passwd VARCHAR(15),
PRIMARY KEY (cid)
);
If you get the php code, it must be that your application is not in your web server, so the browser downloads the source file. You should copy/synchronize your files into/with (probably) /var/www/html.
Look into this: http://thisinterestsme.com/php-displayed-in-browser/

Connecting HTML to MYSQL Through PHP [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm working on a website but I'm a little unsure how to proceed. I've read through some documentation but I think I'm missing something or looking into the wrong stuff. Basically, I have a website with a bunch of pages and a few pages that have forms. I'm trying to tackle my first form, register, which contains a register form. Here is the form that the user will fill out to register:
<form action = "register.php" method = "post">
<br><br>First Name:<br>
<input type="text" name="firstname">
<br>
Last Name:<br>
<input type="text" name="lastname">
<br>
Street Address:<br>
<input type="text" name="streetaddress"> <br>
City:<br>
<input type="text" name="city"> <br>
State:<br>
<input type="text" name="state"> <br>
Zip Code:<br>
<input type="text" name="zipcode"> <br>
Phone Number:<br>
<input type="text" name="phonenumber"> <br>
Email Address:<br>
<input type="text" name="emailaddress"> <br>
User Name:<br>
<input type="text" name="username"> <br>
Password:<br>
<input type="text" name="password"> <br>
<br>Would you like to receive emails about CSIT World Conference?<br>
<input type="radio" name="email" value="yes">Yes
<input type="radio" name="email" value="no">No
<br><br>Would you be interested in volunteering at CSIT World Conference??<br>
<input type="radio" name="help" value="yes">Yes
<input type="radio" name="help" value="no">No
<br><br>
<input type="submit" value="Submit">
</form>
I thought it should then send the data to register.php which looks like this.
define('DB_NAME', 'register');
define('DB_USER', 'root');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_NAME, DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$streetaddress = $_POST['streetaddress'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phonenumber = $_POST['phonenumber'];
$emailaddress = $_POST['emailaddress'];
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "INSERT INTO register (firstname, lastname, streetaddress, city, state, zipcode, phonenumber, emailaddress, username, password) VALUES ('$firstname', '$lastname', '$streetaddress', '$city', '$state', '$zipcode', '$phonenumber', '$emailaddress', '$username', '$password')";
$result = mysql_query($sql);
mysql_close();
</script>
</html>
I also created an empty MYSQL database through phpmyadmin on XAMPP. Basically I'm trying to figure out if I'm on the right track. My understanding is that once I hit submit, it should populate the register.mysql table I created. However, nothing seems to be happening.
Also, here is my connect.php file
<html>
<head>
</head>
<body>
<?php
$con = mysql_connect("localhost","root","password");
if(!$con){
die("Cannot connect:".mysql_error());
}
mysql_close($con);
?>
</body>
</html>
Any help or direction would be greatly appreciated.
You shouldn't use the mysql_* functions because they are deprecated. It's better to try to learn PDO but for this example you can use mysqli_*. Also, check about hashing passwords. I hope you find the following code useful.
<?php
define('DB_NAME', 'register');
define('DB_USER', 'root');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_set_charset($link, 'utf8');
if (!$link) {
die("Database connection failed: " . mysqli_error($link));
}
//Use array to not repeat code
$post_vars = array('firstname', 'lastname', 'streetaddress', 'city', 'state', 'zipcode', 'phonenumber', 'emailaddress', 'username', 'password');
foreach($post_vars as $key) {
$$key = mysqli_real_escape_string($link, $_POST[$key]);
//For example now there is a variable $firstname that you can use
}
$sql = "INSERT INTO user (firstname, lastname, streetaddress, city, state, zipcode, phonenumber, emailaddress, username, password) VALUES ('$firstname', '$lastname', '$streetaddress', '$city', '$state', '$zipcode', '$phonenumber', '$emailaddress', '$username', '$password');";
$result = mysqli_query($link, $sql);
mysqli_close($link);
?>
Edit:
You can select your data like this (consider also trying the PDO code that the other answer has).
$query = "SELECT username, firstname, lastname FROM user;";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row['username'].'<br />';
}
EDIT 2
The SQL for user table is the following. Edit it accordingly.
CREATE TABLE IF NOT EXISTS user (
id int unsigned not null auto_increment,
firstname varchar(40),
lastname varchar(40),
username varchar(40),
password varchar(40),
state varchar(40),
city varchar(40),
streetaddress varchar(40),
zipcode varchar(40),
phonenumber varchar(40),
emailaddress varchar(255),
email tinyint unsigned default 1,
help tinyint unsigned default 1,
time_created timestamp default CURRENT_TIMESTAMP,
primary key(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I would advise the same! use PDO and make sure you "PREPARE" your statements, I've re-written your data using PDO. By preparing our data we can prevent SQL injection which could have adverse affects on your data integrity as well as give unwanted users access to your tables.
<?php
// config
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "register";
$dbuser = "root";
$dbpass = "password";
// Connection Info
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// Write Query
$sql = "INSERT INTO books (firstname,lastname,streetaddress,city,state,zipcode,phonenumber,emailaddress,username,password) VALUES (firstname,:lastname,:streetaddress,:city,:state,:zipcode,:phonenumber,:emailaddress,:username,:password)";
// Prepare Statement
$q = $conn->prepare($sql);
$q->execute(array(':firstname'=>$firstname
':lastname'=>$lastname
':streetaddress'=>$streetaddress
':city'=>$city
':state'=>$state
':zipcode'=>$zipcode
':phonenumber'=>$phonenumber
':emailaddress'=>$emailaddress
':username'=>$username
':password'=>$password));
?>

Connecting form to SQL Database

I am able to connect to mysql database however I can not display data from my form to my database. I am not sure why this is happening but I have been able to retrieve data from my database I just can not enter information into it. For now I am just trying to enter First_Name. I also get no errors when entering in data to the form. Any help would be greatly appreciated!!
<p>
<form name="input1" action="http://seanfagan.webuda.com/Final/club.php" method="post">
First_Name:<input type="text" name="First_Name"><br>
Last_Name: <input type="text" name="Last_Name"><br>
Club_Name: <input type="text" name="Club_Name"><br>
Email: <input type="text" name="Email"><br>
Club_Type: <input type="text" name="Club_Type"><br>
Members: <input type="text" name="Members"><br>
<input type="submit" value="Send"><br>
</form>
<?php
$mysql_host = "mysql14.000webhost.com";
$mysql_database = "a9576602_Final";
$mysql_user = "a9576602_Final";
$mysql_password = "*****![enter image description here][1]";
$mysql_error = "Could not connect to database!";
$conn = mysql_connect($mysql_host, $mysql_user, $mysql_password) or die ("$mysql_error");
$select_db= mysql_select_db('a9576602_Final') or die ("Couldn't select database!");
$value = $_Post['input1'];
$sql = "INSERT INTO Club (First_Name) VALUES ('First_Name')";
if (!mysql_query($sql)) {
die('Errorss: ' . mysql_error());
}
mysql_close();
?>
</p>
Assuming your connection with the database is okay. You can put a <name> attribute for your submit button to serve as a reference for sending your form via $_POST method:
<input type = "submit" name = "input1" value = "Submit">
Then using this, you can trigger your insert statement:
<?php
if(isset($_POST['input1']))
{
// make sure you also declare the variables in your form such as the first name, etc.
$firstName = $_POST['First_Name'];
mysql_query("INSERT INTO Club (First_Name) VALUES ('$firstName')");
}
?>
Hope this helps you :D

Categories