how to store session value in another table? - php

I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?

$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement

Related

Won't Query on the UPDATE part of the program

I'm having a hard time identifying the cause of the problem of my code, which is, it won't query on the "UPDATE" part but the "SELECT" part does work. when i tried using the print_r function, it gives an errors/warnings namely:
"Warning: mysqli_query(): Couldn't fetch mysqli"** and **"Warning:
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null
given"
if(!isset($_POST['n_pass'])&&!isset($_POST['n_pass'])){
if(!isset($_POST['password'])||$_POST['password']==""){
echo 'enter current password';
die;
} else {
include 'include/database.php';
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn,$_POST['lname']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$username = mysqli_real_escape_string($conn,$_POST['uname']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
//Check if the password is equal to the password inside database
$sql = "SELECT password FROM users where id = $id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$cpass = $row['password'];
$verify_pass = password_verify($password,$cpass); //check if current password is equal to the existing password
if($verify_pass != 1){
echo 'incorrect password';
die;
} else {
**//Update Data
$sql="UPDATE users SET firstname=$fname, lastname=$lname, email=$email, username=$username where id=$id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
print_r($row['firstname']);
die;
header("Location: profile.php?successfullyupdated");
}
}
}
Your query is missing the quotes around the strings:
$sql="UPDATE users SET firstname='$fname', lastname='$lname', email='$email', username='$username' where id=$id";
You can skip only the id field since it is an Integer.
Sidenote: you are wide open to SQL Injections. You should use prepared statements.
There are plenty of resources on google to start with this topic
Finally, note that
$row = mysqli_fetch_assoc($result);
print_r($row['firstname']);
is completely useless since you are not returning anything from the UPDATE query.
You can do:
if(mysqli_query($conn, $sql)){
//query was successful - run your code here for success
}else{
//query failed - run your code here for fail
}

Check and Return Value in Mysqli_query

I am Android developer and trying to make one API for register user using PHP and Mysqli. I have made API like below
<?php
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
$response='success';
}else{
$sql = "INSERT INTO tbl_user(email)VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response='success';
}else {
$response='error';
}
}
echo json_encode($response);
?>
basically I am passing email as parameter like example.com/login?=abc#gmail.com
and I want check that email is already in database table or not. if email exist in database I want return user_id in response and if email is not in database than I want add that email in database and want return user_id. I have made API is working fine as I require but I do not know how to return user_id located with that email. Let me know if someone can give me idea to solve my puzzle. Thanks
The below code will create an array with message and user_id.
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
// assign message to response array
$response['message']='success';
// Get the results data
while($row = mysqli_fetch_assoc($query)) {
// assign user_id to response array
$response['user_id'] = $row['user_id'];
}
}else{
$sql = "INSERT INTO tbl_user(email) VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response['message']='success';
// assign last inserted id to response array
$response['user_id'] = mysqli_insert_id($conn);
}else {
$response['message']='error';
}
}
echo json_encode($response);
Prepared statements help you secure your SQL statements from SQL Injection attacks.
First of all, you should use PreparedStatement to avoid sql injection.
Then, second you can use PDO::lastInsertId()

Fetching data from mySql database for php user session

I'm relatively new to PHP and mySQL, and I'm trying to create user sessions with fields from a mySQL database.
The way I've set it up means that I am getting a session with the two fields entered into the login form (username and password) by checking these against the database, but I cannot retrieve any other data from the database and add it to the session.
How can I retrieve other data from the database and add this to the new session?
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
//This one works
$_SESSION['username'] = $username;
//This one doesn't
$_SESSION['email'] = $rows ['email'];
// Redirect user to index.php
header("Location: index.php");
}else{
echo "<div class='form'>
<p>Username/password is incorrect.</p>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
}
?>
$rows is counter variable (having count of number of records) there that's why not working.
Do like below:-
....previous code as it is
$result = mysqli_query($con,$query) or die(mysql_error());
$row = mysqli_fetch_assoc($result); //fetch record
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $row['email'];
header("Location: index.php");
}...rest code as it is
Note:-
1.Don't use md5 password encryption, use password hashing technique.
2.Use prepared statements of mysqli_* to prevent your code from SQL Injection

