mysqli code will not send to database - php

I have searched on here tirlessly and can not seen to find a solution to getting my code to work, i am trying to create a simple sign up system for member to join my website but i can not seen to get my php code to send to the database i have set up, here is the code.
<?php require 'lpgamers/connections/connect.php'; ?>
<?php
if(isset($_POST['Register'])) {
session_start();
$FName = $_POST['First_Name'];
$LName = $_POST['Last_Name'];
$Email = $_POST['Email'];
$PW = $_POST['Password'];
$sql = $con->query("INSERT INTO lpg-user-db (Fname, Lname, Email, Password)Values('{$FName}', '{$LName}', '{$Email}', '{$PW}')");
}
?>
<div class="rightbody">
<form id="registerform" name="registerform" method="post">
<div class="formelement">
<input name="First_Name" type="text" required class="tfield" id="First_Name" placeholder="First Name">
</div>
<div class="formelement">
<input name="Last_Name" type="text" required class="tfield" id="Last_Name" placeholder="Last Name">
</div>
<div class="formelement">
<input name="Email" type="email" required class="tfield" id="Email" placeholder="Email">
</div>
<div class="formelement">
<input name="Password" type="password" required class="tfield" id="Password" placeholder="Password">
</div>
<div class="formelement">
<input name="Register" type="submit" class="button" id="Register" value="Register">
</div>
</form>
I also have a connect file that is required and i have this set up and this does connect to my database
<?php
$con = mysqli_connect("localhost", "root", "", "lpgamers-user-db");
if (mysqli_connect_errno()) {
printf('Connect failed: %s\n', mysqli_connect_error());
exit();
}
?>
am i doing somthing wrong here or is this just a database problem, i am using a wamp server at this moment for testing ?.
Thanks in advance Rob.

mysqli_error($con) should have thrown you an error for this, but you didn't check for errors.
Your lpg-user-db table in
INSERT INTO lpg-user-db
contains hyphens and MySQL is interpreting that as lpg MINUS user MINUS db, in thinking you want it to do math.
The table name would require to have ticks around it:
INSERT INTO `lpg-user-db`
Either do that, or replace them with underscores and renaming it:
INSERT INTO lpg_user_db
References:
http://php.net/manual/en/mysqli.error.php
http://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html
Sidenote: If there are any constraints in your table, mysqli_error($con) will inform you of it.
If the data you are trying to input contains characters that MySQL will complain about and for example John's Bar & Grill, then you will need to escape your data; something you should be doing anyway.
$FName = mysqli_real_escape_string($con, $_POST['First_Name']);
and doing the same for the other POST arrays.
You're also open to an SQL injection, use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP

Related

Cannot send the data into mysql from form

