Can't insert data with php into mysql - php

so i am working on the simple project and i dont know why, but i can't insert data into the database
Here is my connection to database
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "register";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $register);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
And in this part of code i am trying to insert data:
<?php
if (isset($_POST['submitreg'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql = "INSERT INTO users (email, username, password) VALUES ('$email', '$username', '$password')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
header("Location: signin.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
And then i am inserting the code, i am getting this error:
Error: INSERT INTO users (email, username, password) VALUES ('gerulisjonas#gmail.com', 'jonas2422', 'password')
Thank you in advance :)
extra:
Form
<form id="register" class="signinform" action="includes/registerinc.php" method="post">
<div class="formcenter">
<input type="text" name="username" value="" placeholder="user name"><br>
<input type="email" name="email" value="" placeholder="email"><br>
<input type="password" id="passwordid" name="password" value="" placeholder="password"><br>
<input type="password" name="passwordtwo" value="" placeholder="repeat password"><br>
<input type="submit" name="submitreg" class="btn btn-success" value="Register"></input>
</div>
</form>

When creating your connection you named the variable that holds the database name $database, but when you pass it along to mysqli_connect you are using $register.
Try this instead:
$database = "register";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

Hey guys sorry I did bother you, i just run trough my code and i found that i did not included connection.php file in my register.php file

Related

Can't get PHP to process form data into MySQL database [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
I'm trying to process some HTML form data into a MySQL database using some PHP, but this is my first foray into webdev and I think I'm in over my head. The form is POSTed to the formSubmit.php file, which turns them into the variables that the sql command then queries. I've tried changing round the variable layout, but it still won't send for some reason.
The HTML form:
<form class="middleForm" name="pizzaGuest" action="formSubmit.php" method="POST">
<fieldset>
<legend>Guest details</legend>
First name:<br>
<input type="text" name="firstName" required><br>
Last name:<br>
<input type="text" name="lastName" required><br>
Email address:<br>
<input type="email" name="email" required><br>
Party date:<br>
<input type="date" name="date" required><br>
Diet:<br>
<select name="diet">
<option value="omnivore" selected>Omnivore</option>
<option value="pescatarian">Pescatarian</option>
<option value="vegetarian">Vegetarian</option>
<option value="vegan">Vegan</option>
</select><br>
Dairy free?<br>
<input type="checkbox" name="dairyFree"><br>
Toppings:<br>
<input type="text" name="toppings"><br>
Allergies:<br>
<input type="text" name="allergies"><br>
<input type="submit" value="Submit">
</fieldset>
</form>
formSubmit.php:
<?php
$servername = "localhost";
$username = "partyForm";
$password = "████████████";
$dbname = "pizza";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$FirstName = $_POST["firstName"];
$LastName = $_POST["lastName"];
$Diet = $_POST["diet"];
$Allergies = $_POST["allergies"];
$Email = $_POST["email"];
$DairyFree = $_POST["dairyFree"];
$sql = "REPLACE INTO guests (FirstName, LastName, Diet, Allergies, Email, DairyFree) VALUES ($FirstName, $LastName, $Diet, $Allergies, $Email, $DairyFree);";
mysql_query($sql)
mysqli_close($conn);
?>
You might try using prepared statements instead as they proect against sql injection and avoid the need to add quotes as your sql omits.
<?php
$servername = "localhost";
$username = "partyForm";
$password = "xxx";
$dbname = "pizza";
$conn = new mysqli( $servername, $username, $password, $dbname );
if( !$conn ) die("Connection failed");
$sql = "replace into guests ( `firstname`, `lastname`, `diet`, `allergies`, `email`, `dairyfree` ) values (?,?,?,?,?,?);";
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssssss',$_POST["firstName"], $_POST["lastName"], $_POST["diet"], $_POST["allergies"], $_POST["email"], $_POST["dairyFree"] );
$stmt->execute();
$stmt->close();
$conn->close();
?>
For a best usage and confort, check the PDO driver for MySQL instead of mysql. With this method, you can perform prepared statements easily.
The connection with this driver will be:
$dbh = null;
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Erreur !: " . $e->getMessage() . "<br/>";
die();
}
$stmt = $dbh->prepare("REPLACE INTO guests (FirstName, LastName, Diet, Allergies, Email, DairyFree) VALUES (:FirstName, :LastName, :Diet, :Allergies, :Email, :DairyFree);");
$stmt->bindParam(':FirstName', $FirstName);
$stmt->bindParam(':LastName', $LastName);
$stmt->bindParam(':Diet', $Diet);
$stmt->bindParam(':Allergies', $Allergies);
$stmt->bindParam(':Email', $Email);
$stmt->bindParam(':DairyFree', $DairyFree);
$stmt->execute();
// Close the connection at the end of your queries
$dbh->close();
$dbh = null;
This the best approach to secure your code and minimize the risk go SQL injections.

How do I insert values from a form using php and sql using my own script?

Hi first time user and beginner when it comes to using php,
How do I go about inserting values from a form using php and sql.
Ive created the following code using php and sql.
here is my form.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
?>
<form action="/t.php" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
<?php
// set parameters and execute
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$stmt->execute();
$stmt->close();
$conn->close();
?>
the t.php file is simply saying entries were added successfully even though there is no logic there, just a simple echo comment.
I just want to know how to insert data using forms with php and sql.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<form action="/t.php" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
// set parameters and execute
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$stmt->execute();
$stmt->close();
$conn->close();
}
?>
You can do it like this:
To prevent duplication, save the db connection in a file called db.php.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Then, include it in the main.php file. Here's the main.php file written with prepared statement errors prevented.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
# check if all the params are set
if (
!empty($_POST['firstname']) &&
!empty($_POST['lastname']) &&
!empty($_POST['email'])
) {
$firstname = htmlspecialchars(trim($_POST['firstname']));
$lastname = htmlspecialchars(trim($_POST['lastname']));
$email = htmlspecialchars(trim($_POST['email']));
include_once 'db.php';
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
if (
$stmt &&
$stmt->bind_param("sss", $firstname, $lastname, $email) &&
$stmt -> execute()
) {
echo "Yay! Inserted.";
} else {
throw new Exception("Error in MYSQLI Statement");
}
} else {
throw new Exception("Some data is not set");
}
} catch (Exception $e) {
die($e -> getMessage());
}
} else { ?>
<form action="" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
<?php } ?>
The strings should be validated before inserted into the database. Here I have used htmlspecialchars() to prevent XSS and trim() to remove unnecessary white spaces.
Thanks.
Form action will call t.php, but you dont have it!
Create two files: myHtml.html and t.php in the same folder
myHtml.html
<html>
<form action="t.php" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
</html>
t.php
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$stmt->execute();
$stmt->close();
$conn->close();

