Connecting HTML to MYSQL Through PHP [closed] - php

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));
?>

Related

Saving information to mysql table

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');

sending data from form to database not working (php, sql)

I'm making a simple registration form for a test website and for some reason it isn't sending the data to the database, and I don't get an visual error. I've searched around for a fix but haven't found any that work.
This is basically my form (I only copied the form part of the page):
<form action="includes/insert.php" method="post">
<h3>Username</h3>
<input type="text" name="username">
<br>
<br>
<h3>Email Address</h3>
<input type="email" name="email">
<br>
<br>
<h3>Password</h3>
<input type="password" name="password">
<br>
<br>
<br>
<input id="submit-btn" type="submit" name="submit" value="Submit">
</form>
As you can see everything is as its suppose to be.
and this is my insert.php
<?
define('DB_NAME', 'logindb');
define('DB_USER', 'root');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(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());
}
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "INSERT INTO `users` (`id`, `username`, `email`, `password`, `timestamp`) VALUES (NULL, '$username', '$email', '$password', CURRENT_TIMESTAMP)";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
Opening PHP tag is
<?php
Recent versions of PHP do not enable the short code syntax by default.
Use NOW() instead of CURRENT_TIMESTAMP.

Error when trying to Inserting into data into the database. Simple form

I'm new to PHP I have put together a simple form to input data into a database but the data doesn't seem to be inserting into the database. I've been trying to get it working all day.
shows the error Error to Inserting into database at the end of the code.
html
<div id="wrapper">
<section id="top_area">
<article class="box-right">
<form action="script/data.php" method="post">
<p>
<label>Company Name:</label>
<input name="company_name" required="required" placeholder="Joes Cleaners" type="text">
</p>
<p>
<label>Ref:</label>
<input name="ref_num" required="required" placeholder="D123" type="text">
</p>
<p>
<label>Website:</label>
<input name="website" required="required" placeholder="joescleaner.co.uk" type="text">
</p>
<p>
<label>Email:</label>
<input name="email" required="required" placeholder="joescleanersm#gmail.com" type="email">
</p>
<p>
<label>Telephone:</label>
<input name="tel" required="required" placeholder="0712345678" type="number">
</p>
<p>
<label>Message:</label>
<input name="message" required="required" placeholder="hello" type="text">
</p>
<p>
<input value="Submit" type="submit">
</p>
</form>
</article>
</section>
</div>
PHP
<?php
$db_hostname = 'localhost';
$db_database = 'form';
$db_username = 'user';
$db_password = 'password';
// Connect to server.
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());
// Select the database.
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
// Select the database.
mysql_select_db("form")
or die("Unable to select database: " . mysql_error());
// Get values from form
$company_name = $_POST['company_name'];
$ref_num = $_POST['ref_num'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
// Insert data into mysql
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message)
VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message, NOW())";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
header('Location: ../thankyou.php');
}
else {
echo "Error to Inserting into database";
}
// close mysql
mysql_close();
?>
You should start using PDO for DB access, mysql_query is deprecated.
PDO let's you make prepared statements. These are secured against SQL Injections (your code isn't).
$stmt = $dbh->prepare("INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES (:company_name, :ref_num, :website, :email, :tel, :message, NOW())");
$stmt->bindParam(':company_name', $company_name);
$stmt->bindParam(':ref_num', $ref_num);
// And bind the remaining parameters
[...]
$stmt->execute();
If this fails, you can get detailed informations by running
print_r($stmt->errorInfo());
That should help you with finding errors in your SQL.
$dbh is a new PDO instance (see PDO::__construct)
As in your query you are trying to insert more than column values.
Your query is :
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message, NOW())"
Either remove NOW() data or add another column for NOW() data
Also you can try below query.
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message)"
When fixed column errors like Programming Student says, you should modify your mysql_query command:
it needs the db connection you opened before.
Try this:
$result = mysql_query($db_server, $sql);
Why don't try Object Oriented syntax ?
if ($db_server->query($sql) === TRUE) {
header('Location: ../thankyou.php'); } else {
echo "Error: " . $conn->error;
}
}

(HTML,PHP,MySQL) Ensure I have everything I need, Submitting Form Data

