Problems php and MySQL - php

I have 2 tables, user log that is where the people make a register with their email and password, and another table with the name user where the people make complete their own profile.
How can I make with an SQL query to insert the data that insert in the form?
Taking into account that table user makes reference with table user log with the id...
I mean
User log
Id
Email
Password
User
Id
User_id fk id reference userlog(id)
Name
Surname
This is the code wich i made the log in
<?php
session_start();
if (isset($_SESSION['usuario'])) {
header('Location: index.php');
}
$errores = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var(strtolower($_POST['email']), FILTER_SANITIZE_STRING);
$password = $_POST['password'];
$password = hash('sha512', $password);
try {
$conexion = new PDO('mysql:host=localhost;dbname=DATABASE, 'USER', 'PASS');
} catch (PDOException $e) {
echo "Error:" . $e->getMessage();;
}
$statement = $conexion->prepare('
SELECT * FROM userlog WHERE email = :email AND password = :password'
);
$statement->execute(array(
':email' => $email,
':password' => $password
));
$resultado = $statement->fetch();
if ($resultado !== false) {
$_SESSION['usuario'] = $resultado;
header('Location: index.php');
} else {
$errores .= '<li>Datos Incorrectos</li>';
}
}
I make a var_dump() to see what the array in $resultado bring, and it brign me the data of the table, but, when I want to use the data to fill an input it fails

If your data will be coming from POST method, please always use precautions to avoid SQL injection..
I will be using a very elementary example. You can enhance this one for your own use.
$servername = "localhost";
$username = "yourUser";
$password = "yourPass";
$dbname = "youtDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sql = "INSERT INTO Userlog (email, password)
VALUES ('some_email#example.com', 'some_safe_password')";
$conn->exec($sql);
$last_id = $conn->lastInsertId();
$userSql = "INSERT INTO Userlog (userId, name, lastName) VALUES ($last_id, 'some_name', 'some_lastName')";
$conn->exec($userSql);
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

