Whenever I try to save user input to a MySQL database, it saves empty rows as soon as I load the page. Here is my index.php file:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$uName = mysqli_real_escape_string(mysqli_connect($servername, $username,
$password, $dbname), $_POST['username']);
$pass = mysqli_real_escape_string(mysqli_connect($servername, $username,
$password, $dbname), $_POST['password']);
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password)
VALUES ('$uName', '$pass')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<body>
<form action="index.php" method="post">
<input type="text" name="username"> <br> <br>
<input type="password" name="password"> <br> <br>
<input type="submit" name="submit">
</form>
</body>
</html>
Please tell me if there is anything I am doing wrong.
Thanks
Please see modified code below:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$uName = mysqli_real_escape_string(mysqli_connect($servername, $username,
$password, $dbname), $_POST['username']);
$pass = mysqli_real_escape_string(mysqli_connect($servername, $username,
$password, $dbname), $_POST['password']);
$sql = "INSERT INTO users (username, password)
VALUES ('$uName', '$pass')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="" method="post">
<input type="text" name="username"> <br> <br>
<input type="password" name="password"> <br> <br>
<input type="submit" name="submit">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['submit']))
{
$uName=$_POST['username'];
$password=$_POST['password'];
$sql = "INSERT INTO users (username, password) VALUES ('$uName', '$pass')";
if(mysqli_query($conn, $sql)){
{
echo "New record inserted successfully";
}
else
{
echo "There have some problem";
}
}
?>
Please Try this one
Related
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();
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
I have a form that I want to have record changes update my SQL database-table.
In my index.php-file I have f.ex this:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
$tbname = "myVis";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM " . $tbname . " WHERE id = '$_POST[id]'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$image = $row['image'];
$course = $row['course'];
$frdate = $row['frdate'];
$todate = $row['todate'];
$email = $row['email'];
$checkout = $row['checkout'];
}
}
mysqli_close($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
...
</head>
<body>
<form action='' method='post'>
<table>
...
<tr>
<td>Efternamn:</td>
<td>
<input id="lastname2" type="text" value='<?php echo $lastname; ?>' /></td>
</tr>
...
</table>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['submit2'])) {
...
if (isset($_POST['lastname2'])) {
$lastname = $_POST['lastname2'];
}
...
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
$tbname = "myVis";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql2 = "UPDATE " . $tbname . " SET firstname='$firstname', lastname='$lastname', image='$image', course='$course', frdate='$frdate', todate='$todate', email='$email', checkout='$checkout' WHERE id ='".$_POST['id']."'";
$result = mysqli_query($conn, $sql2);
if ($result) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
}
}
?>
<input type="submit" name="submit2" id="submit2" value="Spara" />
<input type="button" name="back" id="back" value="Tillbaka" onclick="history.back()" />
</form>
</body>
</html>
When I try to change a value (say lastname) nothing changes and all values are back to the selected record from the db-table.
How can I get PHP to understand and have a changed value update the table?
Don't quite understand the sequence in my index-file.
Please help.
Regards,
/Fredrik.
Put your submit code at the top of the page after your database connection. Then when you submit the form first match the table column with submitted post values. If any column has different post value then update that column.
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.
I´m trying to create a form connected to a database but when I fill out the form and I refer to the table in phpMyAdmin I see that it have entered a blank record instead of form data. I´m using PhpStorm.
I think all this code is correct...
That is the form of the .html:
<form id="form1" name="form1" method="post" action="index.php">
<label for="userSignUp">Email</label>
<input type="text" name="userSign" id="userSignUp" />
<label for="passwordSignUp">Password</label>
<input type="password" name="passwordSign" id="passwordSignUp" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
</form>
I have the following .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);
}
$db_selected = mysqli_select_db($conn, $dbname);
$userSignUp = ""; // If I substitute "" with characters at this time the table is well updated
$passwordSignUp = ""; // Same as before
if(isset($_POST['userSign'])){
$userSignUp = $_POST['userSign'];
}
if (isset($_POST['passwordSign'])) {
$passwordSignUp = $_POST['passwordSign'];
}
$sql = "INSERT INTO test.person (FirstName, Password) VALUES ('$userSignUp', '$passwordSignUp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();