I need to send my database over to the guy who has the server for a website that I'm managing. Problem is, I'm just now starting to learn PHP and MySQL after only really knowing HTML and CSS. I need to have a form submit data such as FirstName, LastName, Date of Birth, Telephone and etc. through PHP to a MySQL database. Security isn't highly important, as no credit card numbers or anything like that will be going through. But, I'd still like to know how to get the data secure.
Inside of my database, I have a table with all of the entries I need, (FirstName,LastName, DateofBirth, etc.) and I now need to send it to him, so it will be able to store information for the website it self. Here is the problem, I am not exactly sure I am going about the coding portion the correct way.
Here is my HTML:
<html>
<body>
<form action="insert.php" method="post">
<label>First Name: </label><input type="text" name="FirstName">
<label>Last Name:</label> <input type="text" name="LastName"> <br>
<label>Date of Birth:</label> <input type="date" name="DateofBirth">
<label>Telephone:</label> <input type="tel" maxlength="10" name ="Telephone">
<input type="submit">
</form>
</body>
</html>
Here is insert.php
<?php
$con=mysqli_connect("host","username","password","database");
if (mysqli_connect_errno())
{
echo "Error, please try again later.";
}
$sql="INSERT INTO table (FirstName, LastName, DateofBirth, Telephone)
VALUES
('$_POST[FirstName]',
'$_POST[LastName]',
'$_POST[DateofBirth]',
'$_POST[Telephone]')";
if (!mysqli_query($con,$sql))
{
die('Error, please try again later.';
}
echo "Successful";
mysqli_close($con);
?>
Is this correct? Will it work the way that I am needing it to, to where I can pull the information from the table later on? Am I missing any highly crucial components of what I need?
Your code is not correct. $_Post[''] is not directly put in query and this is wrong way to insert data. You should be get data by variables. I have make insert file with database connection file please try this
$host = "hostname";
$user = "username";
$pwd = "password";
$db = "databasename";
$connect = mysql_connect($host, $user, $pwd) or die('Could not connect');
$db = mysql_select_db($db);
$firstname = $_REQUEST['FirstName'];
$lastname = $_REQUEST['LastName'];
$date = $_REQUEST['DateofBirth'];
$telephone = $_REQUEST['Telephone'];
$sql="INSERT INTO `table` (`FirstName`, `LastName`, `DateofBirth`, `Telephone`)VALUES('".$firstname."','".$lastname."','".$date."','".$telephone."')";
if (!mysqli_query($con,$sql))
{
die('Error, please try again later.');
}else{
echo "Successful";
}

PHP to MySQL Code problems

I know there a lot of questions on MySQL and PHP but I can't seem to find an answer simple enough for me to understand what to do and why.
Here is my form script
<form name="tickets" action="tickets98829849.php" method="get">
First Name: <input type="text" name="firstname"><br>
Last Name: <input type="text" name="lastname"><br><br>
Number of Tickets: <input type="text" name="quant"><br><br>
First and Last Name of Date: <input type="text" name="date"><br>
Date a guest? <input type="checkbox" name="guest" value="Yes">Yes<br><br>
Amount paid per ticket: <br><br>
$<input type="text" name="amount" size="2"><br>
<br><input type="submit" value="Submit"></form>
and here is my PHP script
<?php
define('DB_NAME', 'ticketpurch');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'dbpsswd');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
if (!$link) {
die('Could not connect: ' . mysqlerror());
}
$db_selectd = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysqlerror());
}
$value1 = $_POST['firstname']
$value2 = $_POST['lastname']
$value3 = $_POST['quant']
$value4 = $_POST['datename']
$value5 = $_POST['guest']
$value6 = $_POST['amount']
$sql = "INSERT INTO $table ticketpurch (firstname, lastname, quant, datename, guest, amount) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$result = mysql_query($sql)
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
>
When I use the form, the data does not get entered into the table. I do not get an error message. What is wrong with it for not letting me access the table and insert data? I am very new to php, so
Your form's submit method is get but you receive post method. Change it.
In form you mention method="get" change it to method="post"
It will work :)
Remove the $table from the statement. I'm assuming the correct table is ticketpurch, so all you did with $table was confuse the database. In addition, the other answers are also correct. Your form's method is "get," yet you're using $_POST to try to get the data. You should change the form to post, because get is incredibly insecure, especially if this involves purchases.
In addition, you're using deprecated functions like mysql_connect. Instead, use the PDO object. Instead of mysql_connect(), try this:
$table = "mytable";
$sql = new PDO;
$sql->__construct(DB_NAME, DB_USER, DB_PASS);
$stmnt = $sql->prepare("INSERT INTO ticketpurch (firstname, lastname, quant, datename, guest, amount) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$sql->execute($stmnt);
That will ensure that your statements are better secured against SQL injection.
Hope that helped.
Try Like this.
HTML CODE
<form name="tickets" action="tickets98829849.php" method="post">
First Name: <input type="text" name="firstname"><br>
Last Name: <input type="text" name="lastname"><br><br>
Number of Tickets: <input type="text" name="quant"><br><br>
First and Last Name of Date: <input type="text" name="date"><br>
Date a guest? <input type="checkbox" name="guest" value="Yes">Yes<br><br>
Amount paid per ticket: <br><br>
$<input type="text" name="amount" size="2"><br>
<br><input type="submit" value="Submit"></form>
tickets98829849.php code
<?php
define('DB_NAME', 'ticketpurch');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'dbpsswd');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
if (!$link) {
die('Could not connect: ' . mysqlerror());
}
$db_selectd = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysqlerror());
}
$value1 = $_POST['firstname']
$value2 = $_POST['lastname']
$value3 = $_POST['quant']
$value4 = $_POST['datename']
$value5 = $_POST['guest']
$value6 = $_POST['amount']
$sql = "INSERT INTO $table ticketpurch (firstname, lastname, quant, datename, guest, amount) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$result = mysql_query($sql)
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
>
If you use method="get" in the form,then receive html values using $_GET['html element name'];.But for security purpose ,we generally use method="post" in html code and receive value in action page using $_POST[];.

Categories