I learned MySQL, created a form and had it working with the database. I was then told I should be doing it PDO with prepared statements, so I did some research on that and changed my code.
I now have the code right (I think) but I can't figure out how data gets input. As you can see on my code, I have the database creating the rows as the user submits the form. However the database just picks up on whatever is within the speech marks under //insert a row and //insert another row.
For example, right now if the user completes and submits the form, no matter what information they enter, I just get 'Joe' and 'joe#example.com' etc showing in my database. Obviously I need their answers, otherwise my form would be irrelavant (as would the data submission). Have I totally missed the mark or am I missing something silly? I've tried changing and researching but am struggling. Really new to all this.
FORM:
<form action="testsubmit-pdo.php" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="city" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
PHP:
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);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO demo (stu_name, stu_email, stu_city)
VALUES (:stu_name, :stu_email, :stu_city)");
$stmt->bindParam(':stu_name', $stu_name);
$stmt->bindParam(':stu_email', $stu_email);
$stmt->bindParam(':stu_city', $stu_city);
// insert a row
$stu_name = "Joe";
$stu_email = "joe#example.com";
$stu_city = "Joeland";
$stmt->execute();
// insert another row
$stu_name = "Mary";
$stu_email = "mary#example.com";
$stu_city = "Maryland";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
Change this -
// insert a row
$stu_name = "Joe";
$stu_email = "joe#example.com";
$stu_city = "Joeland";
$stmt->execute();
// insert another row
$stu_name = "Mary";
$stu_email = "mary#example.com";
$stu_city = "Maryland";
$stmt->execute();
to this -
// insert a row
$stu_name = $_POST['stu_name'];
$stu_email = $_POST['stu_email'];
$stu_city = $_POST['stu_city'];
$stmt->execute();
Your form will place the values in PHP's POST array and you can access them by the name property from the form.
You post the data entered by the user to your php file
<form action="some_php_file.php" method="post">
<input type="text" name="stu_name">
<input type="email" name="stu_email">
<input type="text" name="stu_city">
<input type="submit" name="submit" value="submit">
</form>
and in php code, first you need to check if the submit button is clicked
//check if submit button is clicked
If(isset($_POST['submit'])){
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);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO demo (stu_name, stu_email, stu_city)
VALUES (:stu_name, :stu_email, :stu_city)");
$stmt->bindParam(':stu_name', $stu_name);
$stmt->bindParam(':stu_email', $stu_email);
$stmt->bindParam(':stu_city', $stu_city);
$stu_name = $_POST['stu_name'];
$stu_email = $_POST['stu_email'];
$stu_city = $_POST['stu_city'];
$stmt->execute();
echo "New records created successfully";
}catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
}
Related
I am trying to pinpoint the problem in these form scripts.
I would like to create a line in the SQL server with the data that will be inserted into the HTML form, but each time only the empty line is created without also inserting the form inputs.
HTML
<form action="insert2.php" method="post">
<label for="First_name">First_name:</label>
<input type="text" name="First_name" id="First_name">
<label for="PASSWORD">PASSWORD:</label>
<input type="text" name=value name="pass" id="pass">
<label for="Emailaddress">Emailaddress:</label>
<input type="text" name=value name="email" id="email">
<input name="submit" type="submit" value="Submit">
</form>
PHP
<?php
if(isset($_POST['submit'])){
$First_name = $_REQUEST['First_name'];
$pass = $_REQUEST['password'];
$email = $_REQUEST['Emailaddress'];
}
$servername = "host";
$username = "user";
$password = "";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(First_name, PASSWORD, Emailaddress)
VALUES ('$First_name', '$pass', '$email')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The posted values should be set as $_POST['ExampleField'] not just a variable with that name.
Ex: $First_name should be $_POST['First_name']
If you look in your error logs you are likely getting undefined variable errors with the code as it is now, because $First_name, $PASSWORD and $Emailaddress are never defined.
Also you should avoid directly putting variables into queries like that, it opens you up to large security risks. I would recommend reading up on SQL Injection (https://www.w3schools.com/sql/sql_injection.asp) and binding parameters (https://www.php.net/manual/en/pdostatement.bindparam.php) to see how to avoid those risks.
You need to retrieve the values after a submit of some sort. You have a submit button but you'll want to give it a name (I named it submit). This code should work but you'll be vulnerable to injection attacks.
PHP
<?php
if(isset($_POST['submit'])){
$First_name = $_REQUEST['First_name'];
$pass = $_REQUEST['PASSWORD'];
$email = $_REQUEST['Emailaddress'];
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(First_name, PASSWORD, Emailaddress)
VALUES('$First_name','$pass','$email')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
HTML
<form action="insert2.php" method="post">
<label for="First_name">First_name:</label>
<input type="text" name="First_name" id="First_name">
<label for="PASSWORD">PASSWORD:</label>
<input type="text" name="PASSWORD" id="PASSWORD">
<label for="Emailaddress">Emailaddress:</label>
<input type="text" name="Emailaddress" id="Emailaddress">
<input name="submit" type="submit" value="Submit">
</form>
Just starting out with PHP. I have code that gets user input through a form and enters the input into a mySQL table. The code has no parse errors. But when a user submits their name and email. It is not going into the table, the table is still empty, and I cannot seem to figure out the problem. Here is my code:
<div id="main">
<h1>Insert data into database using PDO</h1>
<div id="login">
<h2>Students Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="name" id="Fname" required="required" placeholder="Please Enter Your Name"/><br/><br/>
<label>Student Email :</label>
<input type="text" name="email" id="email" required="required" placeholder="Pear#gmsil.com"/><br/><br/>
<input type="submit" value=" Submit " name="submit"/><br/>
</form>
</div>
</div>
<?php
//server name
$db_hostname = "lll";
//database name
$db_database = "lll";
//username
$db_username = "lll";
$db_password = "lll;";
$db_charset = "utf8mb4";
//a string specifying the database type, the hostname and name of the database
$dsn = "mysql:host=$db_hostname;dbname=$db_database;charset=$db_charset";
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE =>PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
);
try {
//create connection
$pdo = new PDO($dsn,$db_username,$db_password,$opt);
if (isset($_POST["submit"])) {
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO students (name,email)";
VALUES ('". $_POST["name"] ."','" . $_POST["email"] . "');
if ($pdo->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Student Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
in the line of code where you write the SQL statement, you placed an extra "; before the second half of the query.
Change
$sql = "INSERT INTO students (name,email)";
VALUES ('". $_POST["name"] ."','" . $_POST["email"] . "');
to
$sql = "INSERT INTO students (name,email) VALUES ('". $_POST["name"] ."','" . $_POST["email"] . "');
This should fix the problem with your failed inserts.
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 have a user input form(HTML) that is supposed to take the information and insert it into a MySQL database via PHP. The PHP apparently executes and echoes "Your registration has completed successfully". A record is created in the database but the columns are blank(I have removed my server, database, and password from the PHP code).
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>User Portal</title>
</head>
<div class="inputContainer">
<header>
User Information Portal
</header>
<form action="php/userPost.php" method="post">
<label for=firstName">First Name</label>
<input type="text" id=firstName" name="fname">
<br><br>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lname">
<br><br>
<label for="eMail">Email</label>
<input type="text" id="eMail" name="email">
<br><br>
<label class="labelRole" for="userRole">Role -</label><br>
<input type="radio" id="userRole" name="role" value="Instructor"> Instructor
<input class="submitButton" type="submit" name="submit" value="Register">
</form>
</div>
</body>
PHP:
<?php
$sname = "server-name";
$uname = "username";
$pword = "password";
$dbname = "web_tech_test";
$conn = new mysqli($sname, $uname, $pword, $dbname);
if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
$sql = "INSERT INTO users (first_name, last_name, email, role)
VALUES ('$fname', '$lname', '$email', '$role')";
if ($conn->query($sql) === TRUE) {
echo "Your registration has completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This creates a new record in the DB but all the columns are blank. Any ideas why this may be happening?
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
this code returns a boolean, not a string value...
Use !empty() just for validation
example
if(empty($_POST['eMail'])) {
die("Email cannot be empty");
}
You're confusing the id and the name tags on the inputs.
The name tags are the ones which will be submitted as keys to your server.
Try this in your server php script after submitting your form to see which key/values are actually received by the server:
var_dump($_POST);
Also, if you want to check that all fields have been filled out, use something similar as this:
if (empty($_POST['firstName'])) {
die("firstname is empty!");
}
In your current example you're actually saving a boolean to your variables.
And, last but not least, never insert variables from a potentially unsafe source (like a user input) directly into your SQL. Use pdo: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers for this
Full code example to get you started:
//prepare your values
if (empty($_POST['fname']) || empty($_POST['lname']|| empty($_POST['email']|| !isset($_POST['role'])) {
die ("some values were empty or not set");
}
//prepare your database
$db = new PDO('mysql:host=server-name;dbname=web_tech_test;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //throw an exception if there is an error
//create your query
$stmt = $db->prepare("INSERT INTO users (first_name, last_name, email, role) VALUES (:first_name,:last_name,:email,:role)"); //create a query statement
$stmt->bindValue(":first_name", $firstName); //put your values into your statement
$stmt->bindValue(":last_name", $lastName);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":role", $role);
if ($stmt->execute()) { //execute the query
echo "Your registration has completed successfully";
} else {
echo "Error :(";
}
I am having trouble getting a record to insert into my database, I have checked the code and all the variables and names match between PHP and the database.
There are no error messages and I am getting the text saying booking was created but, no record is entered into the database.
Here is the php code for inserting the record;
<div class="containter">
<?php
if (isset($_POST['submit'])) {
try {
include ('include\PDO.php');
$sql = "INSERT INTO customers(Customer_Name, Customer_Email, Customer_Contact) VALUES (:Customer_Name, :Customer_Email, :Customer_Contact)";
//Named Parameters
$stmt = $dbh->prepare($sql);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
$Customer_Name = filter_input(INPUT_POST, 'Customer_Name');
$stmt->bindValue(':Customer_Name', $Customer_Name, PDO::PARAM_STR);
$Customer_Email = filter_input(INPUT_POST, 'Customer_Email');
$stmt->bindValue(':Customer_Email', $Customer_Email, PDO::PARAM_STR);
$Customer_Contact = filter_input(INPUT_POST, 'Customer_Contact');
$stmt->bindValue(':Customer_Contact', $Customer_Contact, PDO::PARAM_STR);
print $Customer_Contact;
print $Customer_Name;
print $Customer_Email;
$stmt->execute();
$dbh = null;
} catch (PDOException $e) {
//Error Messages
print "We have had an error: " . $e->getMessage() . "<br/>";
die();
}
?>
<p> Booking Created.</p>
<?php } else { ?>
<form action ="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label>Name:</label> <input type="text" name ="Cusomer_Name">
<label>Email:</label> <input type="email" name ="Cusomer_Email">
<label>Contact:</label> <input type="tel" name ="Cusomer_Contact">
<input type="submit" name ="submit">
</form>
<?php } ?>
</div>
</body>
</html>
I have checked everything I can think of but I just cannot seem to get the records to add to the database.
Any ideas of what I'm doing wrong?
In the html form you have:
<label>Name:</label> <input type="text" name ="Cusomer_Name">
In the php code you filter Customer_Name:
$Customer_Name = filter_input(INPUT_POST, 'Customer_Name');
There is a missing 't' in the html form.
Put Customer_Name instead of Cusomer_Name in the html form and do the same thing for Cusomer_Email and Cusomer_Contact
$stmt->execute(); returns boolean with answer. Try following snippet to figure out where exactly problem is:
$success = $stmt->execute();
if (!$success){
print $stmt->errorInfo()[2]; //PDO driver error message
}