user registration php - php

<?php
include"include/connection.php";
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "insert into employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values ('".$_POST['first_name']."','".$_POST['last_name']."','".$_POST['gender']."','".$_POST['email']."','".$_POST['username']."','".$_POST['password']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['city']."','".$_POST['country']."')";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
This is my code for inserting registration form data into a database. This code adds the data but also gives a parse error, but does not give the error if the username already exists.
Notice: Undefined variable: username in C:\Program Files\EasyPHP5.3.0\www\register_hirer2.php on line 6
Thanks for registration
line 6 is:
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");

Well, your $username is undefined indeed.
Most probably you want to use $_POST['username'].
And of course this obligatory XKCD comic:

If the "data source" is an html form (supposedly using method="post") you have to use $_POST['username'] when register_globals is set to off (which is the default since ...ages). see http://docs.php.net/security.globals
Also have a read of http://php.net/manual/en/security.database.sql-injection.php
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values (". same mysql_real_escape_string() thing here for each parameter .")";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
You can also use prepared statements. This way you don't need/can't forget using an escaping function.
edit and btw: you don't need the SELECT before the INSERT in order to make the username unique. Actually it will make things even harder since now you have to deal with race conditions. You'd have to lock the table between those two queries.
If you add an unique index for the username in your table MySQL will not allow the insertion of a doublet but instead return a specific error code which your script can fetch and handle without the need of dealing with race conditions.
define('ER_DUP_ENTRY', 1062);
$mysql = mysql_connect('..', '..', '..');
mysql_select_db('..', $mysql) or die(mysql_error($mysql));
$fields = array(
'efname'=>'first_name',
'elname'=>'last_name',
'egender'=>'gender',
'eemail'=>'email',
'eusername'=>'username',
'epwd'=>'password',
'eadd'=>'address',
'ephone'=>'phone',
'ecity'=>'city',
'ecountry'=>'country'
);
$sqlparams = array();
foreach($fields as $sql=>$form) {
if ( !isset($_POST[$form]) ) {
die('missing post parameter '. $form);
}
$sqlparams[$sql] = "'".mysql_real_escape_string($_POST[$form], $mysql)."'";
}
$query = '
INSERT INTO
employer
'. join(', ', array_keys($sqlparams)) .'
VALUES
('.join(',', $sqlparams).')
';
// table:employer has been defined with "unique key idxName (eusername)"
$result = mysql_query($query, $mysql);
if ( false!==$result ) {
echo " Thanks for registration";
}
else if ( ER_DUP_ENTRY===mysql_errno($mysql) ) {
echo 'username already exists';
}
else {
echo 'an error occurred';
}

That is because you do not define $username anywhere. It looks as though you want to use $_POST['username']
mysql_query("SELECT * FROM employer WHERE eusername='{$_POST['username']}'");
Also, your code is vulnerable to a SQL Injection

You never define $usernameanywhere, so it gives that error because you are trying to use a variable that it doesn't have a value for.

This is most likely because you've not defined the '$username' variable. I presume that you're relying on this being populated from the incoming GET/POST data (most likely via the depreciated register_globals) which is bad practice.
As such, you'll need to either populate $username via $_POST or $_GET.
More importantly, you should update the insert query to escape the incoming 'untrusted' data using mysql_real_escape_string (e.g.: mysql_real_escape_string($_POST['username']), etc.)

As #Yacoby said your code is vulnerable to an SQL Injection to prevent it you can use mysqli or PDO , if you would like to use mysqli use the following code:
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = $conn->prepare("INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry)) values ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; // preparing the insert
$query->bind_param("ssssssssss" , $variable1 , $variable2 , $variable3 , $variable4 , $variable5 , $variable6 , $variable7 , $variable8 , $variable9 , $variable10); // binding parameters
$query->execute(); // sending the parameter values
$query->close(); // closing the query
$conn->close(); // closing the connection
if ($query) { // checking if the query has been executed with no errors
echo " Thanks for registration";
}
}
?>
BE SURE TO CHANGE THE $conn AND variables to whatever you want!

Related

Wordpress: PHP delete database row in foreach cycle

