I am very new to PHP and I'm trying to make a Log-In system with MySQL. I have a form where the user registers and it saves in a database table called registers. I already have the Log-In verify and all those things. When only one user is registered, it works perfectly. But when another user registers, the SELECT thing only selects the first ro (first user's pw), so the second user can't log-in because the SELECT doesn't include all the table's rows. Here is my code:
include 'cn.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = htmlspecialchars($_REQUEST["user"]);
$u_password = htmlspecialchars($_REQUEST["password"]);
$qry = "SELECT user, password FROM registers";
$result = mysqli_query($conexion, $qry);
$row = mysqli_fetch_array($result);
$db_user = $row["user"];
$db_password = password_verify($u_password, $row["password"]);
if($u_password == $db_password) {
echo "<script>alert('You are in')</script>";
} else {
echo "<script>alert('Error')</script>";
}
}
My question is: How can I select ALL the rows inside registers, since select only detects the first row, that in this case is the first user registered?
In your MYSQL query, you need to specify which username's row you want to extract from MySQL. As you are not specifying a username, it just extracts the first row as you suspect.
Instead of:
$qry = "SELECT user, password FROM registers";
Use this:
$username_requested = mysqli_real_escape_string($conexion, $_REQUEST["user"]);
$qry = "SELECT user, password FROM registers where `user`='username_requested'";
Related
I am working on a small community page where users will be able to post news, pictures, and comment on them. The problem where I am stuck is, whenever a user posts an entry, I want of course the username to be displayed next to the entry.
I am working with multiple tables here, one that stores the user info, and some that store the entry info (news, comments, pictures).
Now whenever a user posts something, I want to get his user ID out of the table USER, so that I can INSERT a new line INTO my table (in this case) NEWS, which wants the values Text, Title and U_ID as foreign key.
I am working with sessions, and since I had no problem simply displaying the name of the login user, I tried to use that user to select "his" row from the table and put the result into a variable ($uid) which I was hoping to use in another query for the INSERT INTO. However, according to the error message I get, something is wrong with my first query. Can anyone help?
<?php
include("dbconnect.php");
session_start();
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
$sqluser = "SELECT FROM USER USER_ID
WHERE Name = '$user'";
$userresult = $conn->query($sqluser) or die($conn->error);
while($row = $userresult->fetch_assoc()){
$uid = $row["USER_ID"];
}
} else {
header('Location: login.php');
}
if (isset($_POST["title"], $_POST["text"])) {
$title = mysqli_real_escape_string($conn, $_POST["title"]);
$text = mysqli_real_escape_string($conn, $_POST["text"]);
$sql = "INSERT INTO NEWS (Titel, Text, U_ID)
VALUES ('$title', '$text', '$uid')";
}
$conn->close();
?>
I think there is mistake in your query
$sqluser = "SELECT FROM USER USER_ID WHERE Name = '$user'";
It should be like this
$sqluser = "SELECT USER_ID FROM USER WHERE Name = '$user'";
So I have an SQL database that has a table for accounts and info, and another one for storing comments on articles. I Have a form for submitting comments and it works just fine, but I wanted to implement a feature to prevent spam and non registered accounts. I was trying to find a way to make the following code work so that it would call upon my account table and check to see if the username section matches what was entered in the form.
I want it to check through my username column on the table to see if what was entered in the box is actually in the database as well, that way if it hasn't been registered it won't submit.
My problem I keep running into is that I try this
<?
if ($_POST['Uname']==`username`){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
But when I do this it thinks that "username" is what the username needs to be in order to submit properly.
I do not want every username to need to be "username" in order for them to submit, I just want it to check through my username column to see if what was entered is one of the registered usernames in the SQL column.
Im not sure if this is possible, or if I am making any sense, but this is my first post on this site and I would appreciate any help I could get.
Full code is below
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("sql***.*******.com","*****","*******");
$db_selected = mysql_select_db("*********",$con); //My login
$test2=$_GET['ID']; //Ignore
$_POST['#']=$test2; //Ignore
$sql="Select * from `Articles` and `Accounts`"; //For pulling data
mysql_query($strSQL,$con);
if ( ? == ? ){ //What should go here?
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Edit
So after making the changes needed, should my previous code end up like this?
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("*******","********","*****");
$db_selected = mysql_select_db("*****",$con);
$test2=$_GET['ID'];
$_POST['#']=$test2;
$username = $_POST['Uname'];
$sql = "Select `id` from `Accounts` where `username` = $username";
mysqli_num_rows($sql,$result);
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
echo $result;
if ($row_cnt!=''){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES ('".$_POST['Uname']."',
'".$_POST['Comment']."',
'".$_POST['Date']."',
'".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Obviously what you doing is not correct, as of now you are putting condition as :
if ($_POST['Uname']==`username`)
which means you saying any user who's name is 'username' should be able to comment, but what you want to achieve is, any user who is valid user and is exist in db should be able to comment. So for that you should write a select sql to check the user, :
$username = $_POST['Uname'];
$sql = "select id from yourusertable where username = $username";
then,
perform
mysqli_num_rows
to check if you get anything greater than zero. If yes, then allow to submit comments.
Simply apply the check that only loggedIn user can comment. So if the user will not exist in users table it will not be loggedIn nor can comment.
Alright, so I have setup a very simple login in and sign up database, it is working perfectly.
However, one of the page I have created where users can check their acccount information (Username and Email) is not working fully.
I have a database that has four columns ID, username, email and password.
All I am doing is taking the user information from the database (Who is logged in) and displaying their username and email on the page.
The problem is that the code is logging every user within the database, I only want it to select one user (The user that is logged in.)
Code:
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['email'] . "<br />";
echo $_SESSION['username'];
}
// Close the database connection
mysql_close();
?>
I'm thankful for the help !
You probably need to store the username value in a $_SESSION in your login session.
if (!isset($_SESSION)) {
session_start();
$_SESSION['id'] = the_id_of_your_logged_username;
}
Then using the value that is stored in the $_SESSION to retrieve the logged user.
session_start();
$id = $_SESSION['id'];
$query = "SELECT * FROM users WHERE id='$id'";
In these way, you can retrieve the logged user, just commonly on how users login and gets their profile directly.
Your SQL query should look something like this...
"SELECT * FROM users WHERE ID = '$user_id'"
Remember to fix any SQL vulnerabilities
$user_id = mysql_real_escape_string($user_id);
I'm using this code to login user and I want to update the value in column loggedin to yes in mysql database. I tried to update it before sending header but it doesn't get updated. Where should I put the code to update the column?
if (isset($_POST['login']))
{
$username = trim(mysqli_real_escape_string($con, $_POST['username']));
$password = trim(mysqli_real_escape_string($con, $_POST['password']));
$md5password = md5($password);
// check user and password match to the database
$query = mysqli_query($con, "SELECT * FROM `user` WHERE username='$username' AND password='$md5password'");
// check how much rows return
if (mysqli_num_rows($query) == 1)
{
// login the user
// get the id of the user
$fetch = mysqli_fetch_assoc($query);
// start the session and store user id in the session
session_start();
$_SESSION['id'] = $fetch['id'];
$_SESSION['username'] = $fetch['username'];
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE userid = 1;");
header("Location: message.php");
}
else
{
// show error message
echo "<div class='alert alert-danger'>Invalid username Or password.</div>";
}
}
You're not updating the correct userid. You're updating userid = 1 instead of the ID belonging to the user who logged in. It should be:
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE id = {$_SESSION['id']};");
You need to change this:
UPDATE user SET loggedin = 'yes' WHERE userid = 1;
To this:
mysqli_query($con, 'UPDATE user SET loggedin = 'yes' WHERE userid = 1');
Please don't use the md5() function hashing passwords, it isn't safe, use these functions instead:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
You also use this:
if (mysqli_num_rows($query) == 1)
To check if the username exists, I suggest changing it to this:
if (mysqli_num_rows($query))
It does the same but you need less code to do it.
Other than that, please also learn how to prepare your queries before inserting them, your current code is vulnerable to SQL injection, more about that can be found here:
How can I prevent SQL injection in PHP?
I want to check if the 'desig' (designation) of a user stored in user_info database, is 'gm' (G.M.) or not.
Currently, I have two users, one with 'desig' as 'gm' and the other as 'mgr', no matter who logs in, the 'gm.html' page always loads.
The correct working should be that if the desig is gm then only it should redirect to gm.html page. (members is a table in user_info db)
<?php
session_start();
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {echo "";}
else{
header("location:login.html");}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$desig = mysqli_fetch_array($result) or die("error");
if($desig!="gm")
{
$mysql_db1='customer';
$con1=mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db1) or die("Connection died for your sins.");
echo "Connected";}
else
header("location:gm.html");
?>
Your code seems to be hard-coded to only return a GM?
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
I am pretty sure that this is supposed to be picked up based on the user and not simply running a "find me a GM user" for anyone.
If I understand your question correctly, shouldn't there be somewhere in betwen the start and end of this snipped that uses the login information to verify what level a user is it?
if((isset($_SESSION['login']) && $_SESSION['login'] ==true))
{
echo "";
// Shouldn't you run a query here to see who your user is?
// For example to get their ID?
}
else
{
header("location:login.html");
}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
// Then here, instead of running this, convert it to something similar to:
$result = mysqli_query($con, "SELECT desig FROM members WHERE userid=$id");
Edit:
Storing the variable is easy - but you have to GET it from somewhere.
You can do this by popping a column in your users table - where you verify the username and password to begin with. I would suggest you look into a basic table like this to store user information. (I would also recommend you store hashes of passwords and the like, but that seems a conversation for another time).
user table:
userID username password userLevel
1 someUser somePass Grunt
2 someUser1 somePass1 MGR
3 someUser2 somePass2 MGR
4 someUser3 somePass3 GM
Armed with this, you can fire off a quick query to the database, verify the username and password, and get their userLevel quite easily.
Once you have the level, you can store it in a session variable if you like and have your code apply logic depending on what is stored in there.
I fixed the problem. There were some logical errors in my code.
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {
//Selecting the whole row to compare and display different variables
$sql = "SELECT * FROM members WHERE username = '".$_SESSION['username']."'";
if(!$sql)
echo mysql_error();
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
//Using $row variable to fetch and compare the value stored in 'desig' with 'gm'
if($row["desig"]=='gm')
header("location:gm.php"); //Opens up different page for gm aka Gen. Mgr.
}
else
header("location:login.html"); //Redirects to this page if no user is logged in.