Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
i have this information on my database...
Username - kam, mav, shin
Password - kam, mav, shin
this is my code...
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl2=mysql_query("SELECT * FROM tablename WHERE `username` =
'".mysql_real_escape_string($_POST['username'])."' and `password` =
'".mysql_real_escape_string($_POST['password'])."'");
while($row=mysql_fetch_array($tbl2))
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}
if (($row['username']!=$_POST['username'])&&($row['password']!=$_POST['password']))
{
header("location: /login.php?codeError=1");
die;
}
?>
the problem is, if i enter the username "mav" and the password is "kam", it still go through the next page. What should i do?
You should just check if the query returns any rows with mysql_num_rows():
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl2 = mysql_query("SELECT `username`, `password` FROM `tablename` WHERE
`username` = '".mysql_real_escape_string($_POST['username'])."' AND
`password` = '".mysql_real_escape_string($_POST['password'])."'
");
$rows = mysql_num_rows($tbl2);
if($rows){
// user and password exists in db
} else {
// does not exist
header("location: /login.php?codeError=1");
die;
}
Like I told you in previous question, try to move from mysql_* functions.
Just a suggestion but why not try it this way:
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}else{
header("location: /login.php?codeError=1");
die;
}
I don't understand why you need two if statements here, it's only boolean and the result will either be true or false.
Hope this helps :)!
You are checking for validation already in your query. If the user entered username and password correctly and only then, the query returns a row, containing that data.
So you only have to count the rows returned bye your Query. If it is below 1, then the user is not authenticated
Try
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}
else
{
header("location: /login.php?codeError=1");
die();
}
Anyway, a nice way to address this kind of issues is temporary printing on screen the variables (as a debug).
echo $row['username']." ".$_POST['username']." ".$row['password']." ".$_POST['password']
see if the variables are actually there of if there are issues with your DB query or with the form that posts the data.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Good day everyone,
Firstly let me explain a little bit about my page flow, btw Im using PHP:-
User will Login to the page using their ID (NRIC No) with pw
Then, In the Main page I would like to display their full name (Eg: Welcome, fullname) whereby the name will automatically fetched from the same table with the nric no in the database.
I was successfully do that when I used the same attribute (fullname) with the ID. However, my sv wants the login ID using NRIC No. SO, When I edit the code, there is nothing appear in the main page :(
Here are my codes in the main page;
<!-- logged in user information -->
<?php if (isset($_SESSION['namapengguna'])) : ?>
<p style="margin-left:360px;margin-right:60px">Welcome<strong><?php echo $_SESSION['namapengguna']; ?></strong></p>
<?php endif ?>
***The information(NRIC No, full name) in the database was successfully inserted.
Example of my Table in database:-
namapengguna | idpengguna | password |
Maisarah | 1234567891 | dfsdfdsf |
This is code for login:-
// LOGIN USER
if (isset($_POST['login_user'])) {
$idpengguna = mysqli_real_escape_string($db, $_POST['idpengguna']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($idpengguna)) {
array_push($errors, "Masukkan ID Pengguna");
}
if (empty($password)) {
array_push($errors, "Masukkan Kata Laluan");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE idpengguna='$idpengguna' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['idpengguna'] = $idpengguna;
$_SESSION['success'] = "";
header('location: lamanutama.php');
}else {
array_push($errors, "ID Pengguna/Kata Laluan salah");
}
}
}
<?php
session_start();
// to store session values
$_SESSION['namapengguna']= $idpengguna; // Initializing Session with value of PHP Variable
?>
Main page Code:
echo $_SESSION["namapengguna"];
please visit this link best example for it. here
As long as you have session you can easily write like this
first add session_start(); and change namepenguna to idpenguna because it has to be the same session you set the time you were receiving result form mysql result
echo 'welcome' .$_SESSION['idpengguna'];
I hope this will work
In your database , password column is not encode by md5(dfsdfdsf), but $password = md5($password);.You should check it
try like this, i hope it will help you:
<?php if (isset($_SESSION['namapengguna'])){
echo 'welcome' .$_SESSION['idpengguna'];
}
?>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
This is my signin.php file
and I want to make a page which only admin (mousoufi) can enter.
I made a new page where I want to post only admin things can see. Else I wanted to echo to other users that they dont have permission here.
I just make a session on top of my admin page?
Any ideas?
<?php
$user=$_POST['user'];
$pass=$_POST['pass'];
$con=new mysqli("localhost","root","","3333");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT username FROM `3333` WHERE password='$pass' AND username='$user'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// outputdata of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You are now logged in " . $row["username"]."<br>";
}
}
else {
echo "Wrong Password Try Again"; }
// Set session variables
$_SESSION["username"] = "$user";
$_SESSION["password"] = "$pass";
print_r($_SESSION);
if ("$user"=="mousoufi" AND "$pass"=="1234"){
echo "HELLO Mousoufi ";
}
$con->close();
?>
If you want to use sessions you need to start them on every single page that you need them on, and that is done with this:
session_start();
Put that at the top of your php script.
You'll need a way to distinguish admins (if you're going to have more than one?), but since your question only states one, this should work for you:
<?php
// start session
session_start();
// check if username is admin
if($_SESSION['username'] !== 'mousoufi'){
// isn't admin, redirect them to a different page
header("Location: /someotherpage.php");
}
Notes
You should have more readable table names. 3333 isn't really the best, especially when you call the table the same thing...
You should at least sanitize your user input variables - mysqli_real_escape_string() at very least. It'd be best if you go with PDO or MySQLi Prepared Statements.
Your script is wrong, badly wrong. If your user didn't log in correctly, don't set the session.
if (mysqli_num_rows($result) < 0) {
die("Wrong Password Try Again";);
} else {
// outputdata of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You are now logged in " . $row["username"]."<br>";
$_SESSION['username'] = $row["username"];
// and so on...
}
}
This is what your block should look like.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have designed a registration form where users are being registered by there name and phone no. now i want a script so that there should be a cheak before registering any user, that wheather the phone number is already been registered or not, only if the user is new he can register into and his data will be filled in the database...
I hope you could do this using this method
if(isset($_POST['signup'])){
$user_name= $_POST['name'];
$phone = $_POST['phone'];
$check = mysql_query("SELECT * FROM users WHERE name='$user_name' AND phone='$phone'");
if( mysql_num_rows($check) ==0 ){
//User is not exist run INSERT Query here
}
else
{
//User is Exist
$exist = true;
exit;
}
}
I don't want to do all of your work for you, but I'll gladly point you in the right direction.
You can do a SELECT query on your users table with the desired username in the WHERE clause and you can use the mysql_num_rows($queryCallback) function in an if statement to see if there are one or more rows returned. If there are, then the process will be terminated and you can just send the user back with an error message.
Example:
SELECT * FROM Users WHERE username = "monkeyballs";
Returns 1 Row
if (mysql_num_rows($result) >= 1) {
return false;
//terminate the registration
} else {
//INSERT query and whatnot
}
Good luck!
I recommend you research MySQL functions in PHP or pick up a framework. CakePHP makes registration / logging in a breeze. Just my two cents for you.
You will have to query the database table holding info about the already registered users and see if that is already there:
eg:
$mysqli = new mysqli("localhost", "user", "password", "dbname");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
if ($query = $mysqli->query("SELECT id FROM users WHERE phone = '123456'")) {
if($result->num_rows == 0)
//register user
else
// send error message
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I’m wondering how you write if statements using mysql/php.
I’ve got an employee table with all their details, ‘username’ and ‘password’ then a column called ‘admin’ with a 0 or 1 as well. The user can login using the "username" and "password" form boxes. How do I write it so that it checks if the username/password exists then checks if admin = 0 and directs them to header location employee.php else if admin=1 then directs them to header location admin.php?
Any help would be greatly appreciated.
edit: This is the code I've got so far...
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
setcookie('username',$myusername,time() + (86400 * 7)); // 86400 = 1 day
if ('admin' == '0'){
header("location:employee.php");
}
else {
header("location:admin.php");
else {
header("location:fail.php");
}
}
?>
try this php code
$username = mysql_real_escape_string(stripslashes($_REQUEST['username'])); // received from post/get
$password = mysql_real_escape_string(stripslashes($_REQUEST['password'])); // received from post/get
$res = mysql_query("SELECT * FROM `employee` WHERE username='$username' AND password='$password' LIMIT 1") or die(mysql_error());
if($row = mysql_fetch_assoc($res))
{
if($row['admin']==1)
{
header("location:admin.php");
exit;
}
else
{
header("location:employee.php");
exit;
}
}
else
{
// invalid username or password
// code here to handle
}
You Can try using a select box of value ADMIN and USER . You can validate the select box in the if statement
if(select=="admin")
{
verify with DB \\admin
Redirect
}
else
{
verify with DB \\ end user
redirect
}
Hope it helps !!
You posted every step. Just code it now.
Make a new mysqli connection.
$mysqli = new mysqli("host", "user", "password", "database");
Define your query:
$query = "SELECT * FROM yourtablename WHERE username=? AND password=?";
Create a prepared statement:
$stmt = mysqli->prepare($query);
Bind the values:
$stmt->bind_param('ss', $submitted_username, $submitted_password);
Execute the statement:
$stmt->execute();
Check if there is a result or not.
If there is a result, check if admin is 0 or 1 and redirect (in case of 1) to admin php with header():
header('Location: admin.php');
You can get your selected data for example with fetch().
Just study the examples from php.net for more information how to get data with mysqli.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to write a script that does the following. Takes a users email and added's it to a database however if the users email already exists it rejects.
<?
require_once('includes/db.php');
$email = mysqli_real_escape_string($link, $_POST['email']);
$dupesql = "SELECT * FROM emails where (email = '$email')";
$duperaw = mysqli_query($link, $dupesql);
if(int mysql_num_rows($duperaw) > 0){
echo 'Error already in there';
}
else {
$sql = "INSERT INTO emails(email)
VALUES('$email')";
$result = mysqli_query($link, $sql);
header('Location: poll/poll.php');
}
// close mysql
mysqli_close($link);
?>
Why not let mysql take care of it? When you already want email to be unique, then define an unique index for email :
CREATE UNIQUE INDEX email_index ON emails (email)
now you only have to check if any rows has been affected after insert :
if (mysqli_affected_rows()>0) {
//success, email inserted
} else {
// rejected
}
By that you'll spare a call to the database and make the code more simplistic, imho.
try this
$mysqli->real_query('INSERT INTO '.$table.' ('.$cols.') VALUES ('.$vals.')');
Change your code as follow:
$dupesql = "SELECT * FROM emails where email = '$email'";
$duperaw = mysqli_query($link, $dupesql);
if(mysql_num_rows($duperaw)==1){
echo 'Error already in there';
}
You are mixing mysqli_ with mysql_ which is the main problem here.
Use mysqli_num_rows instead of mysql_num_rows
You should not mix mysqli() and mysql().
And remove int error casting.
//...
if(mysqli_num_rows($duperaw) > 0){
echo 'Error already in there';
}
//...