First SQL Database not working - php

I am working on a personal project of mine and I am accepting a name and email so I created a database called:
emailtemp with columns of "name" and "email"
PHPMyAdmin Page
HTML Form:
<form method="post" action="connect.php" class="contact100-form validate-form">
<div class="wrap-input100 m-b-10 validate-input" data-validate = "Name is required">
<input class="s2-txt1 placeholder0 input100" type="text" name="username" placeholder="Your Name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 m-b-20 validate-input" data-validate = "Email is required: ex#abc.xyz">
<input class="s2-txt1 placeholder0 input100" type="text" name="emailAddress" placeholder="Email Address">
<span class="focus-input100"></span>
</div>
<div class="w-full">
<button class="flex-c-m s2-txt2 size4 bg1 bor1 hov1 trans-04">
Subscribe
</button>
</div>
</form>
PHP File:
<?php
$connect = mysqli_connect("mysql.*****.net","*****","****>","emailtemp");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO posts (customerName, customerEmail)
VALUES ('$_POST[username]', '$_POST[emailAddress]')";
?>
Based off everything I read and looked at it it should work but after I click "subscribe" it pulls up connect.php and says "is currently unable to handle this request.
HTTP ERROR 500"
Is there a way to have this process in the background and stay on the same page and just say successful?

http://php.net/manual/en/mysqli.prepare.php
$connect = mysqli_connect("mysql.*****.net","*****","****>","emailtemp");
if ($stmt = $mysqli_prepare($connect,"INSERT INTO posts (customerName, customerEmail) VALUES (?, ?)")) {
mysqli_stmt_bind_param($stmt, "ss", $_POST['username'],$_POST['emailAddress']);
mysqli_stmt_execute($stmt);
}

