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 5 years ago.
Improve this question
I need to convert this simple php code to codeigniter model and controller .
inside while loop when fetching data $row indexing should be comes through foreach loop($columns).
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dt";
$columns[0] = 'id';
$columns[1] = 'first_name';
$columns[2] = 'last_name';
$columns[3] = 'position';
$columns[4] = 'office';
$columns[5] = 'salary';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$where_clause = "";
$where_clause_array = [];
foreach($_REQUEST['columns'] as $key=>$column) {
if($column['search']['value'] != '') {
$where_clause_array[] = $columns[$column['data']]." LIKE "."'".$column['search']['value']."%'";
}
}
if(sizeof($where_clause_array) > 0) {
$where_clause = " WHERE ".implode(" AND ", $where_clause_array);
}
$order_by = " ORDER BY ".$columns[$_REQUEST['order'][0]['column']]." ".$_REQUEST['order'][0]['dir'];
$limit = " LIMIT ".$_REQUEST['start'].", ".$_REQUEST['length'];
$sql = "SELECT * FROM users".$where_clause.$order_by.$limit;
$result = $conn->query($sql);
$sqlTotal = $sql = "SELECT * FROM users".$where_clause.$order_by;
$resultTotal = $conn->query($sqlTotal);
$finalResult = [];
$finalResult['draw'] = $_REQUEST['draw'];
$finalResult['recordsTotal'] = $resultTotal->num_rows;
$finalResult['recordsFiltered'] = $resultTotal->num_rows;
$i=0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$finalResult['data'][$i][] = $row["id"];
$finalResult['data'][$i][] = $row["first_name"];
$finalResult['data'][$i][] = $row["last_name"];
$finalResult['data'][$i][] = $row["position"];
$finalResult['data'][$i][] = $row["office"];
$finalResult['data'][$i][] = $row["salary"];
$i++;
}
} else {
$finalResult['data'] = [];
}
echo json_encode($finalResult);
$conn->close();?>
I need to convert this simple php code to codeigniter model and controller .
inside while loop when fetching data $row indexing should be comes through foreach loop($columns).
Thanks
Step-1
First thing first, DB credentials goes to application->config->database.php
Step-2
Controller
class controllerName extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('your_model');
}
public function index(){
$data['columns'][0]='id';
$data['columns'][1]='first_name';
$data['columns'][2]='last_name';
$data['columns'][3]='position';
$data['columns'][4]='salary';
$result=json_encode($this->your_model->getResults($data));
print_r($result);
}
}
Step-3
Model
class Your_model extends CI_Model {
public function getResults($data)
{
$where_clause = "";
$where_clause_array = [];
foreach($_REQUEST['columns'] as $key=>$column) {
if($column['search']['value'] != '') {
$where_clause_array[] = $columns[$column['data']]." LIKE "."'".$column['search']['value']."%'";
}
}
if(sizeof($where_clause_array) > 0) {
$where_clause = " WHERE ".implode(" AND ", $where_clause_array);
}
$order_by = " ORDER BY ".$columns[$_REQUEST['order'][0]['column']]." ".$_REQUEST['order'][0]['dir'];
$limit = " LIMIT ".$_REQUEST['start'].", ".$_REQUEST['length'];
}
$result=$this->db->query('SELECT * from users'$where_clause.$order_by.$limit)->result_array();
return $result;
}
Related
I have a showProduct.php file from where i want to call a function showProduct() in another file. In showProduct() i want to extract all rows from database and to showProduct.php file. the issue is that when i return the array only last row is showing. I want to show all the rows.
The showProduct.php is:
<?php
require_once '../includes/DbOperations.php';
$response = array();
$result = array();
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$db = new DbOperations();
$result = $db->showProduct();
if(!empty($result))
{
$response["prod_name"] = $result["prod_name"];
$response["prod_desc"] = $result["prod_desc"];
$response["prod_image"] = $result["prod_image"];
}
else
{
$response["error"] = true;
$response["message"] = "products are not shown";
}
}
echo json_encode($response);
?>
and showProduct() function is:
public function showProduct(){
$menu = array();
$query = mysqli_query($this->con,"SELECT * FROM `products` WHERE 1");
while ($row = mysqli_fetch_array($query)) {
$menu['prod_name'] = $row['prod_name'] ;
$menu['prod_desc'] = $row['prod_desc'] ;
$menu['prod_image'] = $row['prod_image'];
}
return $menu;
}
In your function, you are just overwriting the last data each time, you need to build this data up. Create an array with the new data and use $menu[] to add this new data to the list of menus...
public function showProduct(){
$menu = array();
$query = mysqli_query($this->con,"SELECT * FROM `products` WHERE 1");
while ($row = mysqli_fetch_array($query)) {
$newMenu = []; // Clear array to ensure no details left over
$newMenu['prod_name'] = $row['prod_name'] ;
$newMenu['prod_desc'] = $row['prod_desc'] ;
$newMenu['prod_image'] = $row['prod_image'];
$menu[] = $newMenu;
}
return $menu;
}
I am trying to create a JSON object as an array from the data received from the SQL Query. Currently the encoded JSON I have got is:
[{"firstname":"Student","lastname":"1"},{"firstname":"Student","lastname":"2"},{"firstname":"Student","lastname":"3"}]
The values I want to insert from another array, the values are in corresponding order to the each array in the JSON above: (JSON)
["85.00000","50.00000","90.00000"]
So the JSON should look like:
{"firstname":"Student","lastname":"1","grade":"85.00000"}
My Current Code:
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
$sqldata = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
foreach($userid as $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
$sqlr = json_encode($sqldata);
$grd = json_encode($grade);
echo $sqlr;
echo $grd;
mysqli_close($conn);
try this code:
foreach($userid as $x => $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row['grade'] = $grade[$x];
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
I added the Variable $x and added $row['grade'] with the same index on the $gradearray
function set_column_values($arr, $column_name, $column_values) {
$ret_arr = array_map(function($arr_value, $col_value) use ($column_name) {
$arr_value[$column_name] = $col_value;
return $arr_value;
}, $arr, $column_values);
return $ret_arr;
}
$sqldata = set_column_values($sqldata, 'grades', $grade);
$sqlr = json_encode($sqldata);
var_dump($sqlr);
Hope it helps!
I get an error in my file "checkusername.php".
The error I get is:
( ! ) Fatal error: Call to a member function get() on null in
C:\wamp\www\Cocolani\php\req\checkusername.php on line 4
There is a "checkusername.php" file :
<?php
include_once("../../includes/db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$username = isset($_POST['username']) ? mysqli_real_escape_string($_POST['username']) : "";
$password = isset($_POST['password']) ? mysqli_real_escape_string($_POST['password']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : '';
$birthdate = isset($_POST['birthdate']) ? mysqli_real_escape_string($_POST['birthdate']) : "";
$firstname = isset($_POST['firstname']) ? mysqli_real_escape_string($_POST['firstname']) : "";
$lastname = isset($_POST['lastname']) ? mysqli_real_escape_string($_POST['lastname']) : "";
$sex = isset($_POST['sex']) ? mysqli_real_escape_string($_POST['sex']) : "";
$tribeid = isset($_POST['clan']) ? mysqli_real_escape_string($_POST['clan']) : "";
$mask = isset($_POST['mask']) ? mysqli_real_escape_string($_POST['mask']) : "";
$mask_color = isset($_POST['maskcl']) ? mysqli_real_escape_string($_POST['maskcl']) : "";
$lang_id = isset($_POST['lang_id']) ? addslashes($_POST['lang_id']) : 0;
$error = '';
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$reg_ok = true;
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'"; // for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
if ($email_check_ok == false) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
/*if ($reg_ok && $email != '') {
// get number of already registered number of registrations with this email address
$sql = "SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
$registered_num_emails = $row->registered_num_emails;
$sql = "SELECT max_num_account_per_email from `cc_def_settings`";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
// it's possible to create new registration using this email address
if ($registered_num_emails >= $row->max_num_account_per_email) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}*/
////////
// echo 'error=111';
// $reg_ok = false;
////////
if ($reg_ok) {
// check for swear words
$db->setQuery("SELECT COUNT(*) as counter from `cc_swear_words` where INSTR('".$username."', `name`)");
$res2 = $db->loadResult();
if ((int)($res2->counter) > 0) { // swear word founded!
$sql = "SELECT * FROM `cc_translations` WHERE caption='USERNAME_NOT_PERMITTED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) {
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ((int)($res->counter) > 0) { // swear word founded!
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) echo 'result=true';
?>
The problem on line 4 which is :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
There is a "settings.php" :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "pass1234";
$db_name = "cocolani_battle";
$appsecret = "80f730a73ac60417c36c341bc975f6f1";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
and there is a "db.php" :
<?php
/*
Usage
$db = new database($dbname);
for selects:
$db->setQuery("SELECT * FROM `table`")
$resultArray = $db->loadResults();
$db->setQuery("SELECT * FROM `table` WHERE `primary_id` = '1'");
$resultObject = $db->loadResult();
for inserts:
$db->setQuery("INSERT INTO `table` (`id`, `example`) VALUES ('1', 'abc')");
if (!$db->runQuery()) {
echo $db->getError();
}
*/
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "pass1234";
var $_DBname = "cocolani_battle";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
}
/*if ($_SERVER["SERVER_ADDR"] == '127.0.0.1') {
$url_root = "http://cocolani.localhost";
} else {
$url_root = "http://dev.cocolani.com";
}*/
?>
How can I fix this error?
As I mentioned in my comment, you can either use the variables you defined in your settings.php:
$db = new database($db_name, $db_server, $db_user, $db_password, $db_urlroot); // You didn't define $db_urlroot anywhere, but you can define it
OR hard-code it into your class. You're not using the variables you pass in anyway, so there's no need to ask for them.
public function __construct() {
For some reason I am getting this notice in my code.
Variable $conn seems to be uninitialized
I don't understand why I'm seeing this notice. I think I'm including my include in the right place.
Class Calendar {
public function show() {
include './includes/dbconn.php';
include_once './includes/functions.php';
for ($i=0; $i<$weeksInMonth; $i++) {
// Create days in a week
for ($j=1;$j<=7;$j++) {
$cal_date = (string)$this->currentDate;
$tutor_date = display_tutor_schedule($conn,$cal_date);
if(isset($tutor_date[$j]['date'])) {
$content .= $this->_showDay($i*7+$j, $tutor_date[$j]['date']);
}
else {
$content .= $this->_showDay($i*7+$j, 0);
}
}
$content .="</tr>";
}
}
}
My $conn variable is coming from include './includes/dbconn.php';. Since I am not getting any PHP database error, such as "Not connected to the database" or something like that, I assume that my connection is right.
functions.php
function display_tutor_schedule($conn,$tutor_date) {
$query = "select * from [dbo].[TUTOR_SCHEDULE] "
. "LEFT JOIN [dbo].[TUTOR] "
. "ON [dbo].[TUTOR_SCHEDULE].tutor_id = [dbo].[TUTOR].tutor_id "
. "LEFT JOIN [dbo].[STATUS] "
. "ON [dbo].[STATUS].status_id = [dbo].[TUTOR_SCHEDULE].status_id "
. "WHERE [dbo].[TUTOR_SCHEDULE].date = '$tutor_date' " ;
$stmt = sqlsrv_query($conn, $query);
$i = 0;
$appt_detail = array();
while ($row = sqlsrv_fetch_array($stmt)) {
$appt_detail[$i]['date'] = $row['date'];
$appt_detail[$i]['t_shedule_id'] = $row['t_shedule_id'];
$appt_detail[$i]['start_time'] = $row['start_time'];
$appt_detail[$i]['end_time'] = $row['end_time'];
$appt_detail[$i]['tutor_fname'] = $row['tutor_fname'];
$appt_detail[$i]['tutor_lname'] = $row['tutor_lname'];
$appt_detail[$i]['status_name'] = $row['status_name'];
$appt_detail[$i]['status_id'] = $row['status_id'];
$i++;
}
return $appt_detail;
}
my_class.php
<?php
$calendar = new Calendar();
echo $calendar->show();
?>
dbconn.php
$serverName = "myserver";
$connectionInfo = array("Database" => "my_database", "UID" => "user", "PWD" => "pwd");
$conn = sqlsrv_connect($serverName, $connectionInfo);
If you are using NetBeans or PhpStorm, then this might be IDE issue.
Check https://netbeans.org/projects/php/lists/users/archive/2013-03/message/49 and PhpStorm warning PHP variable might not have been defined
However, it is advisable that you show us the files you include to check them.
Don't use includes or global for your variables. It's bad.
Instead you should be using classes:
class Database {
private $conn;
public function __construct(){
$serverName = "myserver";
$connectionInfo = array("Database" => "my_database",
"UID" => "user",
"PWD" => "pwd");
$this->conn = sqlsrv_connect($serverName, $connectionInfo);
}
public function get_connection(){
return $this->conn;
}
}
Calendar.php
class Calendar
{
private $conn;
public $weeksInMonth;
function __construct($conn){
$this->conn = $conn;
}
public function show()
{
$content = "";
for ($i = 0; $i < $this->weeksInMonth; $i++) {
//Create days in a week
for ($j = 1; $j <= 7; $j++) {
$cal_date = (string)$this->currentDate;
$tutor_date = display_tutor_schedule($cal_date);
if (isset($tutor_date[$j]['date'])) {
$content .= $this->_showDay($i * 7 + $j, $tutor_date[$j]['date']);
} else {
$content .= $this->_showDay($i * 7 + $j, 0);
}
}
$content .= "</tr>";
}
return $content;
}
function display_tutor_schedule($tutor_date)
{
$query = "select * from [dbo].[TUTOR_SCHEDULE] "
. "LEFT JOIN [dbo].[TUTOR] "
. "ON [dbo].[TUTOR_SCHEDULE].tutor_id = [dbo].[TUTOR].tutor_id "
. "LEFT JOIN [dbo].[STATUS] "
. "ON [dbo].[STATUS].status_id = [dbo].[TUTOR_SCHEDULE].status_id "
. "WHERE [dbo].[TUTOR_SCHEDULE].date = '$tutor_date' ";
$stmt = sqlsrv_query($this->conn, $query);
$appt_detail = array();
while ($row = sqlsrv_fetch_array($stmt)) {
$appt_detail[] = $row;
}
return $appt_detail;
}
}
Usage
$db = new Database();
$conn = $db->get_connection();
$calendar = new Calendar($conn);
$calendar->weeksInMonth = 4;
echo $calendar->show();
Since the variable is first initialized in the dbconn.php, the IDE might not recognize it. Insert
$conn = null;
after the line
public function show() {
Here's my deal:
I found a simple ACL, and have absolutely fallen in love with it. The problem? It's all in mysql, not mysqli. The rest of my site is written in mysqli, so this bothers me a ton.
My problem is that the ACL can easily connect without global variables because I already connected to the database, and mysql isn't object oriented.
1) Is it needed to convert to mysqli?
2) How can I easily convert it all?
Code:
<?
class ACL
{
var $perms = array(); //Array : Stores the permissions for the user
var $userID = 0; //Integer : Stores the ID of the current user
var $userRoles = array(); //Array : Stores the roles of the current user
function __constructor($userID = '')
{
if ($userID != '')
{
$this->userID = floatval($userID);
} else {
$this->userID = floatval($_SESSION['userID']);
}
$this->userRoles = $this->getUserRoles('ids');
$this->buildACL();
}
function ACL($userID = '')
{
$this->__constructor($userID);
//crutch for PHP4 setups
}
function buildACL()
{
//first, get the rules for the user's role
if (count($this->userRoles) > 0)
{
$this->perms = array_merge($this->perms,$this->getRolePerms($this->userRoles));
}
//then, get the individual user permissions
$this->perms = array_merge($this->perms,$this->getUserPerms($this->userID));
}
function getPermKeyFromID($permID)
{
$strSQL = "SELECT `permKey` FROM `permissions` WHERE `ID` = " . floatval($permID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
function getPermNameFromID($permID)
{
$strSQL = "SELECT `permName` FROM `permissions` WHERE `ID` = " . floatval($permID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
function getRoleNameFromID($roleID)
{
$strSQL = "SELECT `roleName` FROM `roles` WHERE `ID` = " . floatval($roleID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
function getUserRoles()
{
$strSQL = "SELECT * FROM `user_roles` WHERE `userID` = " . floatval($this->userID) . " ORDER BY `addDate` ASC";
$data = mysql_query($strSQL);
$resp = array();
while($row = mysql_fetch_array($data))
{
$resp[] = $row['roleID'];
}
return $resp;
}
function getAllRoles($format='ids')
{
$format = strtolower($format);
$strSQL = "SELECT * FROM `roles` ORDER BY `roleName` ASC";
$data = mysql_query($strSQL);
$resp = array();
while($row = mysql_fetch_array($data))
{
if ($format == 'full')
{
$resp[] = array("ID" => $row['ID'],"Name" => $row['roleName']);
} else {
$resp[] = $row['ID'];
}
}
return $resp;
}
function getAllPerms($format='ids')
{
$format = strtolower($format);
$strSQL = "SELECT * FROM `permissions` ORDER BY `permName` ASC";
$data = mysql_query($strSQL);
$resp = array();
while($row = mysql_fetch_assoc($data))
{
if ($format == 'full')
{
$resp[$row['permKey']] = array('ID' => $row['ID'], 'Name' => $row['permName'], 'Key' => $row['permKey']);
} else {
$resp[] = $row['ID'];
}
}
return $resp;
}
function getRolePerms($role)
{
if (is_array($role))
{
$roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC";
} else {
$roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC";
}
$data = mysql_query($roleSQL);
$perms = array();
while($row = mysql_fetch_assoc($data))
{
$pK = strtolower($this->getPermKeyFromID($row['permID']));
if ($pK == '') { continue; }
if ($row['value'] === '1') {
$hP = true;
} else {
$hP = false;
}
$perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']);
}
return $perms;
}
function getUserPerms($userID)
{
$strSQL = "SELECT * FROM `user_perms` WHERE `userID` = " . floatval($userID) . " ORDER BY `addDate` ASC";
$data = mysql_query($strSQL);
$perms = array();
while($row = mysql_fetch_assoc($data))
{
$pK = strtolower($this->getPermKeyFromID($row['permID']));
if ($pK == '') { continue; }
if ($row['value'] == '1') {
$hP = true;
} else {
$hP = false;
}
$perms[$pK] = array('perm' => $pK,'inheritted' => false,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']);
}
return $perms;
}
function userHasRole($roleID)
{
foreach($this->userRoles as $k => $v)
{
if (floatval($v) === floatval($roleID))
{
return true;
}
}
return false;
}
function hasPermission($permKey)
{
$permKey = strtolower($permKey);
if (array_key_exists($permKey,$this->perms))
{
if ($this->perms[$permKey]['value'] === '1' || $this->perms[$permKey]['value'] === true)
{
return true;
} else {
return false;
}
} else {
return false;
}
}
function getUsername($userID)
{
$strSQL = "SELECT `username` FROM `users` WHERE `ID` = " . floatval($userID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
}
?>
Just add a $mysqli property to this class and have the MySQLi object passed to it in constructor.
class ACL {
private $mysqli;
public function __construct(MySQLi $mysqli) {
$this->mysqli = $mysqli;
/* rest of your code */
}
}
The rest is pretty much search and replace.
The code is written to support PHP4. That tells me two things: firstly, the author couldn't use mysqli even if he wanted to, because PHP4 didn't have it, and secondly, the code is probably pretty old, and was written before the PHP devs started really trying to push developers to use mysqli instead of mysql.
If it's well written, then converting it to use mysqli instead should be a piece of cake. The API differences between mysql and mysqli at a basic level are actually pretty minimal. The main difference is the requirement to pass the connection object to the query functions. This was optional in mysql and frequently left out, as it seems to have been in this code.
So your main challenge is getting that connection object variable to be available wherever you make a mysqli function call. The easy way to do that is just to make it a property of the class, so it's available everywhere in the class.
I also recommend you drop the other php4 support bits; they're not needed, and they get in the way.