I'm trying to create a form for admin registration. The code works correctly but more than one admin can register for this page. How can I make it so that only one admin can register?
<html >
<head>
<title></title>
</head>
<body>
<?php
print ("<form action='admin.php' method='post'>
<p>Name
<input type='text' name='firstname' />
</p>
<p>Surname
<input type='text' name='lastname' />
</p>
<p>Username
<input type='text' name='username' />
</p>
<p>Password
<input type='password' name='password' />
</p>
<p>Email <input type='text' name='email'/> </p>
<input type='submit' value='Register'/>
</form>
");
if( !($database=mysql_connect("localhost","root",""))||!(mysql_select_db("st_login",$database)) )
print("Could not connect");
if(isset($_POST['firstname'] )&&isset($_POST['lastname'])&&isset($_POST['username'])&&isset($_POST['password'])
/*&&isset($_POST['notat'])&&isset($_POST['lendet'])*/&&isset($_POST['email'])){
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$username=$_POST['username'];
$password=md5($_POST['password']);
$email=$_POST['email'];
/*
$notat=$_POST['notat'];
$lendet=$_POST['lendet'];
*/
$query = "INSERT INTO login (firstname, lastname, username,password,email,admin) VALUES ('$firstname', '$lastname',
'$username','$password','$email',1)";
}
if ( !empty($firstname)&&!empty($lastname)&&!empty($username) &&!empty($password)&&!empty($email))
{
if(!($result=mysql_query($query,$database)))
{
print("Could not execute query");
die (mysql_error());//ose error
}
echo "YOU HAVE BEEN REGISTERED SUCCESSFULLY!You are the admin of this page";
}
else echo 'Fill in all the blank fields';
mysql_close($database);
?>
</body>
</html>
Here is my database
Add a check when inputting user data to the form. Check whether there are any rows where the field admin is set to 1 (or whatever you use)
Sample code for that
$result = mysql_query("SELECT firstname FROM mytable WHERE admin=1");
if(mysql_num_rows($result)== 0) {
//check if the post variables are set and input the values to the table
} else {
// Admin already exist
}
As mentioned in comments, you should stop using mysql_, and use mysqli_ or PDO with prepared statements instead, an example is given below. Keep in mind that you cannot mix APIs, so your entire code will have to be converted from one to the other.
$mysqli = new mysqli("host", "user", "password", "database");
$result = $mysqli->query("SELECT firstname FROM mytable WHERE admin=1");
if ($result->num_rows == 0)
//check if the post variables are set and input the values to the table
} else {
// Admin already exist
}
Reference
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
Choosing an API
$mysqli->prepare (for prepared statements)
Related
I'm a novice at mysql having trouble with inserting fields. I have created a login form and a homepage form for users to enter personal details. The login form submitted to mysql database fine, but the personal details form refused to submit; only when I specified the same fields as the first form did the form submit. Obviously, I would like to add new data in the second form, and I would appreciate tips on organizing my database, which consists of a single table profile.It stores info on every user including fields: id,username,password,avatar,location,goal, etc.
Appreciate your help & patience. I will combine the info from the two forms into a user record eventually. Right now, though, I would like to know why no new entry is created or error message displayed even though my error display is turned on.
EDIT:: sorry for not including whole code
loginform.php (works fine)
<?php
require("connect.php");
session_start();
$query = "SELECT * FROM `profile`";
if ($query_run=mysqli_query($cnn,$query))
{
echo "
<h1>Sign up for Runners World</h1>
<form action='' method='post'>
Username: <input type='text' name='username'><br>
Email: <input type='text' name='email'><br>
Password: <input type='text' name='pw'><br>
<input type='submit' name='submit' value='submit'>
</form>
";
}
else {
die("<br>could not connect to table");
}
?>
<?php
if (isset($_POST['submit']))//if you submitted the form
{
$username = $_POST['username'];
$password = $_POST['pw'];
$email = $_POST['email'];
if ($username and $password and $email)
{
$addLogin = "INSERT INTO profile (username,email,password) VALUES ('$username','$email','$password')";
$success = $cnn->query($addLogin);
if ($success)
{
$_SESSION['name']="$username";
echo("<script>location.href = 'homePage.php';</script>");
}
else
{
die("login data failed to reach database");
}
}
else {echo "please fill out all the fields";}
}
else {
$submit=null;
echo 'no form submitted';
}
?>
addDetails.php (not submitting)
<?php
session_start();
error_reporting(E_ALL);
ini_set("display_errors",1);
require("connect.php");
require("login.php");
echo "<h1>Welcome ".$_SESSION['name']."</h1>";
echo "<form action='' method='post'>
Avatar: <input type='text' name='avatar'><br>
Location: <input type='text' name='location'><br>
Descripiton: <input type='text' name='about'><br>
Daily Goal: <input type='text' name='goal'><br>
<input type='submit' value='submit' name='submit'>
</form>
";
$avatar = $_POST['avatar'];
$location = $_POST['location'];
$goal = $_POST['goal'];
$about = $_POST['about'];
if (isset($_POST['submit']))
{
$sql = "INSERT INTO profile (avatar,location,goal) VALUES ('$avatar','$location','$goal')";
if ($cnn->query($sql)===TRUE)
{echo "you have inserted profile fields";}
else
{echo "sqlQuery failed to insert fields";}
}
?>
If you want to add data to a row that already exists, look up the UPDATE command in SQL
You should change the Sql statement in 'addDetails.php' to:
UPDATE profile
SET avatar={$avatar}, location={$location}, goal={$goal}
WHERE id={$id}
By the way you should never ever use this statement in your production, it is not safe, you should keep in mind to prevent Sql injection.
I've created this registration form and i want to insert a text file like CV in mysql database named st_login including the table named login.In the following code i've only created a form for registration purposes and want to insert also an option allowing the user to insert a text file (CV)into the registration form and this text file to be saved into that database using Php.
This is my php code:
<html >
<head>
<title></title>
</head>
<body>
<?php
print ("<form action='register.php' method='post'>
<p>Name
<input type='text' name='firstname' />
</p>
<p>Surname
<input type='text' name='lastname' />
</p>
<p>Username
<input type='text' name='username' />
</p>
<p>Password
<input type='password' name='password' />
<p/>
<input type='submit' value='Register'/>
</form>");
extract ($_POST);
if( !($database=mysql_connect("localhost","root",""))||!(mysql_select_db("st_login",$database)) )
print("Could not connect");
if(isset($_POST['firstname'] )&&isset($_POST['lastname'])&&isset($_POST['username'])&&isset($_POST['password']) ){
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$username=$_POST['username'];
$password=$_POST['password'];
$query = "INSERT INTO login (firstname, lastname, username,password) VALUES ('$firstname', '$lastname', '$username','$password')";
}
if ( !empty($firstname)&&!empty($lastname)&&!empty($username) &&!empty($password) )
{
if(!($result=mysql_query($query,$database)))
{
print("Could not execute query");
die (mysql_error());//ose error
}
else echo "You have been registered successfully";
}
else echo "Fill in all the blank fields";
mysql_close($database);
?>
</body>
</html>
I was wondering if someone could give me a hand. My browser is executing most of my php code, but when it gets to certain line, it prints the code instead of executing it.
My code is:
<!DOCTYPE html>
<html>
<body>
<?php
//Display registration form
function register_form(){
$date = date('D, M, Y');
echo <form action='?act=register' method='post'>
Username: <input type='text' name='username' size='30'><br>
Password: <input type='password' name='password' size='30'><br>
Confirm your password: <input type='password' name='password_conf' size='30'><br>
Email: <input type='text' name='email' size='30'><br>
<input type='hidden' name='date' value='$date'>
<input type='submit' value='Register'>
</form>;
}
?>
<?php
//Register users data.
function register(){
//Connecting to database
$connect = mysql_connect("localhost", "username" "password");
if(!$connect){
die(mysql_error());
}
//Selecting database
$select_db = mysql_select_db("database", $connect);
if(!$select_db){
die(mysql_error());
}
?>
<?php
//Collecting info
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$pass_conf = $_REQUEST['password_conf'];
$email = $_REQUEST['email'];
$date = $_REQUEST['date'];
//Check input fields
if(!empty($username)){
die("Please enter your username!<br>");
}
if(!empty($password)){
die('Please enter your password!<br>');
}
if(!empty($pass_conf)){
die("Please confirm your password!<br>");
}
if(!empty($email)){
die("Please enter your email!");
}
?>
<?php
//Check username availability
$user_check = mysql_query("SELECT username FROM users WHERE username='$username'");
$do_user_check = mysql_num_rows($user_check);
//Check if email availability
$email_check = mysql_query("SELECT email FROM users WHERE email='$email'");
$do_email_check = mysql_num_rows($email_check);
//Display errors
if($do_user_check > 0){
die("Username is already in use!<br>");
}
if($do_email_check > 0){
die("Email is already in use!");
}
//Check if passwords match
if($password != $pass_conf){
die("Passwords don't match!");
}
?>
<?php
//Register user
$insert = mysql_query("INSERT INTO users (username, password, email) VALUES ('$username', '$password', '$email')");
if(!$insert){
die("There's little problem: ".mysql_error());
}
echo $username.", you are now registered. Thank you!<br><a href=login.php>Login</a>" ;
}
?>
<?php
switch($act){
default;
register_form();
break;
case "register";
register();
break;
}
?>
</body>
</html>
It prints a lot of the closing ?> tags, but if I remove the tag as well as its opening counterpart, it prints all the code that was between. I've been stuck on this for the last few days and really need some help. Thanks in advance.
UPDATE
I figured it out. I was executing from the directory instead of the address. (not sure if I worded that right). So instead browser pointing to registration page from "http://localhost:port/register.php" it was pointing to "file:///C:/xampp/htdocs/register.php"
Put double quotes around anything you to be echoed since there are single quotes used inside the strings. A simple example:
Ps. you have some other syntax errors as well, but if only you care.
One of them on line 45: $connect = mysql_connect("localhost", "username" "password"); this is definitely not the way it should be. Even if it was;
Notice the missing comma after `"username". Should have been like:
$connect = mysql_connect("localhost", "username", "password");
For the current problem, try this:
<?php
//Display registration form
function register_form(){
$date = date('D, M, Y');
echo "<form action='?act=register' method='post'>
Username: <input type='text' name='username' size='30'><br>
Password: <input type='password' name='password' size='30'><br>
Confirm your password: <input type='password' name='password_conf' size='30'><br>
Email: <input type='text' name='email' size='30'><br>
<input type='hidden' name='date' value='$date'>
<input type='submit' value='Register'>
</form>;";
}
?>
You need to put double quotes around your echoed strings. (double, since you use single quotes inside your tags). If you remove the php-tags, it will be interpreted as just HTML i.e. it will just be sent out to the browser.
If for some reason you hate quotes, you might like to do it as a here document:
echo <<<EOF
<form action='?act=register' method='post'>
Username: <input type='text' name='username' size='30'><br>
...
EOF
There's also at least one missing comma in you code, which will keep that part from executing (in mysql_connect).
B.t.w. you shouldn't use the mysql_*-type functions anymore. They are marked deprecated and are prone to make your code succeptible to SQL injection attacks. I recommend working into PDOs.
And just for wiw, as someone already mentioned in the comments it is not the browser that executes this code. PHP is interpreted by the webserver. The only scripting language that is actually executed browserside is still javascript (correct me if I'm wrong.).
This is probably not secure but ignore that.
Ive made a simple homepage with login, registration and logout. But im having a problem storing the password in my database. It somewhat looks hashed/salted.
I dont understand much when Im not hashing it myself. In fact I have no experience with salting at all, so please dont come with a professional solution.
This is how it looks like in the database after registration:
The database has the following attributes: id, username, password, email:
9, test, *94BDCEBE19083CE, test#mail.com
But should look like this:
9, test, test, test#mail.com
My registration.php looks like this:
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<?php
// loggin in and selects the database
include ("dbConfig.php");
//Input vaildation and the dbase code
if ( $_GET["op"] == "reg" )
{
$bInputFlag = false;
foreach ( $_POST as $field )
{
if ($field == "")
{
$bInputFlag = false;
}
else
{
$bInputFlag = true;
}
}
// If we had problems with the input, exit with error
if ($bInputFlag == false)
{
die( "Problem with your registration info. "
."Please go back and try again.");
}
// Fields are clear, add user to database
// Setup query
$q = "INSERT INTO dbUsers (username, password , email ) "
."VALUES ('".$_POST["username"]."', "
."PASSWORD('".$_POST["password"]."'), "
."'".$_POST["email"]."')";
// Run query
$r = mysql_query($q);
// Make sure query inserted user successfully
if ( !mysql_insert_id() )
{
die("Error: User not added to database.");
}
else
{
// Redirect to thank you page.
Header("Location: register.php?op=thanks");
}
} // end if
//The thank you page
elseif ( $_GET["op"] == "thanks" )
{
echo "<form action='members.php' method='POST'>";
echo "<div class='panel'> <span><font color='lime'>Thanks for registering!</font></span>";
echo "<label><input type='submit' class ='button' value='Back'></label></div></form>";
}
//The web form for input ability
else
{
echo "
<div class='box'>
<h1>Registration</h1>
<form action=\"?op=reg\" method=\"POST\">
<label>
<span>Username</span>
<input autocomplete='off' class='input_text' name='username'>
</label>
<label>
<span>Password</span>
<input autocomplete='off' class='input_text' type='password' name='password'>
</label>
<label>
<span>Email</span>
<input autocomplete='off' class='input_text' name='email'>
</label>
<label>
<input type='submit' class='button' value='Registrer'>
</label>
</form>
</div>";
}
?>
</body>
</html>
Just remove the PASSWORD() function from the SQL statement.
So you have to modify your code like this:
$q = "INSERT INTO dbUsers (username, password , email ) "
."VALUES ('".$_POST["username"]."', "
."'".$_POST["password"]."', "
."'".$_POST["email"]."')";
Beware that this is unsecure because a SQL injection is possible. You can use prepared statements with the mysqli_* functions to prevent this. If you cannot use mysqli_* you can also use mysql_real_escape_string().
Your code would then look like this:
$q = "INSERT INTO dbUsers (username, password , email ) "
."VALUES ('".mysql_real_escape_string($_POST["username"])."', "
."'".mysql_real_escape_string($_POST["password"])."', "
."'".mysql_real_escape_string($_POST["email"])."')";
i'm new to PHP. I created a microsoft access database with user A and pw 123 (testing). I tried to find on the website but unfortunately I can't find any that can actually lead me to authenticate against MS Access, most of the website is purely about SQL, which is what i really do not want, please help!
Currently here are my codes
Login.php
<html>
<body>
<?php
session_start();
// dBase file
include "database.php";
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Please log in your employee ID and Password to apply for leave.</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<div class='short_explanation'>* required fields</div>
<br>
<label for='username'>UserName*:</label>
<input type='text' name='username' id='username' maxlength="50" />
<br>
<label for='password'>Password*: </label>
<input type='password' name='password' id='password' maxlength="50" />
<br><br>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
Database.php
<?php
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$conn=odbc_connect("employee","","") or die (odbc_errormsg());
if (!$conn )
{
exit
("Error connecting to database: ".$conn);
}
// Then you need to make sure the database you want
// is selected.
$sql = "SELECT * FROM empTable";
$rs=odbc_exec($conn,$sql);
?>
How do i continue from here? Thank you! Please note that I can only authenticate everything with MS Access 2003.
session_start();
// Get the data collected from the user
$Username =$_POST["username"];
$Password =$_POST["password"];
if (!$conn = new COM("ADODB.Connection"))
exit("Unable to create an ADODB connection");
$strConn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("DATABASEFILE");
$conn->open($strConn);
$strSQL = "SELECT username, password FROM accounts WHERE username = '$Username' AND password = '$Password'";
$rs = $conn->execute($strSQL);
if (!$rs->EOF)
{
if ( $rs->Fields["Username"]->value
&& $rs->Fields["Username"]->value == $Username
&& $rs->Fields["Password"]->value
&& $rs->Fields["Password"]->value == $Password
)
{
$_SESSION["authenticatedUser"] = $Username;
// Relocate to the logged-in page
header("Location: loggedon.php");
}
}
else
{
$_SESSION["message"] = "Login Error as $Username. " ;
header("Location: admin.php");
}