Looks like you're missing a ) at the end of your mysqli_query() call.
If your DB is really like this:
emailtemp with columns of "name" and "email"
.. then you should match those in your query:
mysqli_query($connect,"INSERT INTO emailtemp (name, email)
VALUES ('$_POST[username]', '$_POST[emailAddress]')");
Recommended to check for user/email first, if they're somehow empty that will throw an exception.
like this:
$username = $_POST[username];
$email = $_POST[emailAddress];
if ($username && $email) {
// stuff here
} else {
// other stuff here
}

You forgot to close the mysqli_query function with an ) and you forgot the brackets around username and emailAdress
mysqli_query($connect,"INSERT INTO posts (customerName, customerEmail)
VALUES ('$_POST[username]', '$_POST[emailAddress]')");
Also this code makes you vulnerable to an SQL injection
Users can inject other commands to the SQL server and they get executed with admin rights.
You can use PDO, a secure implementation of SQL in PHP (if used right of course)
In your example it would be:
$dbhost = "your-host";
$dbname = "your-db-name";
$dbusername = "your-username";
$dbpassword = "your-password";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$statement = $conn->prepare("INSERT INTO posts (customerName, customerEmail)
VALUES (:username, :emailAddress");
$statement->execute(array(
"username" => $_POST['username'],
"emailAdress" => $_POST['emailAdress']
));

Related

html form radio buttons not saving string to database

I have a html form which includes a question involving three radio buttons. I want the word 'road', 'both' or gravel' to be saved to my database. This field is set up as a varchar in the database.
This is my html:
<div class="form-group">
<label>Do you prefer just road or gravel/trail cycling as well?</label>
<label for="road">Just road</label>
<input type="radio" name="bike_terrain" id="road" value="road" required/>
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="both">Both</label>
<input type="radio" name="bike_terrain" id="both" value="both" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="gravel">Just gravel/trail</label>
<input type="radio" name="bike_terrain" id="gravel" value="gravel" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
</div>
I am then using php to validate the input is not empty:
if(empty($_POST["bike_terrain"])){
$bike_terrain_err = "Please select a bike terrain.";
} else {
$bike_terrain = isset($_POST["bike_terrain"]);
}
And php to send it to my localhost database:
if(empty($username_err) && empty($email_err) && empty($bike_terrain_err)) {
// Prepare an insert statement
$sql = "INSERT INTO users (username, email, terrain) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $param_username, $param_email, $param_terrain);
// Set parameters
$param_username = $username;
$param_email = $email;
$param_terrain = $bike_terrain;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Oops! Something went wrong. Please try again later.248";
}
}
}
(Note: I have cut out some of the other fields that I am inserting for simplicity)
$bike_terrain has previously been initialised as a string.
The problem is that nothing is being saved to the terrain field in my database and I don't know why!
Thank you very much! All suggestions, thoughts or ideas are very welcome.
Something like this (untested) should do the trick. you save the same radio with the same name so it would look like a selection somehow.
Had to quickly code from my mobile device XD
<?php
if(isset($_POST['submit'])){
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db = 'people_db'
$con = mysqli_connect($host, $user, $pass, $db) or die ('Cannot connect'.mysqli_error());
$fullname = mysqli_real_escape_string($con,$_POST['fullname']);
$gender = mysqli_real_escape_string($con,$_POST['gender']);
$q = "insert into employeedb (fullname, gender) values ('".$fullname."', '".$gender."')";
mysqli_result($con,$q);
echo 'Data Saved to Database!';
}
?>
<html>
<head>
<title>Save Radio to DB</title>
</head>
<body>
<form name="people" method="POST" action="index.php"
<input type="text" name="fullname" placeholder="Enter your name"/><br/>
<input type="radio" name="gender" value="Male"/>
<input type="radio" name="gender" value="Female"/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

Failing to insert data into database using prepared statement in PHP, no error reported

I'm trying to create a registration form that stores the users entered data into an MySQL database.
I was able to get it to work by manually setting the values, but learned that it was best to use prepared statements. This is what my PHP code looks like:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "accounts";
//Creating a new connection to the database
$connection = new mysqli($servername, $username, $password, $dbname);
//Checking the connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
//SQL string used to insert the data into the database
$sql = "INSERT INTO users (name, email, password) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Failed";
} else {
mysqli_stmt_bind_param($stmt, "sss", $_POST["name"], $_POST["email"], $_POST["passowrd"]);
mysqli_stmt_execute($stmt);
}
?>
And this is the HTML:
<div id="wrapper">
<div id="formContent">
<h3>Complete the following form to register an account:</h3>
<form class="register" action="registration.php" method="post">
Email: <input type="email" name="email" required> <br></br>
Name: <input type="name" name="name" required> <br></br>
Password: <input type="password" name="password" required> <br></br>
Confirm Password: <input type="password" name="confirmed_password" required> <br></br>
<input type="submit" name="submit">
</form>
</div>
</div>
The listed code returns no error but the database is not updated. I have been busting my head for some time now, so any help is appreciated.
First, you have a typo for password (you have $_POST['passowrd']) and second, this is based on the example from the documentation:
# Prepare (use the OOP version of this library)
$query = $connection->prepare("INSERT INTO users (`name`, `email`, `password`) VALUES (?, ?, ?)");
# Bind parameters and spell "password" correctly
$query->bind_param('sss', $_POST['name'], $_POST['email'], $_POST['password']);
# Execute
$query->execute();
# See if the row was created and echo success
echo ($query->affected_rows > 0)? 'Success!' : 'Failed';
You should be using password_hash() (storing) and password_verify() (validating) or a bcrypt equivalent library (if your version of php doesn't have those native functions). When using these functions, make sure your password column has like 255 character length so not as to cut off the password hash.

SQL - Insert form into a database

I have a php script to insert form input into a database called XXXX_comments into the Table called Comments that has Name and Comment as columns.When a user hits Save button the form should be inserted into the DB. I connect to the database using connect.php :
<?php
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
$Dbconnect = "XXX_comments";
// Create connection
$conn = new mysqli($servername, $username, $password);
mysqli_select_db($conn,$Dbconnect);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
in my index.php file i have the following form:
<?php
include ('connect.php');
?>
<?php
if(isset($_POST['Save'])){
$sql = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $comment);
$firstname = $_POST['firstname'];
$comment = $POST['comment'];
$stmt->execute();
Echo "Succefully inserted to table";
}
?>
<div class="container">
<div class="row" id="post-review-box" style="display:none;">
<div class="col-md-12">
<form id="form" accept-charset="UTF-8" action="index.php" method="post">
<input type="text" class="form-control animated" id="firstname" type="hidden" placeholder="Enter your Name">
<br>
<input id="ratings-hidden" name="rating" type="hidden">
<textarea class="form-control animated" cols="50" id="comment" placeholder="Enter your review here..." rows="5"></textarea>
<br>
<div class="text-right">
<div class="stars starrr" data-rating="0"></div>
<a class="btn btn-danger btn-sm" href="#" id="close-review-box" style="display:none; margin-right: 10px;">
<span class="glyphicon glyphicon-remove"></span>Cancel</a>
<button class="btn btn-success btn-lg" type="submit" name="Save">Save</button>
</div>
</form>
</div>
</div>
</div>
<div class="display"></div>
</div>
</div>
</div>
The connection is successful but the data is not being inserted.
You need to assign values before you can use them as below code:
$firstname = $_POST['firstname'];
$comment = $_POST['comment'];
$sql = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
$stmt->bind_param("sss", $firstname, $comment);
You should give name to your inputs and textarea inside the form as
<input type="text" name="firstname" class="form-control animated" id="firstname" type="hidden" placeholder="Enter your Name">
<input id="ratings-hidden" name="rating" type="hidden">
<textarea class="form-control animated" cols="50" name="comment" id="comment" placeholder="Enter your review here..." rows="5"></textarea
and you are assigning values after the binding it to the query, you should assign values for $firstname and $comment before binding it to the query as
if(isset($_POST['Save'])){
$firstname = $_POST['firstname'];
$comment = $_POST['comment'];
$sql = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $comment);
$stmt->execute();
echo "Succefully inserted to table";
}
Edit: The code was using $POST instead of $_POST.
Few remarks:
First of all, in the connect.php file you're mixing OOP and Procedural styles, you can gain the same result by using the following code:
$conn = new mysqli($servername, $username, $password, $Dbconnect);
Next, in your index.php, you've created a prepared statement, but you assigned that to $sql variable, and later you tried to use the undefined $stmt variable, so in order to fix that just change the first 2 lines
$stmt = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $comment);
Hope it will solve your little issue!
For any one intrested I have solved the issue, It seemed like the submit button wasn't responding So i added a javascript onclick function to force submit the form.
<input class="btn btn-default" onclick="myFunction()" value="Submit">
<script>
function myFunction() {
document.getElementById("form").submit();
}
</script>
Thanks for all the answers.