You can pass your data by using post method.
try this code.
$sql = "INSERT INTO users (Userlog, Id, Email, Password)
VALUES ('".$_POST["Userlog"]."','".$_POST["Id"]."','".$_POST["Email"].",'".$_POST["Password"]."')";

Related

How to get logged users user_id from the database and insert it to another table?

I've been trying to get logged persons user_id which is in user_login table in my database and insert it to the another table.
What I know is, get the user_id from the user_login using query and assign that query to the SESSION variable and put that variable in another query where I want to insert it in the table but I'm unable to write a perfect code for it.The only thing I'm achieving is it taking the user_id as 1 in the new table.It would be a great help if you can review my code correct it.
<?php
ob_start();
include ('header.php');
require('includes/connect.php');
require('includes/product.php');
$product = new Product;
if(isset ($_GET['id'])) {
$id = $_GET['id'];
$data = $product -> fetch_data($id);
if(isset($_POST['add'])){
if (isset($_SESSION['logged_in'])) {
$query = $pdo->prepare("SELECT user_id FROM user_login ");
$user_id=$query->execute();
$_SESSION['user_id']['id']=$user_id;
$query = $pdo -> prepare("INSERT INTO cart_items(product_id , user_id, Price) VALUES (?,?,?)");
$query -> bindValue(1, $id);
$query -> bindValue(2, $_SESSION['user_id']['id']);
$query -> bindValue(3, $data['new_price']);
$query ->execute();
header('location:cart.php');
}
else{
header('location:Login Page.php');
}
}
?>
This is where I have done the user validation while logging in (connect.php)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "ecom";
try{
$pdo = new PDO('mysql:host=localhost;dbname=ecom','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
exit('Database error.');
}
function login(){
global $pdo;
$username = $_POST['email'];
$password = md5($_POST['password']);
if(empty($username) or empty($password))
{
$error = "Please fill all the fields";
}
else
{
$query = $pdo->prepare("SELECT * FROM user_login WHERE name = ? AND password = ? ");
$query->bindValue ( 1, $username);
$query->bindValue ( 2, $password);
$query->execute();
$num=$query->rowCount();
if($num==1) {
$_SESSION['logged_in']= true;
//header('location :' .$_SESSION['redirectURL']);
header('location: index.php');
exit();
}
else{
$error = "Please enter correct Username and Password";
}
}
}
?>
Thank you in advance.
replace your else part with this code
$query = $pdo->prepare("SELECT * FROM user_login WHERE name = ? AND password = ? ");
$query->bindValue ( 1, $username);
$query->bindValue ( 2, $password);
$query->execute();
$data = $query->fetchAll(PDO::FETCH_ASSOC);
$num=$query->rowCount();
if($num==1) {
$_SESSION['logged_in']= true;
$_SESSION['user_id'] = $data[0]["user_id"];
//header('location :' .$_SESSION['redirectURL']);
header('location: index.php');
exit();
} else{
$error = "Please enter correct Username and Password";
}
then you can get user id from session

insert user id in another table during registration

I have a registration form that captures email and password. Once the form is submitted it will add an AUTO_INCREMENT userid, email, and password into my users table. During this same submit process I would like to add the ID that was created in my users table to a users_preferences table.
Here is what I currently have:
require("config.php");
if(!empty($_POST))
{
// Ensure that the user fills out fields
if(empty($_POST['username']))
{ die("Please enter a username."); }
if(!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL))
{ die("Invalid E-Mail Address"); }
if(empty($_POST['password']))
{ die("Please enter a password."); }
// Check if the username is already taken
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array( ':username' => $_POST['username'] );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$row = $stmt->fetch();
if($row){ die("This email address is already registered"); }
// Add row to database
$query = "
BEGIN;
INSERT INTO users (
username,
password,
salt
) VALUES (
:username,
:password,
:salt
) ;
INSERT INTO user_preferences (
user_id
) VALUES (
$user_id
);
COMMIT;
";
$user_id = mysql_insert_id();
// Security measures
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++){ $password = hash('sha256', $password . $salt); }
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
header("Location: index.php");
die("Redirecting to index.php");
}
The registration of the user will go through and add the data to the database, but no data is added to the user_preferences table. How do I get this to add the last user id to the second table?
The problem as I see it is that you are trying to put the value of $user_id into the query, yet it would only receive a value in the next command row (although you're not actually running the first query, you're just trying to fetch the last inserted id).
You should first run the INSERT INTO users... query, then retrieve the last inserted id, then run the second query (INSERT INTO user_preferences...).
Also assuming you're using PDO, last inserted id should be $db->lastInsertId() in your context.
** Update
Alright, without changing your code, just mostly refactoring it a tad bit, you should try something like this:
function checkDataValidity(){
if(empty($_POST['username'])){
throw new Exception("Please enter a username.");
}
if(!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL)){
throw new Exception("Invalid E-Mail Address");
}
if(empty($_POST['password'])){
throw new Exception("Please enter a password.");
}
}
function doesUserExist($dbHandler){
$query = " SELECT 1 FROM users WHERE username = :username;";
$query_params = array( ':username' => $_POST['username'] );
$stmt = $dbHandler->prepare($query);
$result = $stmt->execute($query_params);
if ($stmt->rowCount() > 0){
throw new Exception('This email address is already registered');
}
}
function insertNewUser($dbHandler){
try{
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++){
$password = hash('sha256', $password . $salt);
}
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt
);
$dbHandler->beginTransaction();
$query = "INSERT INTO users (username, password, salt) VALUES ( :username, :password, :salt );";
$stmt = $dbHandler->prepare($query);
$result = $stmt->execute($query_params);
$newUserId = $dbHandler->lastInsertId();
$dbHandler->commit();
}catch(Exception $dbException){
$dbHandler->rollback();
$newUserId = NULL;
}
return $newUserId;
}
function insertUserPreference($dbHandler, $userId){
$query_params = array(
':user_id' => $userId
);
try{
$dbHandler->beginTransaction();
$query = "INSERT INTO user_preferences ( user_id ) VALUES ( :user_id );";
$stmt = $dbHandler->prepare($query);
$result = $stmt->execute($query_params);
$dbHandler->commit();
}catch(Exception $dbException){
$dbHandler->rollback();
}
}
require("config.php");
if(!empty($_POST))
{
try{
checkDataValidity();
doesUserExist($db);
$newUserId = insertNewUser($db);
if (!is_null($newUserId)){
insertUserPreference($db, $newUserId);
}else{
throw new Exception('Error inserting user');
}
header("Location: index.php");
die("Redirecting to index.php");
} catch (Exception $e){
echo 'The following error occured: <br/>'.$e->getMessage();
}
}
Don't let the changes baffle you - I've only rearranged your code to be more easily readable. The above solves the original problem by moving the "user insert" into one function where we return the new ID if the insert was successful, otherwise null value, and we also move the second half of the query into its own function.