Need to add count(*) to this file and an if statement

When I change SELECT * to SELECT count(*) the script stops working altogether. How to I add a count(*) to this file and a statement if row count for $user >= 20 allow to INSERT else do nothing.
// Include needed files
include 'mysql.php';
// Connect to MySQL
connectMySQL();
//****** SECURITY CHECK *********
session_start();
if(isset($_SESSION['userid'])){
$user = mysql_real_escape_string($_SESSION['userid']);
//*******************************
// Retrieves variables through AJAX
$favid = mysql_real_escape_string($_GET['favid']);
// $favid = mysql_real_escape_string($_GET['favid']);
// Firstly, check if article is favourite or not
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$matches = mysql_num_rows($query);
// If it is not favourited, add as favourite
if($matches == '0'){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($matches != '0'){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
} else {
// Someone tries to directly access the file!
echo "Invalid session!";
}
Thanks!
Please do necessary steps to avoid SQL injection, also try using mysqli_* functions instead of mysql_* functions
$query = mysql_query("SELECT COUNT(*) as cnt FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$res = mysql_fetch_array($query);
// If it is not favourited, add as favourite
if($res[cnt] == 0){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($res[cnt] > 0){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
I got it resolved. The reason it wasn't working was it took both values into consideration ($user and $favid). As a result it was always either 0 or 1.
I had to create another mysql query with just one value in it ($user) and then I was able to get the row count. Thanks everyone!
try to use below query, using below query if requested user's session will be 20+ then only insert statement will execute else insert statement will be ignore.
INSERT INTO ajaxfavourites(USER,favid ,exptime)
SELECT 1 AS USER, 1 AS favid, NOW() AS exptime
FROM ajaxfavourites WHERE USER=1 HAVING COUNT(*) >=20;

sql only inserts some data in php

Using data from an activation email. $email & $key.
$result1 mysql_query -
The result is that only the email, role, credits are inserted into table users. Data items username, password are not inserted.
$result2 mysql_query -
The data is not deleted from table tempusers
If I echo the data from the while loop the correct data is returned.
Got to be something simple but I just cannot see it. Thanks.
CODE:
include 'core/init.php'; /* database connection*/
if (isset($_GET['email']) && preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_GET['email'])){
$email = mysql_real_escape_string($_GET['email']);
}
if(isset($_GET['key']) && (strlen($_GET['key']) == 32)) {
$key = mysql_real_escape_string($_get['key']);
}
if(isset($email) && isset($key)) {
$result = mysql_query("SELECT * FROM `tempusers` WHERE `email` = '$email' AND `activation` = '$key' ") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user_id = mysql_real_escape_string($row['user_id']);
$username = mysql_real_escape_string($row['username']);
$email = mysql_real_escape_string($row['email']);
$password = mysql_real_escape_string($row['password']);
}
$result1 = mysql_query("INSERT INTO `users` (`username`, `email`, `password`, `role`, `credits`) VALUES ('$username', '$email', '$password', 'user', 0)") or die(mysql_error());
$result2 = mysql_query("DELETE FROM `tempusers` WHERE `user_id` = '$user_id'") or die(mysql_error());
if(!$result1) {
echo "Oops your account could not be activated. Please contact the system administrator!";
} else {
header('Location: prompt.php?x=0');
}
} else {
echo "Error. Please contact the system administrator!";
}
?>
Are you sure the query goes execute? And are you also sure the query have at least 1 result? The $email is already set but to set the username and passwors your query needs to have at least 1 result.
I also noticed $_get['key'] but i am not sure if its neccecary to change it to $_GET['key'].
This $_get in => mysql_real_escape_string($_get['key']) is in lowercase letters.
$_GET is a superglobal and it must be set in uppercase letters like this => $_GET
Sidenote: I noticed that you are using the word key in $_GET['key'] etc.
If your other script happens to be using this word as a column reference, you will need to set it inside backticks, since key is a MySQL reserved word. I'm just thinking outloud here.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Plus, I recommend you use mysqli_ functions with prepared statements, or PDO with prepared statements.

Categories