This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 2 years ago.
I am having issues denying the registration of existing users. please see code below, and further details below that.
<?php
//connect to sql
$con=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//pull user id from form input
$uid=$_POST[uid];
//make sure input is not blank
if($uid==""){echo 'Please enter a username.';exit();}
//make sure it is alphanumeric input only
if(!ctype_alnum($uid)){echo 'The username chosen must be alpha-numberic (A-z,0-9),
without special characters. Please use the back button in your
browser to try again using only alpha-numeric input.';exit();}
//check if user exists
$query=mysqli_query($con, "SELECT * FROM user WHERE uid='$uid'");
if(!$query){die 'query failed to execute';}
if(mysqli_num_rows($query)!=0){echo 'user already exists. Use back button and enter a new username'; exit();
}
//insert record into DB
$sql= "INSERT INTO user (uid, addr, password, passwordlastchanged, email)
VALUES
('$uid', '$_POST[addr]', '$_POST[pwd]','today', '$_POST[email]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
So when I input through my form it works fine, its just that if I try to register an already existing username, it allows it, when I have setup the query to look for an existing entry and cancel if it finds it (or so i thought...).
can you see what I am doing wrong? again I want it to check for the user name and deny further action if it finds it..
I know this is probably lacking in security, I am unfortunately learning as I go so just getting things to work comes first :) Although security suggestions will be logged and considered at the right time.
I spent an enormous amount of time researching this and I feel like I've tried a lot of various query/ function combos.
Try
if(mysqli_num_rows($query)>0)
instead of
if(mysqli_num_rows($query)!=0)
Related
I am currently looking to run a basic insert query using PHP to submit HTML form data to MySQL database.
Unfortunately however the insert process isnt running.
In my Insert syntax I have tried including $_POST[fieldname], ive tried including variables as below, and ive even played around with different apostrphes but nothing seems to be working.
as a side dish, im also getting truck load of wamp deprication errors which is overwhelming, ive disabled in php.ini and php for apache.ini file and still coming up.
If anyone can advise what is wrong with my insert and anything else id be much thankful.
Ill keep this intro straightfoward.
Person logs in, if they try to get in without login they go back to login page to login.
I connect to database using external config file to save me updating in 50 places when hosting elsewhere.
Config file is working fine so not shown below.
database is called mydb.
Im storing the text field items into variables, then using the variables in the insert query.
unitID is an auto increment field so I leave that blank when running the insert.
Unfortunately nothing is going in to the mysql database.
Thanks in advance.
PS the text fieldnames are all correctly matched up
<?php
//Start the session
session_start();
//check the user is logged in
if (!(isset($_SESSION['Username']) )) {
header ("Location: LoginPage.php?i=1");
exit();
}
//Connect to the database
include 'config.php';
$UserName = $_SESSION['Username'];
$UserIdentification = $_SESSION['UserID'];
if(isset($_GET['i'])){
if($_GET['i'] == '1'){
$tblName="sightings";
//Form Values into store
$loco =$_POST['txtloco'];
$where =$_POST['txtwhere'];
$when =$_POST['txtdate'];
$time =$_POST['txttime'];
$origin =$_POST['txtorigin'];
$dest =$_POST['txtdest'];
$headcode =$_POST['txtheadcode'];
$sql= "INSERT INTO sightings (unitID, Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('','$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
mysql_select_db('mydb');
$result=mysql_query($sql, $db);
if($result){
$allocationsuccess = "Save Successful";
header ('Refresh: 2; url= create.php');
}
else {
$allocationsuccess = "The submission failed :(";
}
}
}
?>
"unitID is an auto increment field so I leave that blank when running
the insert"
That's not how it works. You have to omit it completely from the INSERT statement. The code thinks you're trying to set that field to a blank string, which is not allowed.
$sql= "INSERT INTO sightings (Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
should fix that particular issue. MySQL will generate a value automatically for the field and insert it for you when it creates the row.
If your code had been logging the message produced by mysql_error() whenever mysql_query() returns false then you'd have seen an error being generated by your query, which might have given you a clue as to what was happening.
P.S. As mentioned in the comments, you need to re-write your code with a newer mysql code library and better techniques including parameterisation, to avoid the various vulnerabilities you're currently exposed to.
I am sending customer information from the webplatform Second Life via a weblink and php to an SQL server. My SQL server is hosted by the biggest web hosting company in Europe, so I wouldn't expect an error from their end.
I have written a very simple PHP script that translates the information for the database, something that I have done many times successfully. This time a very unexpected error occured: When I test the URL including the variables, then I get following message: The requested URL / was not found on this server ...
THis is the PHP code:
<?php
//You need to insert your specific data for "DB_HOSTNAME","DB_USERNAME","DB_PASSWORD","DB_DATABASE"
$con=mysqli_connect("DB_HOSTNAME","DB_USERNAME","DB_PASSWORD","DB_DATABASE");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//use the parameters in the http-link to set the $ variables and real escape them for security reasons
$key = mysqli_real_escape_string($con, $_GET['key']);
$name = mysqli_real_escape_string($con, $_GET['name']);
$pass = mysqli_real_escape_string($con, $_GET['pass']);
$mailinglist = "1";
//Insert the $ variables into the table
$sql="INSERT INTO SAGS_Global_Players (key, name, pass, mailinglist) VALUES ('$key', '$name', '$pass', '$mailinglist')";
//for debugging: print out the db query on the screen
//echo $sql . '<br/>';
if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }
//close connection to database
mysqli_close($con); ?>
The web address "http://webaddress/8ftgde/newplayer.php&key=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX&name=estelle.pie&pass=6fcrV1vZUC&mailinglist=1"
gives the result:
Not Found
The requested URL http://webaddress/8ftgde/newplayer.php&key=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX&name=estelle.pie&pass=GpTIVOavhc was not found on this server.
If I use the same address without the variables (= http://webaddress/8ftgde/newplayer.php), then a new database entry is created. But (of course) only the auto incremented customer number and the constant variable "1" for mailinglist are entered.
Help anyone?
Please check your .htaccess file if there any change made this error
I am putting Scott's comment up as answer. If you want to do it yourself Scott, then I will mark it with best answer. I did the most stupid mistake possible: I forgot to put a question mark before my variables in the link. Shame on me!
So what I am trying to do is a very basic and straight way of inserting a record into mysql db.
It is just something I have done few times before, however for some reason it is not working with me this time.
So in the following couple of lines of code I will show my code, which basically do the following
1- Check if the user exists in the DB (An existing user is a user with the same email)
2- If the user exists in the DB then it sends an http response with a status code of 409 which means duplication.
(Anyway note that this works perfectly, which implies the connection was made successfully to the DB, and it was able to retrieve any exact user, if any)
3- If the user does not exist it should be inserted in the DB (Here is the problem)
My Code
//Checking if the user exist
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
// Close Connection
mysql_close($con);
echo "409";
}
else{
mysql_query("INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')",$con);
// Select the record
$user_id = mysql_insert_id();
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
// Close Connection
mysql_close($con);
echo "200 " . $result['username'];
}
I googled the possible solutions for this issue, however all similar issues I went through were because of syntax errors.
Any suggestions? Thanks in advance :)
What is the exact error message you are getting? Copy/paste that here, please.
Also, the only odd thing I see is that you are doing the SELECT commands with a variable $table_name, and in the INSERT command you are hard-coding a table name..? Maybe that's it?
INSERT INTO samam_users ...
just put the same table name variable there?
INSERT INTO $table_name ...
Let me know if this helps. :)
$sql = "INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')";
if(!mysql_query($sql,$con)) {
die(mysql_error());
}else {
echo 'inserted succesfully';
}
mysql_error() will give you information about why your query isn't working - allowing you to debug it.
Also don't use mysql_*, it's going to be deprecated and there are much better more secure options like MySQLi or preferably PDO
I think you have to put all the values in INSERT command in double quotes instead of single quote
I am new to both PHP and MySQL, however I am currently learning both in order to create a basic website to administrate my RADIUS accounts. (I've switched to using MySQL for user authentication)
I have made a script that inserts user values into the database, however I need to make it so as if a user account already exists, a duplicate can't be created.
I was using a tutorial I found to try and create this, and it does work to an extent. When I add the user when there is no duplicate account, I am returned the message "Successful" however when there is a duplicate user, the page that is returned is blank, and I'm not sure what I'm doing wrong. Its workable, but annoying.
I am also curious if it is possible to create a pool of numbers (These will be IP Address's) and then have it so that when a new user is created, a number from this pool is used, and then removed from that pool. By doing this I hope I could automate assigning IPs to users without having to have someone manually add them every time a new user is created. Currently to achieve a slightly less desirable approach I made another script that displays a list of users IP address's from my table so that one can just add an IP that isn't on this list. Any advise on where I could learn to do this would be greatly appreciated, I don't know where to start.
Below is the php code that I am using, and the html code for the form. Thank you for any help or advise.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_USER','root');
define('DB_PASSWORD','123');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function AuthAccount()
{
$username = $_POST['username'];
$value = $_POST['value'];
$query = "INSERT INTO radcheck(username, attribute, op, value) VALUES ('$username', 'Cleartext-Password', ':=', '$value')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "User added to authentication database";
}
}
function AddAccount()
{
if(!empty($_POST['username']))
{
$query = mysql_query("SELECT * FROM radcheck WHERE username = '$_POST[username]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query) or die(mysql_error()))
{
AuthAccount();
}
else
{
echo "Username already registered";
}
}
}
if(isset($_POST['submit']))
{
AddAccount();
}
?>
Sign-Up Page:
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-Up</title>
</head>
<body id="body-color">
<div id="Sign-Up">
<fieldset style="width:50%"><legend>Registration Form</legend>
<table border="0">
<form method="POST" action="SignUp.php">
<tr>
<td>Username</td><td> <input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td><td> <input type="text" name="value"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</form>
</table>
</fieldset>
</div>
</body>
</html>
Your approach is riddled with problems:
You have introduced a race hazard, whereby two sessions simultaneously attempting to register the same username may both end up passing through the SELECT test before either one has proceeded to INSERT.
If you are using a transactional storage engine (such as Innodb), one can resolve this issue through proper use of transactions and locking reads, but it's far easier simply to impose a uniqueness constraint within the database and leave MySQL to do the rest:
ALTER TABLE radcheck ADD UNIQUE (username)
You can then simply go straight to INSERT and, if the username already exists, an error will be raised that you can handle accordingly.
You are not escaping your string literals when inlining them into your SQL. This is not only a (serious) security vulnerability, but it also introduces a bug whereby your code will break should someone post a username or password that contains a ' character. Passing literal values as parameters to prepared statements avoids these issues.
You are using an ancient PHP extension to access MySQL. It has not been updated since 2006 and its use has been explicitly discouraged in the PHP manual since 2011. As of PHP v5.5, it is deprecated and it will be removed from PHP altogether in a future version. You should switch to either the improved MySQL extension, PHP Data Objects or a third party abstraction layer.
You are storing plaintext passwords in your database. This not only poses a considerable risk to the security of your application in the event that your database is compromised, but it furthermore poses much wider risks to your users (since it is likely that they use the same passwords for other accounts). For their sake, you should always hash every password with salt; you should also be careful to protect their passwords between their browser and your server, e.g. using HTTPS.
As regards the assignment of IP addresses, your question provides no detail on how such addresses are chosen or for what they are used. Usually one leaves such matters to existing services such as DHCP, which only require configuring according to your policy requirements.
i think if(!$row = mysql_fetch_array($query) or die(mysql_error())) is not correct.
I would do it like this:
class db {
public static function dbFactory($host, $dbase, $user, $pass) {
$pdo = new PDO("mysql:host=$host;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
$db = db::dbFactory('localhost','mydbname','myusername','mypassword');
$db->beginTransaction();
try {
$stmt = $db->prepare("SELECT COUNT(*) as cnt FROM radcheck WHERE username = :uname");
$stmt->bindValue(':uname',$_POST[username]);
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_ASSOC);
if($res['cnt'] == 0) {
// go on ...
}
$db->commit();
} catch (Exception $e) {
$db->rollBack();
}
I have created a form in HTML and the action is set to a php script. I'm pretty new to php and was wondering if someone could help me out with it? I need to write a script to add the info from the form to a database. I need to create the database and the table as well. I did a lot of reading on the net and I'm still unable to do it. This is the script I have. Please tell me what mistakes I have made. Thank you for all the help.
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
$sql="CREATE DATABASE user";
if (mysql_query($con,$sql)) {
echo "Database user created successfully";
}
$sql="CREATE TABLE Persons(PID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(PID),firstName CHAR(30),lastName CHAR(30),age INT, dateofbirth DATE, email CHAR(30)";
if (mysql_query($con,$sql)) {
echo "connected to database";
}
$sql="INSERT INTO Persons (firstName, lastName, age, dateofbirth, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
if (mysql_query($con,$sql)) {
echo "added to database";
}
mysql_close($con);
?>
I tried all the suggested answers and still not able to do it. Can someone please provide the code to do that? I need to obtain data from a form and insert it into a database using php!
Hi Try This Code,
$con=mysql_connect("example.com","peter","abc123");
$sql="CREATE DATABASE user";
if (mysql_query($sql))
{
echo "Database user created successfully";
}
1.- Don't use mysql_ functions because are deprecated, use mysqli_ functions or PDO instead.
2.- You have several error i guess, first of all you select a database my_db on the connection script, but you are created another database in the next line... it's very strange this behaviour. If this script executes every time then you should change your code (you can't create a database and a table every time.
In the insert string you have an error with the post code, try this:
$sql="INSERT INTO Persons (firstName, lastName, age, dateofbirth, email) VALUES ('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['age']}','{$_POST['dateofbirth']}','{$_POST['email']}')";
Your CREATE TABLE query will fail because of syntax error. You have to check queries results especially when next query depends on previous (and you're doing operations like creating databases/tables).
Next thing to change is mysql_*. This functions are deprecated and instead you should use PDO or mysqli_* (they are not hard to learn, just try).
And one more important change have to be done in your script. You're getting user input and adding it to query. Don't do that! You have to always assume that user is trying to hack you, so all inputed data have to be checked and filtered. Also it's good to use prepared statements with such data.
if (mysql_query($con,$sql)){
echo "Database user created successfully";
} else {
echo 'Error creating database - ' . mysql_error();
}
Same thing for all your sql statements to see where you went wrong
Change your code (mysql_query($sql)) instead of (mysql_query($con,$sql))