Getting PostgreSQL Query Error with PHP and Sessions - php

The problem I encountered has to do with the query using session variables.
during the user login i assigned a session variable as such
$myemail = $_POST['email'];
$mypassword = $_POST['password'];
$sql = "SELECT * FROM users WHERE email = '$myemail'";
$result = pg_query($db,$sql);
$row = pg_fetch_assoc($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if(count($result) == 1) {
$_SESSION['user_id'] = $row['id'];
}
The highlight is $_SESSION['user_id'] = $row['id']
Next once the user logs in i want to find the info of the user in my database, so I searched for the user as such
$userid = $_SESSION['user_id'];
$result = pg_query($db, "SELECT * FROM users WHERE id = '$userid'") or die("error on query");
$user_info = pg_fetch_assoc($result);
But I keep on getting error on query showing that the query is failing. I have no idea why this is happening.

if user id is int in your db you don't need the single ticks(''). This will cause query failure as well. You could try something like this ".$userid."
$result = pg_query($db, "SELECT * FROM users WHERE id = ".$userid."") or die("error on query");

but count($result) won't give you row count. Try using
if(pg_num_rows($result) == 1){
$session['user_id']= $row['id'];
}else{
echo pg_num_rows($result);
}

Underneath $_SESSION['user_id'] = $row['id']; in the same if statement, echo the id to see what response you get
echo $_SESSION['user_id'];

Related

Loop through every row in a database table in php

I am new to php.
I am doing login for user, then I would like to compare the username and password of the person when he/she login to every rows in my database table.
For this case, assume user= michael, pssword =1234
I got this:
$username= "michael";
$password= "1234";
include("includes/connect.php");
$mobile_user = "select * from mobileuser" ;
$query = mysqli_query ($conn, $mobile_user);
while($results = mysqli_fetch_array ($query)){
$user_name = $results['mobile_user_name'];
$pass = $results['mobile_user_pass'];
}
However, this only compare to the last row of data in my database table.
For example, if username=michael n password=1234 is located in the last row of my database table, then login success, if it does not located at the last row, login failed.
Anyone can help?
You should modify your code as:
$username= "michael";
$password= "1234";
include("includes/connect.php");
$mobile_user = "SELECT * FROM mobileuser WHERE mobile_user_name='$username' AND mobile_user_pass='$password' LIMIT 0,1";
$query = mysqli_query ($conn, $mobile_user);
$result = mysqli_fetch_array ($query);
$user_name = $result['mobile_user_name'];
$pass = $result['mobile_user_pass'];
This should work like a charm. However a better version of this would be:
$username= "michael";
$password= "1234";
include("includes/connect.php");
$mobile_user = "SELECT count(*) as count FROM mobileuser WHERE mobile_user_name='$username' AND mobile_user_pass='$password'";
$query = mysqli_query ($conn, $mobile_user);
$result = mysqli_fetch_array ($query);
if($result['count'] > 0){
echo "Match Found.";
}
If you want to check if a user's credential are valid, you should count the number of rows where they match ; if this is less than one, the credentials provided are invalid. SQL query :
SELECT COUNT(*) AS number, mobile_user_name, mobile_user_pass FROM mobileuser WHERE mobile_user_name = 'someusername' AND mobile_user_pass = 'somepass'
Note that you should prevent your code from SQL injections, and you may want to store hashed passwords in your database to avoid stocking them in cleartext.
give this a go:
require_once ('con.php');
$q = "SELECT `password` FROM `tbl_where_user_is` WHERE `tbl_row_username` = '$username'";
$r = mysqli_query($db_connnect, $q);
$row = mysqli_fetch_array($r);
$r = mysqli_query ($db_connnect, $q);
if(mysqli_num_rows($r)==1)
{
echo $username;
}else{
echo "user not found";
}

How to get a selected database value as a session variable in php?

I want to get the id in users table as a PHP session variable called $_SESSION['id']. But when I am printing the session variable, I have got Undefined index as the output.
Here is my PHP code.
$jsqla = mysql_query("select id, user_name, user_type from users where pw='$pass' and email='$email'") or die("Website under maintenance.");
$jfeta = mysql_fetch_assoc($jsqla);
$id = $jfeta['id'];
$_SESSION['id'] = $id;
mysql is deprecated. Use mysqli or PDO instead.
nevertheless... update your query.
For better overview and debugging store your sql query first in a variable:
$sql = "select id, user_name, user_type from users where pw='".$pass."' and email='".$email."'";
Now use this code:
(http://php.net/manual/en/function.mysql-fetch-assoc.php)
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$row = mysql_fetch_assoc($result);
$id = $row["id"];
$_SESSION['id'] = $id;
But again ... use mysqli or PDO - mysql is deprecated!
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future.
First check whether the session variable is set or not using the below code.
if(isset($_SESSION['id'])) {
echo $_SESSION['id'];
} else {
echo "error.";
}
Did you used session_start to start a session?
<?php
session_start();
?>
After this
$id = $jfeta['id'];
should work:
<?php
$jsqla = mysql_query("select id, user_name, user_type from users where pw='".$pass."' and email='".$email."'") or die("Website under maintenance.");
$jfeta = mysql_fetch_assoc($jsqla);
session_start();
$id = $jfeta['id'];
$_SESSION['id'] = $id;
?>
your Selection could be the Problem too:
$jsqla = mysql_query("select id, user_name, user_type from users where pw='$pass' and email='$email'") or die("Website under maintenance.");
could work better with this:
$jsqla = mysql_query("select id, user_name, user_type from users where pw='".$pass."' and email='".$email."'") or die("Website under maintenance.");
The message "Undefined index" means that the one value you use isn't set.
you can prevent this by example:
if(isset($jfeta['id']))
{
//do thing
}

INNER JOIN for login form doesn't seem to work in PHP?

Let me first explain what i'm trying to do...
I have two Tables in mysql database. 1st is members and the other one is storename.
I save a random unique Key in both of these tables in the column randKey.
This all works fine.
Now, I have a login form which I am trying to use which has INNER JOIN in the SELECT.
the purpose of using INNER JOIN is to be able to use the randKey in both Tables mentioned above so the users cannot login to someone else's account if you know what I mean.
only if the email, password and randKey is matched then they can login?
However, when I run the PHP/login page and try to login, I get That information is incorrect, try again echoed out to me...
Here is my code:
<?php
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["email"]); // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
// Connect to the MySQL database
include "config/connect.php";
$sql = "SELECT members.email, members.password, storename.email, storename.password
FROM `members`
INNER JOIN `storename`
ON (members.randKey = storename.randKey)";
// query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: dashboard");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
could someone help me out with this?
There are no filters in your query, so it's returning every row of your database. You probably have more than one member, so the number of rows can't be equal to 1.
The second problem is that you're not selecting any id in your query, but you're trying to get if after.
Try this :
<?php
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["email"]); // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
// Connect to the MySQL database
include "config/connect.php";
$sql = "
SELECT members.id
FROM `members`
INNER JOIN `storename` ON (members.randKey = storename.randKey)
WHERE members.email = '$manager'
AND members.password = '$password'
";
// query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: dashboard");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
In your SQL you don't have a where clause so your query fetches all of the rows which is probably bigger than 1.

