So i have 2 functions that checks a users privilegues, and checks if the user can view the page. But it will not work as intended, and i cant figure out why. It's probably really basic, but i dont see it.
Here in use:
if(!isAdmin() || !userCanAddCourses()) {
echo 'You dont have permissions to view this page';
die;
return false;
}
Here is the functions:
function userCanAddCourses(){
$ugarr = getUserGroup($_SESSION['userid']);
$dbtype = "mysql";
$dbhost = DB_HOST;
$dbname = DB_NAME;
$dbuser = DB_USER;
$dbpass = DB_PASS;
$var = explode(',', $ugarr);
foreach ($var as $ug){
$doclibperm ='0';
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT * from roles where id=:ug";
$stm = $conn->prepare($sql);
$stm->execute(array(':ug' => $ug));
$users = $stm->fetchAll();
foreach ($users as $row) {
$addcourses = $row['addcourse'];
if($addcourses=='1'){
return true;
}
}
}
}
function isAdmin() {
$userid = $_SESSION['userid'];
$dbtype = "mysql";
$dbhost = DB_HOST;
$dbname = DB_NAME;
$dbuser = DB_USER;
$dbpass = DB_PASS;
$network = getCurrentNetwork();
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT * from users where network=:network and id=:userid";
$stm = $conn->prepare($sql);
$stm->execute(array(':network' => $network, ':userid'=>$userid));
$users = $stm->fetchAll();
foreach ($users as $row) {
$moderator = $row['role'];
}
if($moderator >= '4'){
return true;
}
}
In the scenario above, the user is an admin, but the userCanAadCourses function will not return true.
Ive tried removing die and return false, and then it will show the page along with the "You dont have permission" echo.
Its like it runs the conditional twice instead of doing the two arguments as one conditional..
Code below will work, but i think my first approach should work.
if(userCanAddCourses()){
$perm = 1;
}
if(isAdmin()){
$perm = 1;
}
if($perm != '1') {
echo 'You dont have permissions to view this page';
die;
return false;
}
Related
I am writing some code to interact with a login database on phpmyadmin through the following code.
However, I get the following error, it doesn't specify which line the error occurs at. It's been bugging me for 3 days, and my researches didn't lead to any solution. Just in case : SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Can someone help me pinpoint the problem please?
Thank you in advance.
<?php
session_start();
$user_name = "test" ;
$user_password = "test";
/* Login to database */
$DB_name = "adaming_login_db";
$DB_user = "root";
$DB_pass = "";
$DB_host = "localhost";
try
{
$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
class USER
{
private $db;
public function __construct($DB_con)
{
$this->db = $DB_con;
}
public function login($user_name,$user_password)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM login_info WHERE user_name = :$user_name AND user_password = :$user_password");
$stmt->execute(array(':user_name'=>$user_name, ':user_password'=>$user_password));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if($user_password == $userRow['user_password'] && $user_name == $userRow['user_name'] )
{
$_SESSION['user_session'] = $userRow['user_id'];
echo "Success";
return true;
}
else
{
echo "Failed";
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
$user = new USER($DB_con);
$user->login($user_name,$user_password);
?>
You need to remove dollar signs from your query. Change:
$stmt = $this->db->prepare("SELECT * FROM login_info WHERE user_name = :$user_name AND user_password = :$user_password");
to
$stmt = $this->db->prepare("SELECT * FROM login_info WHERE user_name = :user_name AND user_password = :user_password");
I am building a login portal with mySQL and PHP
I have this file (dbc.php):
<?php
class db_connect {
protected $DB_SERVER = "localhost";
protected $DB_USERNAME = "root";
protected $DB_PASSWORD = "";
protected $DB_DATABASE = "mydb";
public function connect() {
$conn = new mysqli($this->DB_SERVER, $this->DB_USERNAME, $this->DB_PASSWORD, $this->DB_DATABASE);
if(mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_errno());
}
return $conn;
}
}
?>
Then my actual PHP script (login.php) takes a POST from the login page:
<?php
//include database connection
include("dbc.php");
session_start();
//put post values into variables
$username = $_POST['username'];
$password = $_POST['password'];
//create db connector object
$db = new db_connect();
$conn = $db->connect();
//select correct db
mysqli_select_db($conn,”mydb”);
$username = mysqli_real_escape_string($conn,$username);
$query = "SELECT password FROM mydb.users WHERE username = '$username'";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result) == 0)
{
header('Location: sorry.html');
}
$pwhash = $result;
if (password_verify($password, $pwhash)) {
header('Location: welcome.php');
} else {
header('Location: sorry.html');
}
?>
This never returns a value which is odd.
Any help appreciated!
$result holds a MySQLi response resource, not a string or array.
You need to change this line:
$pwhash = $result;
To this:
$pwhash = mysqli_fetch_assoc($result)['password'];
I want to create a script that runs any query from through PHP the same way you would run it through the MySQL console just by calling MySQL::query([the query]);.
I have created a good portion of the PHP script already but I think I'm stuck. So far it can pull information just fine but it does not like it when I try to make any changes to the database itself. I would like it to also write to MySQL as well, but I can't figure out how to do it dynamically.
Here is the code I have so far:
<?php
include '..\..\shared\Error_Code.php';
class MySQL {
private static $host;
private static $username;
private static $password;
private static $database;
private static $logged_in = false;
public static function login($host, $username, $password, $database) {
self::$host = $host;
self::$username = $username;
self::$password = $password;
self::$database = $database;
if (self::confirm_login()) {
self::$logged_in = true;
} else {
self::$logged_in = false;
Error_Code::print(107.0); //There was an issue with the login.
}
}
public static function change_database($database) {
if (self::$logged_in) {
$old_database = self::$database;
self::$database = $database;
if (!self::confirm_login()) {
self::$database = $database;
Error_Code::print(107.1); //The database you entered dose not exist.
}
} else {
Error_Code::print(107.2); //You have not logged in yet.
}
}
private static function confirm_login($host = -1, $username = -1, $password = -1, $database = -1) {
$host = (($host != -1) ? $host : self::$host);
$username = (($username != -1) ? $username : self::$username);
$password = (($password != -1) ? $password : self::$password);
$database = (($database != -1) ? $database : self::$database);
if (!(is_null(self::$host) || is_null(self::$username) || is_null(self::$password) || is_null(self::$database))) {
$connection = mysqli_connect($host, $username, $password);
if ($connection) {
$response = mysqli_query($connection, "SHOW DATABASES");
$bg_db = array("information_schema", "mysql", "performance_schema", "phpmyadmin", "test");
if (!in_array(self::$database, $bg_db)) {
while ($row = mysqli_fetch_assoc($response)) {
if($row['Database'] == self::$database) {
return true;
}
}
}
Error_Code::print(107.8); //Login information is wrong.
return false;
} else {
Error_Code::print(107.9); //Login information is wrong.
return false;
}
} else {
Error_Code::print(107.7); //Login information is missing.
return false;
}
}
public static function logged_in() {
return self::$logged_in;
}
public static function query($query, $host = -1, $username = -1, $password = -1, $database = -1) {
$host = (($host != -1) ? $host : self::$host);
$username = (($username != -1) ? $username : self::$username);
$password = (($password != -1) ? $password : self::$password);
$database = (($database != -1) ? $database : self::$database);
$continue = self::confirm_login($host, $username, $password, $database);
if ($continue) {
return new Data($query, $host, $username, $password, $database);
} else {
return new Data($query, $host, $username, $password, $database);
Error_Code::print(107.3); //You have not logged into a database.
}
}
}
class Data {
private $query;
private $host;
private $username;
private $password;
private $database;
public function __construct($query, $host, $username, $password, $database) {
if ($query < 0) {
return $this;
} else {
$this->query = $query;
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
return $this->get();
}
}
//get data from a database using an SQL query
public function get() {
//query database
$connection = mysqli_connect($this->host, $this->username, $this->password, $this->database);
if ($connection) {
$response = mysqli_query($connection, $this->query);
//get data from query
if ($response) {
$rows = array();
while ($row = mysqli_fetch_array($response, MYSQLI_ASSOC)) {
array_push($rows, $row);
}
return $rows;
} else {
if (true) {
//<----- I THINK THIS IS WHERE I WOULD HAVE TO ADD THE CODE FOR MAKING CHANGES TO THE DATABASE
//$prepare = mysqli_prepare($connection, $this->query);
//mysqli_stmt_execute($prepare);
} else {
Error_Code::print(108.0); //Could not run query because there was no response
return -1;
}
}
} else {
Error_Code::print(108.1); //Could not run query because there was no connection
return -1;
}
}
//print the results of the query to a table
public function print_table($table_id = -1) {
$data = $this->get();
if ($data < 0) {
Error_Code::print(108.2); //Could not build table do to an issue with the query.
return -1;
} else {
$th = "<tr>";
foreach ($data[0] as $col => $value) {
$th = "$th<th>$col</th>";
}
$th = "$th</tr>";
$td = "";
foreach ($data as $row) {
$td = "$td<tr>";
foreach ($row as $col => $value) {
$td = "$td<td>$value</td>";
}
$td = "$td</tr>";
}
$table_id = ($table_id < 0) ? "" : " id='$table_id'";
echo "<table class='database_data'$table_id>$th$td</table>";
return 1;
}
}
}
?>
Any ideas on what I can change to get it to INSERT, DELETE, UPDATE and everything else.
Check this out:
https://github.com/indieteq/indieteq-php-my-sql-pdo-database-class
It might be a bit too much for your needs, but is, in my opinion, a great example of how to build a database class
I'm beginning php/MySql and have been asked to use a class to access my database. I can get the display to work when I have all my code in one file but when I try to call the class from another file, I get nothing.
This is the one that works:
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';
$myNewConnection = mysqli_connect($host,$username,$password,$dbname);
$query = "SELECT user_name FROM users" or die ("Error..." . mysqli_error($myNewConnection));
// execute the query
$result = $myNewConnection->query($query);
// display output
while($row = mysqli_fetch_array($result)) {
echo $row["user_name"] . "<br>";
}
?>
This is my code to call the class:
<?php
include("users.php");
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';
//initiate the class
$myDB = new MyDB('localhost', 'root', '', 'testdb');
//$myDB = new MyDB($host,$username,$password,$dbname);
?>
This is my class:
<?php
class MyDB {
public $query;
public $myConnection;
public function _construct($host,$username,$password,$dbname){
// establish the connection
$this->myConnection = mysqli_connect($host,$username,$password,$dbname);
}
public function list_users() {
// create query to list all users
$this->query = "SELECT user_name FROM users" or die ("Error..." . mysqli_error($this->$myNewConnection));
// execute the query
$result = $this->$myConnection->query($this->$query);
// display output
while($row = mysqli_fetch_array($result)) {
echo $row["user_name"] . "<br>";
}
}
}
?>
Any help appreciated
Change this line as below (remove the dollar sign from query and myConnection):
$result = $this->myConnection->query($this->query);
Plus you might need to call your list_users function using the code below (right after instantiating your class! Pass your defined variables to constructor instead of their actual values):
$myDB = new MyDB($host,$username,$password,$dbname);
$myDB->list_users();
Also constructors are written with two underscores like this:
public function __construct
function __construct with two "_". Delete all "$" after "->":
<?php
class MyDB {
public $query;
public $myConnection;
public function __construct($host,$username,$password,$dbname){
$this->myConnection = mysqli_connect($host,$username,$password,$dbname);
}
public function list_users() {
$this->query = "SELECT user_name FROM users";
if($result = $this->myConnection->query($this->query)) {
while($row = mysqli_fetch_array($result)) {
echo $row["user_name"] . "<br>";
}
}
}
}
And you have to run list_users():
<?php
include("users.php");
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';
$myDB = new MyDB($host, $username, $password, $dbname);
$myDB->list_users();
?>
What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();