User not being deleted on link click [duplicate] - php

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have a users table and I want to be able to delete a user when a link is clicked. $user_name is set in a session. Here is the link:
<?php echo "Delete Account" ?>
Here is the code on delete_user.php:
<?php
session_start();
session_destroy();
require "connection.php";
?>
<?php
if($_GET['id'] != ""){
$user_name = $_GET['id'];
$sql = "DELETE FROM users WHERE user_name='{$user_name}'";
$result = mysqli_query($connection, $sql);
header('Location: register.php');
}
?>
<?php include "footer.php";?>
I don't understand why it's not deleting the user from the database when this code is executed?

There's no clear reason as to why your code is not working. However, you mentioned being new to PHP, so picking up good practices with your code could (1) help solve the issue at hand, (2) make your code more efficient, and easier to debug.
I recommend you use mysqli in the object-oriented manner, it requires less code, and usually easier to follow.
Making the connection is simple:
<?php
$host = 'localhost';
$user = 'USERNAME';
$pass = 'PASS';
$data = 'DATABASE';
$mysqli = new mysqli($host, $user, $pass, $data);
// catch errors for help in troubleshooting
if ($mysqli->errno)
{
echo 'Error: ' . $mysqli->connect_error;
exit;
}
?>
Creating a safe environment for your server keep in mind these things:
Do not trust user input (ever!)
Do not perform direct queries into your database.
When developing, break your code into steps so you can easily troubleshoot each part.
With those three simple things in mind, create a delete file.
<?php
if (isset($_GET['id'])
{
// never trust any user input
$id = urlencode($_GET['id']);
$table = 'users';
// set a LIMIT of 1 record for the query
$sql = "DELETE FROM " . $table . " WHERE user_name = ? LIMIT 1";
// to run your code create a prepared statement
if ($stmt = $mysqli->prepare( $sql ))
{
// create the bind param
$stmt->bind_param('s', $id);
$stmt->execute();
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' were updated.'
);
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: There was a problem with your query'
);
}
}
else
{
echo 'No user id is set...';
}
The code will help you set the query, and delete the user based on their user_name... Which I am not sure that is the best solution, unless user_name is set to be an unique field on your MySQL database.

Firstly this is a horrible way to do this, you are prone to SQL Injections and also using GET literally just tags the query to the end of the URL which is easily obtainable by a potential hacker or ANY user as a matter of fact. Use POST instead with a bit of jQuery magic, I would also recommend using Ajax so that you don't get redirected to php file and it will just run. As it is not anyone can access that URL and delete users so I recommend using PHP SESSIONS so that only people from your site can delete users. Also simply passing the id to the PHP file is very insecure as ANYONE could simply create a link to your php file on their site and delete users.
Therefore try this to fix your code (with added security):
PLEASE NOTE: I am aware that this may not be the best way nor the worst but it is a fairly secure method that works well.
Your main page, index.php:
<?php
session_start();
// Create a new random CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
...
<form id="delete_user_form" action="delete_user.php" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_name; ?>" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Delete User" />
</form>
In your .js file (make sure you have jQuery linked):
window.csrf = { csrf_token: $("input[name= csrf_token]").val() };
$.ajaxSetup({
data: window.csrf
});
$("#delete_user_form").submit(function(event) {
event.preventDefault(); //Stops the form from submitting
// CSRF token is now automatically merged in AJAX request data.
$.post('delete_user.php', { user_id: $("input[name=user_id]").val() }, function(data) {
//When it it's complete this is run
console.log(data); //With this you can create a success or error message element
});
});
Now for your delete_user.php file, this should fix the errors:
<?php
session_start();
require "connection.php";
// Checks if csrf_token is valid
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
if(isset($_POST['user_id']) && $_POST['user_id'] != ""){
$user_name = $_POST['user_id'];
$sql = "DELETE FROM users WHERE user_name = '$user_name' LIMIT 1"; //LIMIT 1 only allows 1 record to be deleted
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully"; //You get this in your javascript output data variable
} else {
echo "Error deleting record: " . $conn->error; //You get this in your javascript output data variable
}
$conn->close();
}
}
?>
I don't know what your connection.php contains so this is what I'd put in it:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