submit a html form to mySQL using php

very new to this, i am currently trying to create a log in system for my website. i have created a html log in form which i plan to use for users to create accounts. i have created a php page which has my code to connect to the server which is shown below.
when i fill the form i dont get any output. I'm not sure if the php code is in the wrong place (it is as a separate file) or no output is expected. when a form is submitted, the database doesn't seem to change when i submit it manually while testing.
My end goal is to be able to add users to the table called users in my database.
Here is my code for my log in form:
<body>
<h2>Sign Up</h2>
<p></p>
<form action="Create_User.php" method="post">
<div class="imgcontainer">
<img src="http://fc05.deviantart.net/fs70/f/2012/361/1/6/albert_einstein_by_zuzahin-d5pcbug.jpg" alt="Einstein the lad" class="img" />
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Please Enter your desired Username" name="username" required />
<label><b>Password</b></label>
<input type="password" placeholder="Please Enter Your Desired Password" name="password" required />
<label><b>Email Address</b></label>
<input type="email" placeholder="Please Enter Your Email Address" name="email" required />
<label><b>Date Of Birth</b></label>
<input type="date" name="date_of_birth" required />
<label><b>First Name</b></label>
<input type="text" placeholder="Please Enter your first name" name="first_name" required />
<label><b>Surname</b></label>
<input type="text" placeholder="Please Enter your surname" name="surname" required />
</div>
<div class="container" style="background-color: #f1f1f1">
<button type="submit">Sign Up</button>
<button class="signinbtn" onclick="location.href='/AccountRelatedPages/SignIn.aspx'">Already have an account? Sign in here</button>
</div>
</form>
</body>
here is the code in my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "rootpass";
$dbname = "synther_physics";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password, email, date_of_birth, first_name, surname)
VALUES ('<?php echo $_POST[$username];', '<?php echo $_POST[$password];', '<?php echo $_POST[$email], <?php echo $_POST[$date_of_birth];, <?php echo $_POST[$first_name], <?php echo $_POST[$surname];')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Again very new to all this so im trying my best to get my head around so please bear that in mind.
Thanks.
Putting all together from the comments, sql injections, password_hash(). for sql injections protection then u need use prepared statements. I won't say much a lot of important things were said in the comments, hope you went through them all, because I did.
This is how your code should look :
<?php
$servername = "localhost";
$username = "root";
$password = "rootpass";
$dbname = "synther_physics";
//Validate user inputs
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
$email = $_POST['email']; //VALIDATE the email
$dob = $_POST['date_of_birth'];
$fname = $_POST['first_name'];
$sname = $_POST['surname'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password, email, date_of_birth, first_name, surname)
VALUES (?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssss", $username, $hash, $email, $dob, $fname, $sname);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error : " . $conn->error; // on dev mode only
// echo "Error, please try again later"; //live environment
}
$conn->close();
?>
Edit :
if your php is on the same file and the html, then to avoid undefined indexes notice, you will need to check if the form was submitted, before processing. what you need to do is to have a name attribute to your form button.
then check if form is submitted.
<?php
$servername = "localhost";
$username = "root";
$password = "rootpass";
$dbname = "synther_physics";
//Validate user inputs
if(isset($_POST['buttonName'])){
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
$email = $_POST['email']; //VALIDATE the email
$dob = $_POST['date_of_birth'];
$fname = $_POST['first_name'];
$sname = $_POST['surname'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password, email, date_of_birth, first_name, surname)
VALUES ('?,?,?,?,?,?')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssss", $username, $hash, $email, $dob, $fname, $sname);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error : " . $conn->error; // on dev mode only
// echo "Error, please try again later"; //live environment
}
$conn->close();
}
?>
Also you need to check if fields are set and not empty.