Checking if username already exists will not show the correct answer

I'm trying to create a duplicate check with PHP and MySQL and have now tried many different varieties. Nevertheless, my code does not show if the user name already exist. As far as I know this should be the right (of many) formula for a functional duplicate check?
$username = "heihei";
$checkquery = mysqli_query($con,"SELECT * FROM users
WHERE username='$username'") or die(mysqli_error());
if (mysqli_num_rows($checkquery)) {
echo ">0" ;
}else {
echo "0" ;
}
User table looks like this:
ID USERNAME
1 heihei
2 neinei
When defining $username as heihei, result is 0.
Result is the same if I define $username as something.
It will show that the user don't exists already.
What is the problem here?
Do this:
Replace
if (mysqli_num_rows($checkquery)) {
with:
if (mysqli_num_rows($checkquery) > 0) {
and replace echo ">0" ; with echo "Exists"; - that's what I use with success.
Try this also:
$results = "SELECT username FROM users WHERE username = '$username'";
$checkquery = mysqli_query($con,$results) or die(mysqli_error());
if (mysqli_num_rows($checkquery) > 0) {
The way I do it in my script, is this:
$mysqli = new mysqli("xxx","xxx", "xxx", "xxx");
$username = mysqli_real_escape_string($mysqli,$_POST['username']);
$username = $_POST['username'];
$sql = "SELECT username FROM users WHERE username = '$username'";
$results = mysqli_query($mysqli,$sql) or die(mysqli_error());
if (mysqli_num_rows($results) > 0)
{
die("Sorry, that username is already taken.");
}
Also you can use another query:
SELECT COUNT(*) FROM users WHERE `username` = '$username'
And see the results
if(mysqli_num_rows(mysqli_query($checkquery))== 0){
echo "no duplicates";
}

Write an ID into session as a variable

I need to insert an ID into session for later use. Table contains ID, username and password.
To get the ID im using:
$sql = "SELECT id FROM members WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
And trying to store it into session:
$_SESSION["id"] = $result;
When im trying to insert $_SESSION[id] into a table I get the value of 0 (which is the default value I made).
Kinda new on PHP, any help would be appriciated :)
you need fetch the value aswell:
$result=mysql_query($sql);
$fetch =mysql_fetch_array($result);
$_SESSION["id"] = $fetch["ID"];
Attempting to print $result won't allow access to information in the resource.
You need to use a function to access the resource returned:
$row = mysql_fetch_assoc($result)
$id = $row['id'];
The proper way to handle result would be to first check it has any value at all, i.e.:
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_query() returns a resource on success, or FALSE on error. You need to fetch the rows from that result:
$result = mysql_query("SELECT id, name FROM mytable") or die(mysql_error());
$row = mysql_fetch_array($result);
if($row){ // check that there was really selected at least one row
$_SESSION['id'] = $row['id'];
}

Categories