Hi guys I am very new to PHP development.
I am writing a smiple script to get and email perameter from the url, cycle through some rows in a database table and delete the row if it is found.
I have got everything except the deleting of the row. I would really appreciate someone talking me through my mistake to help me understand. I think the error lies in the WHERE condition.
The error message I get is:
ERROR: Could not able to execute DELETE FROM wp_email_address_db WHERE alaofolasade#yahoo.com==alaofolasade#yahoo.com.
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
//sanatise and lowercase email addy from URL
$emailToRemove = filter_var ( strtolower($_GET["usermail"]), FILTER_SANITIZE_EMAIL);
//get DB table
$data = $wpdb->get_results("SELECT * FROM wp_email_address_db`");
foreach ($data as $d) {
//sanatise and lowercase email addy from DB
$email = filter_var ( strtolower($d->email_address), FILTER_SANITIZE_EMAIL);
//check if the email addy is in this row
if($email == $emailToRemove){
//get info
echo 'true <br/>';
echo 'id: '.$d->id.'<br/>';
//I need to delete this row
$sql = "DELETE FROM wp_email_address_db WHERE $email = $emailToRemove";
if(mysqli_query($link, $sql)){
echo "Records were deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
}
// $columnTitles = ['id','email_address','imported_via'];
?>
You have a typo in email and the value in where clause should be within single quotes:
change this to:
$sql = "DELETE FROM wp_email_address_db WHERE email = '$emailToRemove'";
Your query should be this :
$sql = "DELETE FROM wp_email_address_db WHERE email = '$emailToRemove'";
It is always better to use quotation (single quote', double quote ") also defining the column with back-tick.
Query:
$sql = "DELETE FROM wp_email_address_db WHERE `email` = '".$emailToRemove."'";
Your main error is $email which should be the column name with back-tick here WHERE $email = $emailToRemove
Should not be the query something like
DELETE FROM wp_email_address_db WHERE email_field_name = '$emailToRemove'
instead of
DELETE FROM wp_email_address_db WHERE $email = $emailToRemove
In your query you are passing the value of $email as field name and I assume that the field alaofolasade#yahoo.com does not exist
Try replacing
$sql = "DELETE FROM wp_email_address_db WHERE $email = $emailToRemove";
with
$sql = "DELETE FROM wp_email_address_db WHERE '$email' = '$emailToRemove'";
I removed the foreach, you don't need to retrieve ALL the mails from your database.
Moreover I used the prepared statements to avoid SQL injections
This kind of script which perform delete query to database HAVE to be protected from all users. Only admins should be allow to this script
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
// WARNING: You should check the identity of the user performing this action, MySql DELETE action is dangerous
global $wpdb;
//sanatise and lowercase email addy from URL
$emailToRemove = filter_var ( strtolower($_GET["usermail"]), FILTER_SANITIZE_EMAIL);
$sqlDeleteQuery = '
DELETE
FROM wp_email_address_db
WHERE email = ?
';
$statement = mysqli_prepare($link, $sqlDeleteQuery);
// Bind the email to your query (the ? ), this avoid the SQL injection attack
$statement->bind_param('s', $emailToRemove);
if (false !== mysqli_stmt_execute($statement)) {
die('The MySql query failed ! Error : ' . mysqli_error($link));
}
$emailsDeleted = mysqli_stmt_affected_rows($statement);
echo sprintf('"%d" emails deleted', $emailsDeleted);
I can't try the above code, so please let me know if something is wrong :)
Solved it by:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
if (isset($_GET["usermail"])) {
global $wpdb;
$remove = filter_var(strtolower($_GET["usermail"]), FILTER_SANITIZE_EMAIL);
$wpdb->query("DELETE FROM wp_email_address_db WHERE email_address='$remove'");
echo "You have successfully been unsubscribed.";
}
?>

How to escape mysql blank and duplicate data using php

I am using this code to send data to mysql database and its functioning well though users are sending blank data and duplicating too.
<?php
require "conn.php";
$lostidno = $_POST ["lostidno"];
$phonenol = $_POST ["phonenol"];
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
$conn->close();
?>
How do I prevent this?
You can use trim function to remove spaces at the beginning and the ending of a string. After that you are able to check if the two parameters aren't empty:
<?php
require "conn.php";
$lostidno = trim($_POST["lostidno"]);
$phonenol = trim($_POST["phonenol"]);
if(!empty($lostidno) && !empty($phonenol))
{
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
if ($conn->query($mysql_qry) === TRUE) {
echo "Information Recieved!";
}
else {
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
}
$conn->close();
}
?>
You should also have a look at this to prevent SQL injections.
1. To avoid blank values
Check the values of variables before executing insert query on database using empty() PHP function.
2. Avoid duplicate values
You can do it in two ways, Either specify UNIQUE constriant in database TABLE or run SELECT query before inserting data into database.
//this to check the duplicate records
Fire the select query : select * from lostdb.lost where col1= $lostidno and col2 = $phonenol;
//this is to check the blank condition
if($lostidno !== "" && $phonenol != "")
{
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
}
The best way to prevent duplicates is to mark the unique database columns as UNIQUE
ALTER TABLE <table_name> ADD UNIQUE(<column_name>);
To prevent blank data from ever getting into the database you need to check them with a few modifications in the code you posted:
if( ($lostidnol != "") && ($phonenol != "") )
{
if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
{
//error
}
}
else
{
//Notify the user that they're trying to insert blanks
}
If you want to provide proper user experience you should also provide some client side validation using JavaScript or jQuery
Use trim function to remove blank spaces from string.
<?php
require "conn.php";
$lostidno = trim($_POST ["lostidno"]);
$phonenol = trim($_POST ["phonenol"]);
//Check record exist or not.
$unique_check = "select count(*) as cnt from lostdb.lost where lostidno='".$lostidno."' and phonenol='".$phonenol."'";
//Execute above query and check record already exist or not. If record not exist then only allow to insert it.
$result_unique_check = $conn->query($mysql_qry)->one();
$record_exist = $result_unique_check['cnt'];
if($record_exist > 0){
echo "Record alreay exist.";
}else{
//Insert new record
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
$conn->close();
}
?>

display message to let user know that the value already exist

I want to display an error message if the insert already exists.
I've made name unique in the database and if I enter the same value, it does not insert. Just as I wanted. Here is my code:
$query = "INSERT INTO register(name) VALUES('$foo')";
mysql_query($query) or die('An Error occurred' . mysql_error());
Now I want to echo a message to let the user know that the value he has entered is already present in the database and will not be inserted. Anyone?
I take it you are collecting $foo from a form?
what I would do is an sql query of the table register collecting the name field then when you collect the name entered in the form and its posted you can run an if condition against the name field you have already gathered using the sql statement and if there is a name = to the name they enter on the field they can receive a message and exit before the sql injection into the register table.
The simpliest way:
$res = mysql_query($query):
if ($res)
echo 'Insertion ok';
else
echo 'error: name already exists';
A better way: do first a SELECT query to see if name exists or not.
Note: you should think about moving from mysql_* to mysqli_* or PDO
Try this :
$query = "INSERT INTO register(name) VALUES('$name')";
$user = mysql_query($query):
if ($user)
echo 'User Register';
else
echo 'User Already Exist';
As per Melon's comment, you should use mysqli.
// Create your connection
$mysqli = new mysqli($host, $user, $pass, $dbname);
// Do your query
$mysqli->query("INSERT INTO register(name) VALUES('$foo')");
if($mysqli->affected_rows == 0) {
// Your chosen method of alerting the user goes here
}
\\this first part collects name information from your table.
$name="SELECT name FROM register";
$name_query = mysqli_query($db_conx, $name);
$numrows = mysqli_num_rows($name_query);
if($numrows < 1){
echo "cannot find user";
header ("location: index.php");
}
while ($row = mysqli_fetch_array($name_query, MYSQLI_ASSOC)){
$name = $row["name"];
}
\\ this part gets the name from your form
if (isset($_POST['class']) && ($_POST['class'] !='')){
$foo = $_POST['foo'];
\\this part checks to see if the 2 values are equal
if ($name == $foo){
echo "This name has already been used try again";
\\this part then adds the name if its not already in the database
}else{
$query = "INSERT INTO register(name) VALUES('$foo')";
mysql_query($query) or die('An Error occurred' . mysql_error());
}
}
//then all you need to do is create your form to post the foo or name so it can be collected and passed through the querys.

Trying to create login with cookies

I'm try to get cookies on to a browser. It's giving me parameter 1 error and parameter 3. This code works elsewhere on my site but not here. Can someone help me?
if ((!isset($_POST["uname"])) || (!isset($_POST["password"])))
{
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
exit;
}
$userpass = md5($_POST['password']);
#$db = mysqli_connect("$dbc_ser", "$dbc_usr", "$dbc_pwd", "$dbc_db");
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
AND password = PASSWORD('$userpass')";
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$result = mysqli_query($db, $sql);
while ($info = mysqli_fetch_array($result))
{
$id = stripslashes($info['id_files']);
$u_acct = stripslashes($info['uname']);
$name = stripslashes($info['name']);
$job_title = stripslashes($info['job_title']);
$location = stripslashes($info['company']);
$cell_num = stripslashes($info['cell_num']);
$office_num = stripslashes($info['office_num']);
$office_email = stripslashes($info['office_email']);
$login_right = stripslashes($info['login_right']);
$first_run = stripslashes($info['first_run']);
$attempts = stripslashes($info['attempts']);
$locked_out = stripslashes($info['locked_out']);
$land_page = stripslashes($info['land_page']);
}
}
Try debugging some of the individual variables. What is in $sql, for example? Is it correct?
Is the "Cannot connect" clause executed, or does it get to the query and fail there? (I am not sure what "parameter 1 error and parameter 3" means).
Don't forget to escape the 'email' value by the way - this code has an SQL injection hole.
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
This is not going to work the way you expect.
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
You need to read up on SQL injection.
while ($info = mysqli_fetch_array($result))
You allow multiple accounts with the same email address / password?????
It's giving me parameter 1 error and parameter 3
Couldn't you post the actual error message you get?
$id = stripslashes($info['id_files']);
WTF? Smartquotes?
I'm not sure i understand your question but the last time i checked anyone who wants to use cookies uses the $_COOKIE global variable, either for setting them or accessing them. $_POST is made to get stuffs from forms, not cookies.
Please check the manual for more details about $_COOKIE
Regards

How to find out if the following SQL statement is working

I'm fairly new to mysql and I was wondering if the following code should be working. I've been checking with my database after submission of this form and nothing is getting inputted into the database. Please let me know what I'm doing wrong, Thank you!
<?php
$username = $_SESSION['username'];
$email = $_POST['email'];
$desc = $_POST['desc'];
$url = $_POST['url'];
$priority = $_POST['priority'];
if( strlen($username) > 0 && strlen($email) > 0 && strlen($desc) > 0)
{
$sql = "INSERT INTO feature_request_table (username, desc, email, url, priority, status)
VALUES( '$username' , '$desc' , '$email' , '$url' , '$priority' , '0' )";
echo "The sql statement is: " . $sql . "</br>";
mysql_query($sql);
//echo "The result is: " . $results . "</br>";
echo "Your request have been sent. Please allow a brief period of time for your webmaster implement your request. Thank you!";
}
mysql_close($con);
?>
Use the return value of mysql_query() and check if it is NULL to find out if the query was successful:
$result = mysql_query($sql);
// A NULL value of $result indicates failure
if (!$result) {
// something went wrong!
// See the error...
echo mysql_error();
}
Also, we don't see in the posted code that mysql_connect() was called. Also check that the connection was successfully made:
$conn = mysql_connect(all the connection details...);
if (!$conn) {
// connection failed
}
One thing I haven't seen mentioned yet is that you may not have auto-commit turned on, in which case your insert will return TRUE, but you will not see any change in the DB until you commit the insert.
You should really use the isset() function instead of strlen. Also, it does look like your never actually connecting to a mysql server according to the given code. Try posting the sql statement that is echoed into phpMyAdmin directly.
Following are the changes you need to do.
Use the column name desc with some other name of enclose in 'desc'.
Always print the error message or even terminate the output.
Check whether the POST Items are received correctly or not.
Here is the modified code.
if( isset($username) && isset($email) && isset($desc) )
{
$sql = "INSERT INTO feature_request_table (username, 'desc', email, url, priority, status)
VALUES( '$username' , '$desc' , '$email' , '$url' , '$priority' , '0' )";
echo "The sql statement is: " . $sql . "</br>";
mysql_query($sql) or die (mysql_error());
//echo "The result is: " . $results . "</br>";
echo "Your request have been sent. Please allow a brief period of time for your webmaster implement your request. Thank you!";
}
This sould do it :
$data = mysql_query($sql);
if($data === false) { // TODO: better error handling
// Do something...
echo mysql_error();
// Or see the errors...
}
Note : if you want to have valid HTML pages in all situations handle your errors don't use OR DIE().

Categories