Inputting data from a HTML form to MYSQL using PHP error

I am having some trouble using PHP to input data into a MYSQL database from a form. Below I have included the files and I would just like to mention I've previously inputted data by changing the values:
VALUES ('Jake', 'Doe', 'john#example.com')";
and it works.
index.php
<?php include 'assets/header.php';$title='Home Page';?>
<div class="context">
<form action="connect_to_mysql.php" method="post">
<label>First Name:</label>
<input type="text" name="first_name" id="fist_name" required="required" placeholder="Please Enter First Name"/><br /><br />
<label>Last Name:</label>
<input type="text" name="last_name" id="last_name" required="required" placeholder="Please Enter Your Last Name"/><br/><br />
<label>Email:</label>
<input type="email" name="email" id="email" required="required" placeholder="Please Enter Your Email"/><br/><br />
<input type="submit">
</form>
</div>
<?php include 'assets/footer.php';?>
connect_to_mysql.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = "INSERT INTO hello_world (firstname, lastname, email)
VALUES ('.$first_name', '.$last_name', '.$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Error:
Fatal error: Uncaught Error: Call to undefined function
mysql_real_escape_string() in
E:\XAMPP\htdocs\mysql\connect_to_mysql.php:14 Stack trace: #0 {main}
thrown in E:\XAMPP\htdocs\mysql\connect_to_mysql.php on line 14
Use this code and check if the error still comes up
Note: this code is connecting via the PDO class
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new PDO('mysql:host='.$servername.';dbname='.$dbname.';', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = $conn->prepare("
INSERT INTO hello_world(first_name, lastname, email)
VALUES (:firstname, :lastname, :email)
");
$sql->execute([
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email
]);
if ($sql->rowCount() > 0) {
echo "New record created successfully";
}
else
{
//error message
}
?>

Adding user to MySQL database in php using phpMyAdmin

I think I am successfully connecting to my database by:
<?php
$user = 'root';
$pass = '9KSroMDjEqNmEYY4';
$db = 'chatservice';
$host = '127.0.0.1';
$conn = new mysqli($host, $user, $pass, $db, 3306) or die("Unable to connect");
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
?>
My question is how I would use the registration code to successfully add a user to the database. When entering the form I press register I do not get any error messages stating that the registration didn't succeed. It seems that the php code is not being reached after the initial connection. I am new to php and mySQL so any tips on formatting would be nice too!
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$id', '$password')";
$result = mysqli_query($query);
if($result){
$msg = "Registered Sussecfully";
echo $msg;
}
else
$msg = "Error Registering";
echo $msg;
}
?>
<div class="register-form">
<title>Chat Page Start</title>
<form action="" methods="POST">
<p>
<label>Username: </label>
<input id="user" type="text" name="user" placeholder="user" />
</p>
<p>
<label>ID: </label>
<input id="IDNUM" type="text" name="IDNUM" placeholder="ID number" />
</p>
<p>
<label>Password: </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" value="Register" />
</form>
</div>
Another thing is how would I check the status of my database connection and where I should be checking this status?
your database connection is mysqli_connect and you execute the query in mysql_query is not proper.
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', ' $id ', '$password')";
$result = mysqli_query($query,$conn);
if($result){
$msg = "Registered Sussecfully";
}
else
$msg = "Error Registering";
}
?>
You are connecting database using mysqli:
$conn = new mysqli('localhost', $user, $pass, $db, 3306) or die("Unable to connect");
And executing query using mysql:
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$IDNUM', '$password')";
$result = mysql_query($query);

Categories