Storing data entered when signing up

I need to create a sign up page that will store user name email passwords and put them in a database so that the user can then login and access a profile etc.
I have made a database database however nothing will go into it. I input one manually but anything I try to do from the webpage won't go to the database.
Code for the webpage: Signup is the page I want displayed and adduser is the code for adding the data to the database.
Signup:
<?php include '../view/header.php';
?>
<br>
<br>
<h1 class="light white-text text-lighten-3">Sign up!</h1>
<br>
<br>
<form class="form" id="signup" action="addUser.php" method="post">
<div class="form-group ">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Your Email">
</div>
<br>
<div class="form-group ">
<input id="user_name" type="text" class="validate" name="user_name"required="required">
<label for="user_name">User Name</label>
</div>
<br>
<div class="form-group col s6">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter a Password">
</div>
<br>
<br>
<button type="submit" class="orange btn btn-primary">Submit</button>
</form>
<?php
include '../view/footer.php';
AddUser:
<script src="../js/materialize.js" type="text/javascript"></script>
<script src="../js/materialize.min.js" type="text/javascript"></script>
<script src="../js/init.js" type="text/javascript"></script>
<?php
$server = "localhost";
$username = 'root';
$Password ="";
$database = 'commish';
$con = mysqli_connect($server, $username, $Password, $database);
$email = filter_input(INPUT_POST, 'email');
$user_name = filter_input(INPUT_POST, 'user_name');
$password = filter_input(INPUT_POST, 'password');
new_user( $user_name, $password,$email, $con);
function new_user($user_name, $password, $email,$con)
{
global $con;
$query = "INSERT into users (user_name, password, email) VALUES (:user_name, :password, :email)";
$statement = $con->prepare($query);
$statement->bindValue(":user_name", $user_name);
$statement->bindValue(":password", $password);
$statement->bindValue(":email", $email);
$statement->execute();
echo 'Successfully created new user';
}
There's no bindValue() method in mysqli, PDO has. So here are the two approaches to solve your problem:
1)mysqli method:
Use bind_param() method to bind variables to your prepared statement. So your new_user() function should be like this:
function new_user($user_name, $password, $email,$con){
$query = "INSERT into users (user_name, password, email) VALUES (?, ?, ?)";
$statement = $con->prepare($query);
$statement->bind_param("sss", $user_name, $password, $email);
if($statement->execute()){
echo 'Successfully created new user';
}else{
// query failed
}
}
NOTE: Since you're passing the connection handler $con to this function, there's no need to use global $con;. Plus Globals are evil.
2)PDO method:
Keep your new_user() function as it is and change this line
$con = mysqli_connect($server, $username, $Password, $database);
to
$con = new PDO("mysql:host=$server;dbname=$database",$username,$Password);
Sidenote: Never store password as a plain readable text, always perform salted password hashing on raw password before inserting it into the table.
There's no bindValue() method in mysqli, you should use bind_param()
new_user function :
function new_user ($user_name, $password, $email)
{
global $con;
$stmt = $con->prepare("INSERT into users (user_name, password, email) VALUES (?,?,?)";
$stmt->bind_param("sss", $user_name, $password, $email);
$stmt->execute();
$stmt_error = $stmt->error;
$stmt->close();
if ($stmt_error)
echo 'Error on create new user: '.$stmt_error;
else
echo 'Successfully created a new user';
}

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;
}
}

Categories