I am trying to send data from form but its sending the name in stead of value of the input box. File is uploading properly and the input box name is uploading too but I need to put the values.
<form action="intern.php" enctype="multipart/form-data" method="post" autocomplete="off">
<h3 class="register-heading">Want to be a <strong>learner Bee</strong>?</h3>
<div class="row register-form">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" name="iname" placeholder="Your Certificates name" value="" required />
</div>
<div class="form-group">
<input type="text" class="form-control" maxlength="14" minlength="10" name="icon" placeholder="Your 24/7 opened Phone Number" value="" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="ildegree" placeholder="University you are graduating from" value="" required />
</div>
<div class="form-group">
<textarea type="text" class="form-control" name="iaboutus" placeholder="What you know about us!" value="" required ></textarea>
</div>
<div class="form-group">
<textarea type="text" class="form-control" name="iaddress" placeholder="Your present address " value="" required ></textarea>
</div>
<div class="form-group" >
<label class="form-control" for="iapply"><input name="icvfile" style=" border: 0; clip: rect(1px, 1px, 1px, 1px); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px;" type="file" name="" id="iapply" accept=".doc, .docx, .pdf, .png, .jpg, . ppt, .pptx" required>Click here to upload your CV</label>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input class="form-control" name="inname" placeholder="Nick Name you like to called by" value="" required />
</div>
<div class="form-group">
<input type="email" name="iemail" class="form-control" placeholder="Your own mostly used Electronic mail" value="" required />
</div>
<div class="form-group">
<select class="form-control" name="icontrib" required>
<option class="hidden" selected disabled>How you can contribute us?</option>
<option>Graphic Design</option>
<option>Sales</option>
<option>Creative Idea Generation</option>
</select>
</div>
<div class="form-group">
<textarea type="text" class="form-control" name="ixp" placeholder="Your past working experience in short" value="" required ></textarea>
</div>
<div class="form-group">
<textarea type="text" class="form-control" name="ifgoal" placeholder="Where you want to see yourself after 10 years!" value="" required ></textarea>
</div>
<input type="submit" class="btnRegister" name="isubmit" value="Submit"/>
</div>
</div>
</form>
Upper one is the form that I need to filled. Just stuck somewhere, cannot find out.
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("Location: https://teambbc.asia/error.html");
}
$sql = "INSERT INTO Intern (Name, Contact, University, AboutUs, Address, NickName, Email, Contribution, Experience, FutureGoal) VALUES ('iname', 'icon', 'ildegree', 'iaboutus', 'iaddress', 'inname', 'iemail', 'icontrib', 'ixp', 'ifgoal')";
//Filename upload
$user=$_POST['inname'];
$cont=$_POST['icon'];
//$filename=basename($_FILES["file"]["name"]);
$tmp=$_FILES["icvfile"]["tmp_name"];
$extension = explode("/", $_FILES["icvfile"]["type"]);
$name=$user.".".$extension[1];
move_uploaded_file($tmp, "recruitment_cv/" . $user. "-" .$cont .".".$extension[1]);
if (mysqli_query($conn, $sql)) {
header("Location: https://teambbc.asia/congratulations.html");
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
header("Location: https://teambbc.asia/error.html");
}
$conn->close();
}
My connnection with database is okey, I am not thinking about that one.
Your Problem:
You are inserting Strings [ref] rather than Variables [ref] in to your SQL.
See:
$sql = "INSERT INTO Intern (Name, Contact, University, .... )
VALUES ('iname', 'icon', 'ildegree', .... )";
The values in 'quotes' are MySQL string literals. These values are NOT PHP variables. So they will be the same, no matter what variable data you give to PHP.
Solution Basics:
To fix this, you need to understand that when you submit a form the superglobals $_POST/$_GET and $_REQUEST are populated with the form data.
Example:
HTML:
<form action="intern.php" enctype="multipart/form-data" method="post" autocomplete="off">
<input type="text" class="form-control" name="iname" placeholder="Your Certificates name" value="" required />
<input type='submit' value='Button to submit the form'>
</form>
PHP:
if(!empty($_POST['iname'])){
print_r($_POST['iname']); // This will output the value entered into the form for the iname form element.
}
So Applying This To Your SQL:
You need to at a very basic level turn your strings into variables:
$sql = "INSERT INTO Intern (Name, Contact, University, .... )
VALUES ('".$_POST['iname']."', '".$_POST['icon']."', '".$_POST['ildegree']."', .... )";
BUT:
THIS IS DEEPLY INSECURE.
YOU MUST NEVER, EVER TRUST USER SUBMITTED DATA. EVER.
Reference and Reference
So how should you save this data safely, to your SQL table?
By using Prepared Statements; either PDO or MySQLi.
My example here will use Object Orientated MySQLi Prepared Statements:
$sql = "INSERT INTO Intern (Name, Contact, University) VALUES (?,?,?)";
$insert = $conn->prepare($sql);
/***
* See https://www.php.net/manual/en/mysqli-stmt.bind-param.php
* You can add multiple values at once:
***/
$insert->bind_param("sss", $_POST['iname'],$_POST['icon'],$_POST['ildegree']);
$insert->execute();
This will insert the data (example only three bits of data but you should get the idea), safely and easily into your database.
There is a lot I have missed out for simplicity and verboseness, so you should read up on how to use PDO/MySQLi proficiently.
NOTES:
One ? in the SQL string for each placeholder.
One value letter in the bind_param for each placeholder value. The value, and the corresponding value letter (i,s,d,b) MUST match the SQL column type (you can't insert string-type (s) values into integer-type columns (INT, TINYINT, etc.).
In MySQLi order is important, the first ? will relate to the first bind_param value (in the example codeblock above, $_POST['iname']).
Qualifier:
Some of your MySQL PHP code uses procedural interactions, and functions - and some of your MySQL PHP code uses Object Orientated interactions and functions. These CAN NOT BE MIXED and will result in errors and inconsistencies for you.
ALWAYS USE OBJECT ORIENTATED PHP/MYSQL INTERACTIONS Reference and Reference
Objct orientated interactions use the -> syntax.
You have:
if ($conn->connect_error) {
error_log("Connection failed: " . $conn->connect_error);
header("Location: https://teambbc.asia/error.html");
}
This is Object Orientated. This is best.
But:
mysqli_query($conn, $sql);
This is Procedural. This is not best. The OO version of this line would be $var = $conn->query($sql).
Bonus advice:
Do not use die to output error messages to the screen, error messages should always be output to the error log file.
When using header("Location: ... "); you must always put die() or exit afterwards:
Example:
if ($conn->connect_error) {
error_log("Connection failed: " . $conn->connect_error);
header("Location: https://teambbc.asia/error.html");
exit;
}
Good luck!
You should assign data to variables firstly. After that, you can insert to db.
function make_secured($x)
{
$variable = strip_tags(mysql_real_escape_string(trim($x)));
return $x;
}
$_POST = make_secured($_POST);
$name = $_POST['iname'];
$contact = $_POST['icon'];
$sql = "INSERT INTO Intern (Name, Contact) VALUES ('$name', '$contact')";
make_secured() function does checking all sql injection attacks in the POST.

html form, PHP insert data into database not working?

I have HTML registration form when I submit the form the PHP code appears and data not insert to database i made my database using phpMyAdmin, what should I do?
Here my PHP code:
<?php
$con=mysqli_connect('localhost','root','');
$db=mysqli_select_db($con,'research_sys');
if ($con) {
echo "good";
}else {
die('error');
}
if(isset($_POST['submit'])){
$Fname = mysqli_real_escape_string($con,$_POST["Fname"]);
$Lname = mysqli_real_escape_string($con,$_POST["Lname"]);
$email = mysqli_real_escape_string($con,$_POST['email']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$sql = mysqli_query($con,"INSERT INTO `research_sys`.`researcher` (Re_fname,Re_lname,Re_mobile,Re_password) values ('$Fname','$Lname','$email','$password ')");
if (mysqli_query($sql)){
echo "insert";
} else {
echo "error" .$sql ."<br>". mysqli_error($con);
}
}
?>
here my registration HTML code
<form method="post" action="connect.php">
<legend class="center">Register </legend>
<br>
<div>
<input type="text" name="Fname" placeholder="First Name"/>
</div>
<div>
<input type="text" name="Lname" placeholder="Last Name"/>
</div>
<div>
<input type="text" name="email" placeholder="Email"/>
</div>
<div>
<input type="password" name="password" placeholder="Password"/>
</div>
<div>
<input type="password" name="con_password" placeholder="Password confirm"/>
</div>
<input type="submit" name="submit" value="submit"/>
</form>
Look at the following:
$sql = mysqli_query($con,"INSERT INTO `research_sys`.`researcher`
^^^^^^^^^^^^ function
(Re_fname,Re_lname,Re_mobile,Re_password)
values ('$Fname','$Lname','$email','$password ')");
^ space
if (mysqli_query($sql)){
^^^^^^^^^^^^ function
You're using that mysqli_query() function twice, remove one and just do:
if ($sql){...}
and mysqli_error($con) should have thrown you an error about it.
If it didn't throw an error, then that may suggest you're using this as file:/// as opposed to http://localhost.
Edit:
"i have html registration form whin i submit the form the php code apears"
That's because of what I wrote above before quoting you. You need to run this off a webserver with php/mysql installed and running properly and as http://localhost.
Also, remove the space in this '$password '. That space counts as a character.
Double-check your column names also. There seems to be something that doesn't match (Re_fname,Re_lname,Re_mobile,Re_password) the Re_mobile and you're referencing an email '$email' in VALUES.
You also seem to store plain text passwords; don't, it's not safe if you intend on going live with this. Use password_hash() and a prepared statement.
Footnotes:
$con=mysqli_connect('localhost','root','');
$db=mysqli_select_db($con,'research_sys');
You can shorten that to using all 4 arguments in mysqli_connect():
$con=mysqli_connect('localhost','root', '', 'research_sys');

Inconsistencies with Input form?

I am just getting into web design with PHP, Ajax, and all the other goodies. I am trying to make a basic system that prints a username and password (or any fields) to a stored database. (I know this isn't secure, it's just a beginners project.) It seems to be highly inconsistent. Field A and Field B do not always print to the database. Sometimes it will print multiple times, and sometimes not at all. Here is the code you might need:
<form class="_rwf8p" data-reactid=".0.0.0.0.1.2">
<div class="_ccek6 _i31zu" data-reactid=".0.0.0.0.1.2.0">
<input class="_kp5f7 _qy55y" aria-required="true" autocapitalize="off" id="Username" name="Username" type="username" placeholder="Username" value="" autocorrect="off" spellcheck="false" class="" data-reactid=".0.0.0.0.1.2.0.0" type="text" />
</div>
<div class="_ccek6 _i31zu" data-reactid=".0.0.0.0.1.2.1">
<input class="_kp5f7 _qy55y" aria-required="true" autocapitalize="off" id="Passwd" name="Passwd" type="password" placeholder="Password" value="" autocorrect="off" spellcheck="false" class="" data-reactid=".0.0.0.0.1.2.1.0" type="password" />
<div class="_j4ox0" data-reactid=".0.0.0.0.1.2.1.1">
<a class="_19gtn" href="/accounts/password/reset/" data-reactid=".0.0.0.0.1.2.1.1.0">
Forgot?
</a>
</div>
</div>
<button class="_rz1lq _k2yal _84y62 _7xso1 _nv5lf" data-reactid=".0.0.0.0.1.2.2">
Log in
</button>
</form>
<script>
$("html").keypress(function(event) {
if(event.keyCode == 13) {
saveCridentials();
}
});
$("#signIn").click(function() {
saveCridentials();
});
function saveCridentials() {
$.ajax({
type: "POST",
url: "log.php",
data: { "username" : $("#Username").val(), "password" : $("#Passwd").val() },
dataType: "json"
});
$("#Username").val("");
$("#Passwd").val("");
}
</script>
The PHP:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
fwrite(fopen('cridentials.txt', 'a'), "Username: ". $username . " Password: ". $password . "\n");
?>
Any help would be really great, thanks!
"I am trying to make a basic system that prints a username and password (or any fields) to a stored database"
Why not try just php and MySql
First you will have to connect to your database:
<?php
/* Database config */
$db_host = 'localhost';
$db_user = 'yourinput';
$db_pass = 'yourinput';
$db_database = 'yourinput';
$link = mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
mysql_select_db($db_database,$link);
mysql_query("SET names UTF8");
// Now lets say a user is trying to register with username and password, basically the same concept as what you would be trying to do.
if($_POST['submit']=='Register')
mysql_query(" INSERT INTO registered(usr,pass)
VALUES('".$_POST['usr']."','".md5($pass)."')");
// This would plug the values of the username and password, which is a randomly generated password but you could figure out how to conform it to the way you want.
// Most important your database has to be set up correctly. Check out this link http://dev.mysql.com/doc/refman/5.7/en/database-use.html , phpMyAdmin work great when working with data bases as well.
// Now, you HTML code has to written correctly. Your input form must be configured correctly to correspond to your php code & database. In your case you are simply trying to get the username and password into the database. Your id in your form has to be the same as you database and php code.
<input class="field" id="username" name="username" size="23" type="text" value="">
<input class="field" id="password" name="password" size="23" type="text" value="">
//If that doesn't help take a look at: https://www.eduonix.com/blog/web-programming-tutorials/learn-submit-html-data-mysql-database-using-php/

PHP code keeps inserting empy values into the database.

So I'm trying to create this form and every time I try to create a dummy user it creates an empy one in the database.
Here's the php code create.php:
<?php
session_start();
include ('connection.php');
$username = $_POST['usernamesignup'];
$email = $_POST['emailsignup'];
$password = $_POST['passwordsignup'];
mysql_query("INSERT INTO users (usernamesignup, passwordsignup, emailsignup)
VALUES ('$username', '$password', '$email')")or die (mysql_error());
header('Location: login.html');
mysql_close($db);
?>
And here's the part of the form Login.html:
<form action="create.php" autocomplete="on">
<h1> Sign up </h1>
<p><label for="usernamesignup" class="uname" data-icon="u">Your username</label>
<input id="usernamesignup" name="usernamesignup" required="required" type="text" placeholder="mysuperusername690" /></p>
<p><label for="emailsignup" class="youmail" data-icon="e" > Your email</label>
<input id="emailsignup" name="emailsignup" required="required" type="email" placeholder="mysupermail#mail.com"/></p>
<p><label for="passwordsignup" class="youpasswd" data-icon="p">Your password </label>
<input id="passwordsignup" name="passwordsignup" required="required" type="password" placeholder="eg. X8df!90EO"/></p>
<p><label for="passwordsignup_confirm" class="youpasswd" data-icon="p">Please confirm your password </label>
<input id="passwordsignup_confirm" name="passwordsignup_confirm" required="required" type="password" placeholder="eg. X8df!90EO"/></p>
<p class="signin button"><input type="submit" value="Sign up"/></p>
<p class="change_link">Already a member? Go and log in </p>
</form>
Any help would be greatly appreciated.
EDIT: The adding of method:"post" did the trick. Thank you very much to all of you for your fast response and the very valid advises on security and on how I should change to a more current form instead of what I used here.
You need to specify the form method to POST in your case. Try
<form action="create.php" autocomplete="on" method="POST">
You have to check if the values sent by your form are not null or with an empty string. And please be very careful your code is vulnerable to sql injections and hash your password in sha512 or something like that.
have a look to this function : http://php.net/manual/en/function.empty.php
and try to add this in your form :
<form action="create.php" autocomplete="on" method="post">
try adding this to your form tag
method='post'
Default method for form is GET, and you're trying to get your values from POST, so they're empty...
You should do:
$password = $_GET['password'];
// etc.
Or, if you don't know:
$password = $_REQUEST['password'];
// etc.
I recommend you to use a mysqli class. I've used this one myself in smaller projects: https://github.com/ajillion/PHP-MySQLi-Database-Class
You're missing "form validation" in your code. This prevents empty and malicious form submits if you integrate validation properly into your forms and backend code
A simple example of how to make sure data was entered in the specific fields, try this:
<?php
if (empty($_POST['usernamesignup']), empty($_POST['...']))
{
echo 'Not all required data was submitted';
}
else
{
// Process the form, all data was received
}
4. Have you considered using a php framework? Try something like Codeigniter or Laravel if you want something more advanced and usable.
Please consider including <form action="create.php" autocomplete="on" method="POST">
Please I beg you, Don't store raw password in database just use an encryption method.
And use PDO instead of mysql_*
see here: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

php mysql INSERT INTO mysql by using register form

I am php beginner and I am trying to make e-commerce by using php.
I am trying to make register form and I want to save these data into mysql server.
The coding looks like OK, but the data did not store in mysql server.
Could you give your answer for this? php language is first time that it is what I am struggled. Please give some advice. Thanks.
--registerForm.php--
<h4>Create a new account</h4>
<div class="box">
<form action="register.php" method="post">
<p>User ID: <input type="text" name="userId" size="30"/>*</p>
<p>Password: <input type="password" name="password" size="30"/>*</p>
<p>Retype Password: <input type="password" name="repassword" size="30"/>*</p>
<p>First Name: <input type="text" name="firstName" size="30"/>*</p>
<p>Last Name: <input type="text" name="lastName" size="30"/>*</p>
<p>Your Address (*):</p>
<p> <textarea name="address" rows="5" cols="30"></textarea></p>
<p>Phone: <input type="text" name="phone" size="20"/>*</p>
<p>E-mail: <input type="text" name="email" size="21"/>*</p>
<p><input type="submit" value="Create Account"/></p>
</form>
</div>
--register.php--
<?php
require "sql_connection.php";
if(isset($_POST['submit']))
{
if($_GET["userId"]==$_GET["repassword"]){
mysql_query("insert into customer (userId, password, firstName, lastName, address,
phone, email)
values
('$_GET[userId]','$_GET[password]','$_GET[firstName]','$_GET[lastName]','$_GET[address]','$_GET[phone]','$_GET[email]')")
or die(mysql_error());
}
echo "Done!!!!";
}
?>
--sql_connection.php--
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "**MY_PASS**";
$db_name = "**MY_DB**";
#mysql_connect("$db_host", "$db_username", "$db_pass", "$db_name") or die("connection is fail.");
#mysql_select_db("$db_name") or die("database does not exsist.");
echo "Successfully connection!!";
?>
if($_GET["userId"]==$_GET["repassword"])
Why do you compare userid to a retype pssword field?
I think it should be :
if($_GET["password"]==$_GET["repassword"])
Also make sure you escape strings to prevent SQL Injection Attacks.
http://php.net/manual/en/function.mysql-real-escape-string.php
And Like Paul said, to correctly retrieve the data use $_POST
Few things. Your $_GET and $_POST are mixed up. and NEVER post your db_pass and uername in public. Also, you're suppressing errors using #. don't do that.
i.e.
if($_GET["userId"]==$_GET["repassword"]){
should be
if($_POST["userId"]==$_POST["repassword"]){
and changes all these to $_POST
Your code:
$_GET[userId]','$_GET[password]','$_GET[firstName]','$_GET[lastName]','$_GET[address]','$_GET[phone]','$_GET[email]')
Should be:
$_POST[userId]','$_POST[password]','$_POST[firstName]','$_POST[lastName]','$_POST[address]','$_POST[phone]','$_POST[email]')"
As your form method defined is POST so use $_POST to get values after submit instead of $_GET
require "sql_connection.php";
if(isset($_POST['submit']))
{
if($_POST["userId"]==$_POST["repassword"]){
mysql_query("insert into customer (userId, password, firstName, lastName, address,
phone, email)
values
('$_POST[userId]','$_POST[password]','$_POST[firstName]','$_POST[lastName]','$_POST[address]','$_POST[phone]','$_POST[email]')")
or die(mysql_error());
}
echo "Done!!!!";
}
?>
Values are not quoted properly. You should quote then before insert.
mysql_query("insert into customer (userId, password, firstName, lastName, address,
phone, email)
values
('".$_POST[userId]."','".$_POST[password]."','".$_POST[firstName]."','".$_POST[lastName]."','".$_POST[address]."','".$_POST[phone]."','".$_POST[email]."')")
I think that what you are trying to do is:
if($_GET["password"]==$_GET["repassword"]) {

Categories