PDO PHP If Username Exist, Increase Username By 1

I have this login and registration script from the net. Everything is working fine.
Objectives:
Usernames entered by the user will only be alphabets. If the username entered is not exist in the database, it will automatically add a number 1 on the username, example, user1.
Let's say the database have already had user1, user2, user3. Whenever a user entered user, it will then check what is the last incrementing number which in this case, it is 3, so it will then add into the database as user4.
Problems:
As I am trying to learn PDO as much as I could and it is still pretty difficult for me to understand. Also, I do not have any idea where should I start from.
Below are my current working code:
if (isset($_POST['submit'])) {
if(empty($_POST['username']) || empty($_POST['password'])){
$errors[] = 'All fields are required.';
}else if(!ctype_alpha($_POST['username'])){
$errors[] = 'Please enter only alphabet letters.';
}else{
if ($users->user_exists($_POST['username']) === true) {
$errors[] = 'That username already exists';
}
}
if(empty($errors) === true){
$username = htmlentities($_POST['username']);
$password = $_POST['password'];
$users->register($username, $password);
header('Location: register.php?success');
exit();
}
}
public function user_exists($username) {
$stmt = $this->db->prepare("SELECT COUNT(`id`) FROM `userinfo` WHERE `username`= ?");
$stmt->bindValue(1, $username, PDO::PARAM_STR);
try{
$stmt->execute();
$rows = $stmt->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
public function register($username, $password){
$password = sha1($password);
$stmt = $this->db->prepare("INSERT INTO `userinfo` (`username`, `password`) VALUES (?, ?) ");
$stmt->bindValue(1, $username, PDO::PARAM_STR);
$stmt->bindValue(2, $password, PDO::PARAM_STR);
try{
$stmt->execute();
// mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
Is there any kind souls out there can help me out on this? Letting me know where should I start and what should I do? Or the flow of the whole procedure in achieving my objectives.
Any help will be much appreciated! Thanks in advance.
Here is a example how to change your function to check if the user exist .. and which is the last index.
It is not pretty but will do the job and may be point you to the right ideas.
public function register($username, $password){
$password = sha1($password);
//check if the user exists and find first posible free index
$_username = $username;
if($this->db->query("SELECT * FROM `userinfo` WHERE `username` = 'user' ")){
$n = 1;
$max_index = 20;
while ($n < $max_index ) { //just to be safe
$_username = $username . $n;
if (!$this->db->query("SELECT * FROM `userinfo` WHERE `username` = '" . $_username . "' ")) {
break;
}
$n++;
}
if($n == $max_index){
die("Sorry ,there already (".$max_index.") entries of this username.");
}
}
//continue as normal just use $_username in the final query
$stmt = $this->db->prepare("INSERT INTO `userinfo` (`username`, `password`) VALUES (?, ?) ");
$stmt->bindValue(1, $_username, PDO::PARAM_STR);
$stmt->bindValue(2, $password, PDO::PARAM_STR);
try{
$stmt->execute();
// mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
First of all you have to add a Sql-Wildcard like % _ * meaning see here to find all usernames they starts with "user" and have one or more charakter behind the "user"-string. Currently you only will get the username that excatly matchs the insert username.
But you could get some trouble by using the wrong wildcard, then
SELECT COUNT(id) FROM userinfo LIKE username = user%;
will always selct usernames like user1, user2, user3 but also something like userhorst..
To the pdo, the pdo help you to protect you system from sql injections. The prepare function sends only something like a query with wildcars for your parameter, thats means they send your statement without the parameters, to the Database. After this you send with the bindValue-function the single values to the Database. And finally you will excecute the statement. During this process the datapase can check each sended value for invalid signs.
Finally you have to check your if-statement. You will only get true when one user with the same name was in the database in all other cases (0,2,3,4,5,6,7) you get false.. But you want
if countUsers equal 0 then:
return false;
else
return true;
fi
Another part is you should thinking about using the sha1-hash, there are still better hashs to protect your passwords.
You can select all usernames like user* using:
SELECT username FROM `userinfo` WHERE username LIKE 'user%'
Next you should sort your results using asort:
asort($array_of_usernames);
then use substr or preg_match to get the number at the end of the username:
$number = substr($each_username, -1, 2) //within a foreach
Increment the number gotten then insert into database.
$new_username = "user" . $number++;
Thanks for the help guys!
Below are my current working code which I manage to tweak here and there based on the help given:
public function register($username, $password){
$stmt = $this->db->prepare("SELECT username FROM `userinfo` WHERE `username` LIKE :username");
$parse_username = "%".$username."%";
$stmt->bindValue(':username', $parse_username, PDO::PARAM_STR);
$stmt ->execute();
$user = $stmt->fetch();
$n = 1;
if($user){
$db_username = $user["username"];
$username_counter = preg_match("/".$username."(\d+)/", $db_username, $matches) ? (int)$matches[1] : NULL;
while ($n < $username_counter ) { //just to be safe
$new_username = $username . $n;
if (!$user) {
break;
}
$n++;
}
if($n == $username_counter){
$n++;
$new_username = $username.$n;
}
}else if(!$user){
$new_username = $username.$n;
}
$password = sha1($password);
$query = $this->db->prepare("INSERT INTO `userinfo` (`username`, `password`) VALUES (?, ?) ");
$query->bindValue(1, $new_username);
$query->bindValue(2, $password);
try{
$query->execute();
$_SESSION['new_username'] = $new_username;
// mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
I am not sure that my way of coding is the best or professional, it is just based on my little logical knowledge of the flow. If there are any area where I can improve or rewrite, help me out if you wish to. =)

how to avoid duplicating in php

i am new in terms of php. i am now creating a simple program which is similar as a login page. may you please help me to do my coding, i have mysql table named user which has 3 column userid, email and password. my primary is userid and it is an auto increment. how can i have code which is, the column email should no duplication or no same email. i have already code for avoiding empty fields i don't know now how to do about the duplication..
here is my sample code:
<?php
if(isset($_POST['submit'])){
$dbhost = 'localhost';
$dbuser = 'root';
$conn = mysql_connect($dbhost, $dbuser);
mysql_select_db('dtr');
if(! $conn ){
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ){
$email = addslashes ($_POST['email']);
$password = addslashes ($_POST['password']);
}
else{
$email = $_POST['email'];
$password = $_POST['password'];
}
//validation
if($email == ''){
echo "empty ang email" ?></br><?php ;
return false;
}
if($password == ''){
echo "kailangan may password ka\n" ?></br><?php ;
return false;
}
---------------------->//select * table where username=user
{
$sql = "INSERT INTO user "."(email, password) "."VALUES('$email','$password')";
$retval = mysql_query( $sql, $conn );
}
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
}
?>
help me plz..
you can try:
$sql = "SELECT userid from users WHERE email = ". $_POST["email"];
if (mysql_num_rows(mysql_query($sql, $con)) >= 1)
{
echo "That email you provided seems to be already used";
return;
}
And please thing about using a different db extension since mysql is deprecated as of PHP V. 5.5. It will give you better security features with binding and prepared statements.
Simply use this, I think it should give u help:
$name = $_POST[name];
$pass = $_POST[pass];
$user = "SELECT * from users WHERE email = '".$email."'";
$result = mysql_query($user);
if(mysql_num_rows($result)>0){
return "$result";
}
else{
mysql_query("INSERT INTO users(email, pass) VALUES ('$email', '$pass')");
}

Using a variable to direct traffic

I am mostly sure that my error is with the variable not being gotten from the table. However I can not see the error I am asking for that data at the same time I am asking for the username and password. The table consists of [username],[password],[company]. The goal is to have the user get directed based on the name in company after the username and password have been verified. I keep getting the echo at the end.
Here is the code
function RegisterUser($usename, $password, $company)
{
// hash the pwd
$hpwd = hash('sha256',$password);
$q ='insert into users values(username, password, company) values(?,?,?)';
$stmt = PDO::prepare($q);
$stmt->exectue(array( $username, $hpwd, $company));
}
// validate user and return the company if successfull
function ValidateUser($username, $password, &$company)
{
$hpwd = hash('sha256',$password);
$q ='select company from users where username=? AND password=?';
$stmt = PDO::prepare($q);
$stmt->exectue(array( $username, $hpwd));
if( ($company = $stmt->fetch(PDO::FETCH_COLUMN)) === false )
{
$company = header( 'Location: login.php' );
}
elseif($company == "monkeynones"){
header( 'Location: admin1.php' );
}
Your query is wrong:
$sql = "SELECT 'password' and 'company' from users where 'username' = '$username';";
should be
$sql = "SELECT `password`, `company` from `users` where `username` = '$username'";
Use backticks, not quotes, around identifiers. and is replaced by a comma, and the trailing semicolon in the query isn't required.
It is so important that new programmers learn to do username/password authentication properly I felt it necessary to write this longer post.
Firstly, as eicto pointed out, the mysql extension is both deprecated and should really not even be used ever.
So to the metal.
visit php.net and learn about PDO
Never store unencoded passwords.
here is what you should do:
set up PDO:
// you need to store $link somewhere. in a class preferrably
function InitPDO(&$link)
{
// havet the database handle all strings as UTF-8.
$options = array('PDO::MYSQL_ATTR_INIT_COMMAND' => 'set names utf8');
$link = new PDO ( 'mysql:host='.$config['dsn_host'].';dbname='.$config['dsn_db'], $config['username'], $config['password'], $options ) ;
// If there is an error executing database queries, have PDO to throw an exception.
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
upon registration of user.
function RegisterUser($username, $password, $company)
{
// hash the pwd
$hpwd = hash('sha256',$password);
$q ='insert into users values(username, password, company) values(?,?,?)';
$stmt = $link->prepare($q);
$stmt->execute(array( $username, $hpwd, $company));
}
// validate user and return the company if successfull
function ValidateUser($username, $password, &$company)
{
$hpwd = hash('sha256',$password);
$q ='select company from users where username=? AND password=?';
$stmt = $link->prepare($q);
$stmt->execute(array( $username, $hpwd));
if( ($company = $stmt->fetch(PDO::FETCH_COLUMN)) === false )
{
$company = 'invalid'; // because user auth failed';
}
//else all is good
}
example test usage.
// assumes there is a 'login.php' and a 'invalid.php' file
$link = null;
InitPDO( $link );
RegisterUser('tester','password','login');
VerifyUser('tester','password', $redir );
if( file_exists( $redir . '.php' ) )
{
header( 'Location: '. $redir . '.php' );
exit;
}
echo 'error. no valid page found to fullfill query';

Categories