Related

php- How to record which user clicked on a link to download a file

I am trying to record which user has downloaded a file in an SQL database. Every file uploaded has its path displayed as a link on the site, allowing the user to download that file from a folder on the server. I am having trouble figuring out how to record which user has downloaded a file though. How can I query my database that a specific user has clicked a specific link? I have the user id stored as a session variable, so possessing the user id is not a problem. My code to display the downloadable files are as follows:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project_website1";
$user_id = $_SESSION[ 'user_id' ];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "<tr><td>" . $row["file"]. "</td><td>" . $row["title"]. "</td><td>" . $row["deadline_claim"]. "</td></tr>";
echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='" .$row["file"]. "'>CLAIM</td></a>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
If you want it to be purely PHP, as suggested, just use the task_id of the row in your file table. Here is a basic example, noting I have reorganized some elements to help keep your script cleaner. Ideally you will want to keep the functions on a different page and include them when you want to use them. Keeps your script cleaner and more easily readable.:
# Better to make a function/class to do your database so you can reuse it easily.
function getConnection( $servername = "localhost", $username = "root",$password = "",$dbname = "project_website1")
{
# Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
# Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
# Make a task retrieval function/class that will deal with getting the rows only
function getTasks($con,$id=false)
{
$sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
# I am assuming your task_id values are numeric, so I don't sanitize here
if ($id) {
if(is_numeric($id))
# Append sql
$sql .= " WHERE `task_id` = '{$id}'";
else
# You shouldn't get this exception unless someone is trying to
# Manually put something else here via injection attempt
throw new Exception("Id must be numeric!");
}
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$new[] = $row;
}
}
# Send back rows
return (!empty($new))? $new : array();
}
# This is more of a listener, but it will cut down on some redundant check-script
function getFileId()
{
if(!empty($_GET['file']) && is_numeric($_GET['file']))
return (!empty($_GET['action']) && $_GET['action'] == 'download')? $_GET['file'] : false;
return false;
}
# As noted, you would include the functions here...
session_start();
# Get session id
$user_id = $_SESSION[ 'user_id' ];
# Get the database connection
$conn = getConnection();
# If there is a download
if(!empty($_GET['action']) && $_GET['action'] == 'download') {
# Get the tasks, could be based on id or all
$tasks = getTasks($conn, getFileId());
# Save to the database, make sure that you either bind parameters, or
# check that the values are numeric (if they are supposed to be numeric)
# Also check the count here first for the task before inserting. Make an error if not.
# Usually means user is trying to manipulate the request
$conn->query("INSERT into downloads (`fileid`,`userid`) VALUES('".$tasks[0]['task_id']."','".$user_id."')");
# Download file. If you want to obfuscate the file, you would use
# download headers instead:
# http://php.net/manual/en/function.readfile.php
header('Location: '.$tasks[0]['file']);
# Stop execution
exit;
}
# Get all tasks
$tasks = getTasks($conn);
# If there are rows, output them
if (!empty($tasks)) {
echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
# output data of each row
foreach($tasks as $row) {
echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='?action=download&file=" .$row["task_id"]. "'>CLAIM</td></a>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Final note, I have not tested this, so be aware of that.
your header for calling script in html
<head>
<script laqnguage="javascript" src="myfunction.js" type="text/javascript"></script>
</head>
then in your while loop in php jump out of php
?>
<form name"myform" method="get" action="<? php echo $row["file"]; ?>">
<input type="button" name="name" Value"<? php echo $row["file"]; ?>" onClick="setinsertAction();" />
</form>
then jump into php again
<?php
now create a file called myfunction.js and put this inside
function setinsertAction() {
document.myform.action = "HERE PUT YOUR PHP FILE THAT WILL DO THE QUERY";
document.myform.submit()'
}
if all goes well it should the retrieve the file for download and executed your php script if the you replace your php file for the query in the .js file if it fails let me know

PHP Login code doesn't work, user stays stuck on the login page

I am new to PHP and can't find answers as to why the following code doesn't work. This should be easy, but I can't figure this out. This code produces no errors, and the SQL statement is correct in the phpAdmin SQL console. I've searched web & StackOverflow, but can't find a good answer. What's wrong?
ALL users (whether in the db or not) get ignored and stuck on login page.
<?php
session_start();
//create function to check login form for admin or other type of user.
//Redirect the admin user to the welcome page.
function login()
{
//strip login and password using in-build htmlspecialchars function
$value1 = htmlspecialchars($_POST['login']);
$value2 = htmlspecialchars($_POST['password']);
//set variables for the db connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$loggedin = '';
//Create new connection to db
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection and handle any error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header('Locatin: login.php');
}
else {
//check if super admin user exists in db
$sql = "SELECT count(*) FROM admins WHERE AdminLevel = 1";
$result = mysqli_query($conn,$sql);
//check to see if query returns any rows
if(mysql_num_rows(($result) > 0) {
include 'welcome.php';
}
//check if the password and username match
if(($username === $value1) && ($password === $value2)) {
$_SESSION['loggedin'] = TRUE;
echo "Hello ".$value1.", you are logged in!<br>";
}
//send user error message if login/username and password wrong
else {
echo "Incorrect username or password<br>";
include 'login.php';
}
//close the db connection
$conn->close();
}
?>
Login Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<script>
//function to check the form
function chkForm()
{
//determine the number of elements in the user login form
var intFormLen = document.forms[0].elements.length;
//loop through the form fields to see that a value has been input
for (var i = 0; i < intFormLen; i++) {
if (document.forms[0].elements[i].value == "") {
//send user an error message if login field empty
document.getElementById(document.forms[0].elements[i].name).innerHTML="Required Field";
document.forms[0].elements[i].focus();
return false;
}
}
//clear the form fields
function clearWarn(fieldName)
{
document.getElementById(fieldName).innerHTML = "";
return true;
}
return;
}
</script>
</head>
<body>
<h2>Admin Login</h2>
<div class="phpEcho">
<div class="formLayout">
<form action="#" method="post" onsubmit="return chkForm();">
<label for="login">Login:</label>
<input type="text"name="login" onchange="return clearWarn('fieldName')">
<div id="login" style="color:red"></div><br>
<label for="password">Password:</label>
<input type="password" name="password" onchange="return clearWarn('fieldName')">
<div id="password" style="color:red"></div><br><br>
<input type="submit" name="cmdSubmit" value="Log in">
</form>
</div>
</div>
</body>
</html>
You set your form action="#" and don't submit it in JavaScript.
As noted by Jason, chkForm() will never return true, which would also prevent the form from submitting.
This script has a lot of issues that should be addressed. I will go over a couple things that may help you:
1) I would suggest using some kind of config / bootstrap file to include in your documents that contains reusable elements and start session. Require/include only once.
/config.php
define("_DS_",DIRECTORY_SEPARATOR);
define("DBUSER",'root');
define("DBPASS",'');
define("DBHOST",'localhost');
define("DBDATABASE",'mydb');
// Start session
session_start();
2) You will want to separate out your functions, importantly your database connection, whether by class or by function. You want to keep tasks separate so it's easy to reuse.
Here is an example (I am going to use PDO because I am more familiar with it but principle is the same):
/functions/connection.php
function connection()
{
// This is just a really basic connection, one could expand on this
return new PDO('mysql:host='.DBHOST.';dbname='.DBDATABASE, DBUSER, DBPASS);
}
/functions/login.php
/*
** #param $username [string] by making this a param, you can manually log in users outside of POST
** #param $password [string] same as username
** #param $conn [resource] You will want to inject your connection into this
** in order to use it. Don't make the connection
** inside. May as well reuse resources already active
** #return [bool] If you return TRUE or FALSE, that will tell your script
** whether the login succeeded or failed for notification
*/
function login($username,$password,$conn)
{
// Don't worry about stripping down the username/pass, just bind
// the username and match the password
// You need to select from your user table (or whatever table
// you are storing your usernames for your site)
$query = $conn->prepare("select * from `users` where `username` = :0");
$query->execute(array(':0'=>$username));
$result = $query->fetch(PDO::FETCH_ASSOC);
if(empty($result))
return false;
// You will want to use password_hash to save passwords
if(!password_verify($password,$result['password']))
return false;
// I use htmlspecialchars here so I don't forget when echoing to page
// but you can do it at the time you echo to browser
$_SESSION['first_name'] = htmlspecialchars($result['first_name']);
//etc....
return true;
}
To use:
/index.php
// Include our soon-to-be-used files
require_once(__DIR__._DS_.'config.php');
require_once(__DIR__._DS_.'functions'. _DS_.'connection.php');
require_once(__DIR__._DS_.'functions'. _DS_.'login.php');
// Set connection
$con = connection();
// See if a post has been made
if(isset($_POST['login'])) {
$loggedin = login($_POST['login'],$_POST['password'],$con);
}
// If the login attempt made
if(isset($loggedin)) {
// If successful
if($loggedin) {
header('Location: welcome.php');
exit;
}
else
// If failed, you can note in a variable an echo in the html section
$error = 'Login failed';
}
For the client-side validation, I would suggest jQuery Validate, it's easy and works very well.

Login issue with mySQL no database selected

I'm a beginner of PHP coding which I face this problem and I tried to fix it.
I have search through stackoverflow for answers but it stills no good.
This is my Login form.php file
<form name = 'LoginForm' method = 'POST' action = 'verifyUser.php'>
<br />
E-MAIL: <input type = "Textbox" Name = "App_Email"><br><br>
PASSWORD: <input type = "password" Name = "App_Password"><br><br>
<input type = 'Submit' name = 'Login' value = 'Log in'><br><br>
</form>
This form will goes to verifyUser.php and these are codes
include ('DBconnect.php');
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if($username=='' || $pass=='') {
header("Location:login.php?id=Some fields are empty");
}
$result = mysql_query("SELECT * FROM applicant_acct ");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if ($username==$row['App_Email']) {
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.html?id=$username");
} else {
header("Location:login.php?id=username or your password is incorrect. Please try again");
}
}
}
And final DBconnect.php
<?
$dbc = mysql_connect('localhost','root','root') OR die('Wrong Connection!!!!!!!');
mysql_select_db('onlinerecruitment') OR die ('Cannot connect to DB.');
?>
I really have no idea why it shows "Query Failed: No database selected"
I think the problem is in verifyUser.php but have no idea where.
And another thing, after I logged in how can I generate the text "Welcome - "Username"" and provide them the logout button?
Please help.
Thank you.
Generally you may want to research a graphical user interface such as XAMPP or MySQL workbench until you are more comfortable with Database systems.
Here it seems like most of the improvements can be made in you DBConnect.php file. You are beginning and I can appreciate that. Consider something along the following lines that incorporates additional the security of PDO:: static calls.
<?php
public function _dbconnect($hostpath, $database, $username, $password){
try {
$this->conn = new PDO("mysql:host = {$hostpath};
dbname - {$database};
charset = utf8",
$username,
$password);
} else { exit(); }
?>
If this particular code block doesn't help I would highly recommend that you continue by investigating PDO:: calls.
<?php
include ('DBconnect.php');
if(isset($_POST['Login'])){
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if(empty($username) || empty($pass) || ctype_space($username) || ctype_space($pass)){
header("Location:login.php?error=1");
} else {
$result = mysql_query("SELECT * FROM applicant_acct");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.php?id=$username");
} else {
header("Location:login.php?error=0");
}
}
?>
I have a lot to say about your code.
Use isset function . This function check if something was done.
Check your database details again. Maybe you wrote something
wrong (misclick or something)
Use $_GET['error'] to get errors. I set 1 = for empty characters and 0 for 0 match between database and inputs.
Use sessions for after login message. You can also use Session to handle your errors.
EDIT: I recommend you to start to learn MySQLi or PDO.

php + sql server login & sessions

Hello i am trying to create a login and session script with php to use for sql server and i cannot get it to work, it seams like no mater what i put into the login form aslong as it validates it will work, i cannot figure out what is wrong with the code however, i've just resently started using php and sql server and have not gotten the knowlage to figure out the problem for my self if soeone could help that would be great, also if you knwo any good tutorial sites that use sql server and php could you please share as there doesnt seam to be that many good tutorial sites for them sadly. any help is much welcomed at this stage. my main problem is, is that it isnt checking if the information posted in the html form exists in the database. (i have taken out the js validation as it doesnt seam nessessary however that works)
Login.html
<form name="log" action="log_action.php" method="post">
Username: <input class="form" type="text" name="uNm"><br />
Password: <input class="form" type="password" name="uPw"><br />
<input name="submit" type="submit" value="Submit">
</form>
log_action.php
session_start();
$serverName = "(local)";
$connectionInfo = array("Database"=>"mydatabase","UID"=>"myusername", "PWD"=>"mypassword");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false){
echo "Error in connection.\n";
die( print_r( sqlsrv_errors(), true));
}
$username = $_REQUEST['uNm'];
$password = $_REQUEST['uPw'];
$tsql = "SELECT * FROM li WHERE uNm='$username' AND uPw='$password'";
$stmt = sqlsrv_query( $conn, $tsql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if($stmt == true){
$_SESSION['valid_user'] = true;
$_SESSION['uNm'] = $username;
header('Location: index.php');
die();
}else{
header('Location: error.html');
die();
}
index.php
<?php
session_start();
if($_SESSION['valid_user']!=true){
header('Location: error.html');
die();
}
?>
Thank you for any help you guys might be able to bring
The problem is that you never actually check the results of the query.
if($stmt == true){
only checks that the query executed without errors - it says nothing about the results returned by the query.
Therefore, you need to use the sqlsrv_fetch function (or one of the related functions) to actually examine the result of the query.
In your particular case, simply checking if the result set has rows with sqlsrv_has_rows should be sufficient.
Sorry if it ins't how you'd answer, I am just a newbie here, but I think I have something to contribute. See if this code works for you:
<?php
#starts a new session
session_start();
#includes a database connection
include 'connection.php';
#catches user/password submitted by html form
$user = $_POST['user'];
$password = $_POST['password'];
#checks if the html form is filled
if(empty($_POST['user']) || empty($_POST['password'])){
echo "Fill all the fields!";
}else{
#searches for user and password in the database
$query = "SELECT * FROM [DATABASE_NAME].[dbo].[users] WHERE user='{$user}' AND"
."password='{$password}' AND active='1'";
$result = sqlsrv_query($conn, $query); //$conn is your connection in 'connection.php'
#checks if the search was made
if($result === false){
die( print_r( sqlsrv_errors(), true));
}
#checks if the search brought some row and if it is one only row
if(sqlsrv_has_rows($result) != 1){
echo "User/password not found";
}else{
#creates sessions
while($row = sqlsrv_fetch_array($result)){
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['name'];
$_SESSION['user'] = $row['user'];
$_SESSION['level'] = $row['level'];
}
#redirects user
header("Location: restrict.php");
}
}
?>
If you want, you can do the same with sqlsrv_fetch combined with sqlsrv_get_field().
Sth like:
<?php
session_start();
[... CONNECTION ...]
[... your POST request ...]
[... check your forms ...]
Here is the past that is kinda particular
[... YOUR QUERY ...]
$result = sqlsrv_query( $conn, $query);
if(!sqlsrv_fetch($result)){
die(print_r(sqlsrv_erros()),true);
}else{
$_SESSION['id'] = sqlsrv_get_field($result, 0);
[... and so on ...]
}
?>
The sqlsrv_fetch() only holds a row and sqlsrv_get_field reads the content of that row. One grabs the other punches. Once you only is retrieving data from the database if the row that contains user AND password exists, sqlsrv_fetch() will only stay with the row that does have the parameters passed by form, if they exist in the database.
I don't recommend, but you can use sqlsrv_num_rows() to check the number of rows, but you need to set some parameters to the sqlsrv_query: $sqlsrv_query($conn, $stmt, array($params), array( "Scrollable" => SQLSRV_CURSOR_KEYSET )) or sth like that.
Thank you for the opportunity!!! :D
Good luck!

Php login error - Notice: Undefined index:

I looked at previos Undefined error questions to see if I could find help for my question, but I can't seem to fix it for my problem.
So when I try to log in a user I get an error that says Undefined index:
No sure why Im getting this message on my login.php page
I have a database and a table called users with data inserted
this is what I use to connect to the database
conn.php
<?php
session_start();
$dbhost = "127.0.0.1"; // my database
$dbname = "fxdme";
$dbuser = "root";
$dbpass = "";
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname) or die("MySQL Error: " . mysqli_error("Cant Connect"));
?>
the login script
login.php
<?php include 'template/header.php';?>
<form action="login.php" method="POST">
User Name: <input type="text" name="username" />
Password: <input type="password" name="password"/>
<input class="submit" name="submit" type="submit" value="Log In"/>
</form>
<?php
$result=$mysqli->query('SELECT * FROM users WHERE username = "' .
$_POST['username'] . '" AND password = "' . $_POST['password'] . '"');
//set session user
$row = $result->fetch_assoc();
$_SESSION['user_id'] = $row['id'];
if ($_SESSION['user_id']) {
echo "You are logged in, $session_username. <a href='logout.php'>Log out</a>"; }
else {
echo " cant log in";
}
?>
// Index page
My index page
index.php
//in the template header is where Im calling my conn file
<?php include 'template/header.php'; ?>
<?php
if (isset($_GET['invalid'])) {
echo "<tr><td colspan='2' align='right'>Invalid login.</td></tr>";
}
?>
Im trying to get the error fixed so I'm not worried about sql injections at the moment. I just want to be able to login and and worry about the other stuff later.
You will find that $_POST["username"] will return invalid index if username is not in the post variables.
I usually create a set of variables to hold the my post variables so I can do validation and normalisation of the data first
So before your query statement
$username=(isset($_POST) && isset($_POST["username"]) ? $_POST["username"] : "";
$password=(isset($_POST) && isset($_POST["password"]) ? $_POST["password"] : "";
then use $username and $password in your query. You could event turn the previous statements into a function call passing in the variable name to check.
function getPostVar($name) {
return (isset($_POST) && isset($_POST[$name]) ? $_POST[$name] : "";
}
$username=getPostVar("username");
$password=getPostVar("password");
Obviously your code is ripe for sql injection with at username of ' union select * from users --
There is not anything in your code to make a query string in URL to fetch by $_GET. How can you have an index when you don't have anything ?
For what you said, you must use a header('location:index.php?invalid=1'); if the user can not log in to your system.
Might not be the same issue for you but I had this same error when converting to mysqli and my fetch statement looked the same as yours.
try changing.
$row = $result->fetch_assoc();
to
$row = $result->fetch_array(MYSQLI_ASSOC));

Categories