I need to import the values of emailaddress and fullname from html into my SQL table.
Here is my HTML:
<!DOCTYPE html>
<head>
<title>Julian's Newsletter</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link href="newsletter.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
<body>
<h1>Newsletter</h1>
<form action="formsubmit.php" method="post">
<div class="container">
<h2>Subscribe to my Newsletter</h2>
<p>Subscribe to my newsletter to recieve recent news, a specialy curated product list, and the Product of the Month.</p>
</div>
<div class="container" style="background-color:white">
<input type="text" placeholder="Name" name="fullname" required>
<input type="text" placeholder="Email address" name="emailaddress" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Monthly Newsletter
</label>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
</form>
</body>
And here is my PHP so far. I am a beginner and I have very little knowledge of PHP.
<?php
$servername = "localhost";
$emailaddress = "emailaddress";
$fullname = "fullname";
$dbname = "email_windowsisslow_com";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $fullname, $emailaddress);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO emaillist (emailaddress, fullname)
VALUES ('', '')";
// 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;
?>
I am new to Stack Overflow and I do not assume that anyone will actually write the code for me. I need help understanding what is written, and how to write the code to perform the action I require of it.
I would suggest you must use prepared statements to avoid SQL injection.
$stmt = $conn->prepare("INSERT INTO emaillist (emailaddress, fullname)
VALUES (:emailaddress , :fullname)");
$stmt->bindParam(':emailaddress ', $emailaddress );
$stmt->bindParam(':fullname ', $fullname );
$stmt->execute();
In your PHP file change the two lines:
$emailaddress = "emailaddress";
$fullname = "fullname";
To
$emailaddress = $_POST["emailaddress"];
$fullname = $_POST["fullname"];
And add to your insert statement
$sql = "INSERT INTO emaillist (emailaddress, fullname) VALUES ({$emailaddress}, {$fullname})";
Related
PHP only adding Numbers to MySQL in column of VARCHAR instead of texts
when using query directly in MySQL it works...but if I use $_POST from HTML, IT fails
I don't know the reason how it is getting failed. what is the problem here ?
<?php
$link=mysqli_connect("localhost","root","","home_ac");
if(mysqli_connect_error()) {
die("error in database");
}
$name =$_POST["name"];
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,$name)";
if(mysqli_query($link, $query)){
echo "done";
}
else {
echo "failed";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<input type="text" placeholder="enter a name" name="name">
<input type="submit" value="add">
</form>
</body>
</html>
You need quotes around text
$query = "INSERT INTO `test`(`number`, `name`) VALUES (NULL,'$name')";
Please, think about prepared query. It solve quotes problem and protect from SQL injection.
You have to use PHP Prepared Statements or PHP Data Objects (PDO).
For example, using PDO:
<html>
<head>
<meta charset="utf-8">
<title> Example PDO Insert </title>
</head>
<body>
<form method="post" action="" name="myForm" id="myForm">
<input type="text" placeholder="Enter Your Name" name="name" required="required">
<input type="submit" name="submit" value="add">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "home_ac";
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);
if ( isset($_POST['submit']) && !empty($_POST['name']) ) {
# code...
$sql = "INSERT INTO test (number,name) VALUES (NULL,'$name')";
// 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;
?>
I have created a html register page which is really basic and requires the user to enter their First name, Last name, email, and password. However only the first and last names are being recorded in the database in phpmyadmin and the email and passwords are showing as blank cloumns. I have tried to drop and add the tables and columns again without any luck, i have changed variable names and no luck as well. Not too sure what to do.
Php code
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password_ = $_POST['password_'];
if (isset($_POST['register'])) {
register($first_name,$last_name,$_email,$password,$conn);
}
$conn->close();
function register($first_name,$last_name,$email,$password,$conn) {
// echo $first_name . " " . $last_name . " " . $student_id . " " . $email;
$sql = "INSERT INTO `register` (`first_name`, `last_name`, `email`, `password_`) VALUES ('$first_name', '$last_name', '$email', '$password_')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
html code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<form role="form" action="register.php" method="POST">
<div class="form-group">
<label>First Name:</label>
<input type="text" class="form-control" id="first_name" name="first_name"required>
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" class="form-control" id="last_name" name="last_name"required>
</div>
<div class="form-group">
<label>Email address:</label>
<input type="varchar" class="form-control" name="e_mail" id="email"required>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" id="password" name="password"required>
</div>
<div class="form-group">
<label>Confirm Password:</label>
<input type="password" class="form-control" id="confirm_password"required >
<script>
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
</div>
<button type="submit" class="btn btn-default" name="register">Register</button>
</form>
</body>
</html>
In order to grab the _POST variables, your input forms must have a name attribute. For your Email form, you have only specified an ID and no name. Go back and add in the name='email' attribute and it should work. Same for password.
It looks like i was missing an underscore in the php register code where it states the function. i have added it and now my code seems to be working, thanks for all the feedback!
I have two tables, members and games. In members is data such as member_id, first_name, last_name, etc.
What I'm trying to do is create a form for games, where the user can input the first and last names of the member who participated (in one string, not separately) and some PHP code queries this name, finds the corresponding id and stores this instead. Of course, member_id is a foreign key in games, but the users aren't going to know the member's id, they will only know their name.
If anyone could explain how I might go about doing this I would greatly appreciate it.
Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
</head>
<body>
<form action="action.php" method="post">
<p>
<label for="date">Date:</label>
<input type="date" name="date" id="date">
</p>
<p>
<label for="duration">Duration:</label>
<input type="time" name="duration" id="duration">
</p>
<p>
<label for="member_id">Member Name:</label>
<input type="text" name="member_id" id="member_id">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Action:
<?php
// database connection
include 'pdo_config.php';
try {
// new pdo connection
$conn = new PDO($dsn, $user, $pass, $opt);
// prepare statement and bind parameters
$stmt = $conn->prepare("INSERT INTO games (date, duration, member_id)
VALUES (:date, :duration, :member_id)");
$stmt->bindParam(':date', $date);
$stmt->bindParam(':duration', $duration);
$stmt->bindParam(':member_id', $member_id);
// post data
$date = $_POST['date'];
$duration = $_POST['duration'];
$member_id = $_POST['member_id'];
// execute statement
$stmt->execute();
// success or error message
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
This should work.
Ask the user to input the member name in the form instead of the member id. Then make a first query to the database to get the member id from the member name.
Have in mind that it's not a good idea to search the member id from its name, because you could have more than one member whit the same name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
</head>
<body>
<form action="action.php" method="post">
<p>
<label for="date">Date:</label>
<input type="date" name="date" id="date">
</p>
<p>
<label for="duration">Duration:</label>
<input type="time" name="duration" id="duration">
</p>
<p>
<label for="member_name">Member Name:</label>
<input type="text" name="member_name" id="member_name">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
// database connection
include 'pdo_config.php';
try {
// new pdo connection
$conn = new PDO($dsn, $user, $pass, $opt);
// post data
$date = $_POST['date'];
$duration = $_POST['duration'];
// Note that the explode only works well if user inputs one blank space to separate the name
// You can try to improve the separation method or better use two different inputs in the form
$nameArray = explode(" ", $_POST['member_name']);
$first_name = $nameArray[0];
$last_name = $nameArray[1];
$statement = $conn->prepare("SELECT member_id FROM members WHERE first_name = :first_name AND last_name = :last_name");
$statement->execute(array(':fisrt_name' => $first_name, ':last_name' => $last_name));
$row = $statement->fetch();
$member_id = $row['member_id'];
// prepare statement and bind parameters
$stmt = $conn->prepare("INSERT INTO games (date, duration, member_id)
VALUES (:date, :duration, :member_id)");
$stmt->bindParam(':date', $date);
$stmt->bindParam(':duration', $duration);
$stmt->bindParam(':member_id', $member_id);
// execute statement
$stmt->execute();
// success or error message
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
I'm new to PHP and still trying to get my head round it. this form says that the data has been sent to the database but when I look the database is empty, no errors are showing up? is there a problem with my code.
Note: I understand that this form is not protected from SQL Injection.
HTML
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Page 3 Form</h2><hr/>
<span id="error">
</span>
<form action="page4_insertdata.php" method="post">
<label>Company Name :<span>*</span></label><br />
<input name="company_name" type="text" placeholder="Joes Cleaner" required>
<br />
<label>Ref :<span>*</span></label><br />
<input name="ref" type="text" placeholder="H123" required>
<br />
<label>Website :<span>*</span></label><br />
<input name="website" type="text" placeholder="www.google.com" required>
<br />
<label>Email :<span>*</span></label><br />
<input name="email" type="email" placeholder="Joescleaners#gmail.com" required>
<br />
<label>Telephone :<span>*</span></label><br />
<input name="tel" type="text" placeholder="07123456789" required>
<br />
<label>Message :<span>*</span></label><br />
<input name="message" id="message" type="text" size="500" required>
<br />
<input type="reset" value="Reset" />
<input name="submit" type="submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
PHP
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2><hr/>
<?php
$servername = "localhost";
$db_database = 'form';
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "DB Connected successfully. ";
$company_name = $_POST['company_name'];
$ref = $_POST['ref'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$sql = "INSERT INTO detail (company_name,ref,website,email,tel,message)
VALUES ('$company_name','$ref','$website','$email','$tel','$message')";
if($sql){
echo " Database Sent.";
}
else {
echo "ERROR to insert into database";
};
?>
</div>
</div>
</body>
</html>
Change the following code:
if($sql){
echo " Database Sent.";
}
else {
echo "ERROR to insert into database";
};
To:
$result = $conn->query($sql);
if($result){
echo " Database Sent.";
}
else {
echo "ERROR to insert into database";
};
This way you are actually performing the query and checking on failure of query...
To make your query a bit safer, try the following:
$sql = "
INSERT INTO detail (
company_name,
ref,
website,
email,
tel,
message
)
VALUES (
'" . mysqli_real_escape_string($company_name) . "',
'" . mysqli_real_escape_string($ref) . "',
'" . mysqli_real_escape_string($website) . "',
'" . mysqli_real_escape_string($email) . "',
'" . mysqli_real_escape_string($tel) . "',
'" . mysqli_real_escape_string($message) . "'
)";
Better yet, use binding of params by replace the $sql instantiation and query execution ($conn->query()) with the following:
$stmt = $conn->prepare("INSERT INTO detail (company_name,ref,website,email,tel,message) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $company_name, $ref, $website, $email, $tel, $message);
$stmt->execute();
You can read up on binding parameters with mysqli by visiting PHP: mysqli_stmt::bind_param - Manual
Complete code:
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2><hr/>
<?php
$servername = "localhost";
$db_database = 'form';
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $db_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "DB Connected successfully. ";
$stmt = $conn->prepare("INSERT INTO detail (company_name,ref,website,email,tel,message) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss',
$_REQUEST['company_name'],
$_REQUEST['ref'],
$_REQUEST['website'],
$_REQUEST['email'],
$_REQUEST['tel'],
$_REQUEST['message']
);
if($stmt->execute()) {
echo " Database Sent.";
} else {
echo "ERROR to insert into database: " . $stmt->error;
};
?>
</div>
</div>
</body>
</html>
You arent actually sending a query, you are setting the variable $sql = "INSERT....."
which is always true.
you need to do:
$result = $mysqli->query($sql);
if ($result......)
SOLVED - ANSWER ADDED AT THE BOTTOM OF THE POST
Please can someone help me out as I can´t understand what the heck I am doing wrong.
I have a html form with 2 fields "title" and "message". I´m trying to get this to go into the database with PDO and $_POST but I am just getting this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null' in
I´m doing everything by the book but it´s not working and I going to throw my computer out the window soon. So please anyone have any idea what is wrong? Why is title turning "NULL"?
The database is a 4 column table (id, title, message and timestamp). The id field is primary and auto intent
ANY help is really appreciated!!! And I´m a beginner...
Here is post.php file:
<?php
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post" action="post.php" enctype="text/plain">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>
And here is the connect.inc.php file:
<?php
class DB extends PDO
{
public function __construct($dbname = "blogdata")
{
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8";
parent::__construct($dsn, "root", "", $opt);
}
}
?>
ANSWER:
This issue was finally solved. The problem is you need to check if $_POST is empty or not. And right after the if (!empty($_POST)) { set the require 'connect.inc.php';. Also to minimize code do like Dave Just said, change :
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
To:
$stmt->execute(array(':title' => $_POST['title'], ':message' => $_POST['message']));
Here is the working code in post.php:
<?php
if (!empty($_POST)) {
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message) VALUES (:title, :message)");
$stmt->execute(array(':title' => $_POST['title'], ':message' => $_POST['message']));
$title = $_POST['title'];
$message = $_POST['message'];
// Redirect to index.php
header ('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>
If you haven't thrown the computer out the window already, you should've checked whether $_POST vars were set or not before passing them to a PDO execute statement.
<?php
require 'connect.inc.php';
if( isset($_POST['title'], $_POST['message']) ) {
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
}
?>
PS
I have no idea what $time would do there.