$_GET and isset() url response Json - php

I have use a lot of answers here to solve almost everything, but i can't figure out how to accomplish this;
I use PHP to get data from my MySQL, and encode to json with url request, so wen I go to miweb. com /_js/ajax/load_content.php?f=1
I get a perfect response from my databesa and echo to json encode, 1 means user with id number 1
my response looks like this:
[{"i":"1","n":"Azul","p":"_imgs\/site\/iconos\/0-100\/22\/activo\/ico_00022_138.jpg"}]
and if i go to miweb. com/_js/ajax/load_content.php?f=2 i will get
[{"i":"2","n":"Lety","p":"_imgs\/site\/iconos\/0-100\/87\/activo\/ico_00087_138.jpg"}]
what i need to accomplish is to go to ?f=1,2
miweb.com /_js/ajax/load_content.php?f=1,2 and get the response in same json like this
[{"i":"1","n":"Azul","p":"_imgs\/site\/iconos\/0-100\/22\/activo\/ico_00022_138.jpg"},
{"i":"2","n":"Lety","p":"_imgs\/site\/iconos\/0-100\/87\/activo\/ico_00087_138.jpg"}]
this is my php scrip:
require '../../system/config.php';
if( isset($_GET['h']) ) {
get_ficha($_GET['h']);
} else {
die("Solicitud no vĂ¡lida.");
}
function get_ficha( $id) {
// CONECCION DATABASE//
$database = new mysqli(HOST, USER, PASS, DBNAME);
if($database->connect_errno) {
die("No se pudo conectar a la base de datos");
}
mysqli_set_charset($database, "utf8");
//Sanitize ipnut y preparar query
if( is_array($id) ) {
$id = array_map('intval', $id);
$promo = "WHERE `ID` IN (" . implode( ',', $id ) . ")";
} else {
$id = intval($id);
$promo = "WHERE `ID` = " . $id;
}
if ( $result = $database->query( "SELECT * FROM (ficha)" . $promo) ) {
if( $result->num_rows > 0 ) {
$promo = array();
while( $row = mysqli_fetch_array($result))
{
$id=$row['id'];
$nombre=$row['nombre'];
$icono=$row['ico_138'];
$promo[] = array(
'i'=> $id,
'n'=> $nombre,
'p'=> $icono
);
}
} else {
$promo = array(
);
}
$result->close();
} else {
$promo["success"] = false;
$promo["data"] = array(
'message' => $database->error
);
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($promo, JSON_UNESCAPED_UNICODE);
$database->close();
}
exit();

You need to explode the get variable
get_ficha(explode(',', $_GET['h']));
Then in your function
if( is_array($id) && count($id) > 1) {
$id = array_map('intval', $id);
$promo = "WHERE `ID` IN (" . implode( ',', $id ) . ")";
} else {
$id = intval($id);
$promo = "WHERE `ID` = " . $id;
}

Related

Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4

I'm still a beginner programmer , so I hope you give the solution step by step.
I'm trying to make a private server for a flash game and i have a problem that I don't know how can I solve it at all .
I wanna connect the game with the database , and when someone tries to make an account (register) in the game , the account data supposed to be saved in the database ( like: username,password,mask color,birth date,register date,etc...) but it doesn't happen
The file which is responsible about this step is called " register.php" and
I keep getting this error :
Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4
the problem is in this line :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
and this is "register.php" :
<?php
include_once("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"));
$FROM_EMAIL = $obj->getEmailFrom();
function generateTribeCurrency($ID, $db) {
// $db = new database();
// get init purse amount
$db->setQuery("SELECT init_purse_amount FROM `cc_def_settings`");
$row = $db->loadResult();
$init_purse_amount = $row->init_purse_amount;
// load tribe info
$db->setQuery("SELECT * FROM `cc_tribes`");
$tribeinfo = $db->loadResults();
$newstr = array();
foreach ($tribeinfo as $i) {
if ($ID == $i->ID) array_push($newstr, $init_purse_amount); else array_push($newstr, 0);
}
$newstr = implode(",", $newstr);
return $newstr;
}
$hackchk = false;
foreach($_POST as $POST) {
$POST = mysqli_real_escape_string($POST);
}
function remove_bad_symbols($s) {
return preg_replace(
array(0=>'#/#', 1=>'#\\\#', 2=>'#;#', 3=>'#{#', 4=>'#}#', 5=>'#<#', 6=>'#>#', 7=>'###', 8=>'#\'#', 9=>'# #', 10=>'#"#') // patterns
, '' // replacements
, $s);
}
$username = isset($_POST['username']) ? remove_bad_symbols($_POST['username']) : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$birthdate = isset($_POST['birthdate']) ? $_POST['birthdate'] : "";
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$sex = isset($_POST['sex']) ? $_POST['sex'] : "";
$tribeid = isset($_POST['clan']) ? $_POST['clan'] : "";
$mask = isset($_POST['mask']) ? $_POST['mask'] : "";
$mask_color = isset($_POST['maskcl']) ? $_POST['maskcl'] : "";
$lang_id = isset($_POST['lang_id']) ? $_POST['lang_id'] : 0;
$error = '';
$purse = generateTribeCurrency((int) $tribeid, $db);
// 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 = "";
$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";
}
// 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 ($username && $email && $sex && $birthdate) {
if ($email_check_ok) {
if ($res->counter == "0") {
// check that there are no registrations from this same IP in the last 2 hours
$db->setQuery("SELECT COUNT(*) as counter FROM `cc_userreginfo` WHERE IP='".$_SERVER['REMOTE_ADDR']."' AND (DATE_SUB(CURDATE(), INTERVAL 2 HOUR)<register_date)");
$regcheck = $db->loadResult();
if (($regcheck != null && (int)($regcheck->counter) == 0) || $hackchk == false) {
// get number of already registered number of registrations with this email address
$query = $db->setQuery("SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'");
$row = $db->loadResult();
$already_registered_num_emails = $row->registered_num_emails;
// get max number of accounts per email from settings table
$query = $db->setQuery("SELECT max_num_account_per_email from `cc_def_settings`");
$row = $db->loadResult();
$max_num_account_per_email = $row->max_num_account_per_email;
if ($already_registered_num_emails < $max_num_account_per_email) {
$uniqid = uniqid();
$newreq = "INSERT INTO `cc_user` (`ID`,`username`, `password`, `email`, `birth_date`, `first_name`, `last_name`, `sex`, `about`, `mask`, `mask_colors`, `clothing`, `tribe_ID` , `money`, `happyness`, `rank_ID`, `status_ID`, `lang_id`, `register_date`, uniqid, permission_id) VALUES ";
$newreq .= "(NULL, '{$username}', '{$password}', '{$email}', '{$birthdate}', '{$firstname}' , '{$lastname}', '{$sex}', '', '{$mask}', '{$mask_color}', '', '{$tribeid}', '{$purse}', 50, 0, 3, '{$lang_id}', NOW(), '{$uniqid}', 4)";
$db->setQuery($newreq);
$res = $db->runQuery();
if ($res) {
// add registration info into the userreginfo table as well.
$iid = $db->mysqlInsertID();
$db->setQuery("INSERT INTO `cc_userreginfo` (`ID`, `user_id`, `register_IP`, `register_date`, `last_update`) VALUES (NULL, ".$iid.",'".$_SERVER['REMOTE_ADDR']."', NOW(), NOW())");
$res2 = $db->runQuery();
$counter = ($regcheck != null) ? $regcheck->counter : 0;
echo 'response=true&reg='.$counter;
// ----------------------------------
// send confirmation email
// ----------------------------------
$cur_lang = ($lang != "") ? substr($lang, 1)."/" : "";
$msg = $obj->getTranslation(-13, $lang, "email_templates", "id", "content");
$msg = str_replace("%FIRST_NAME%", $firstname, $msg);
$msg = str_replace("%LAST_NAME%", $lastname, $msg);
$msg = str_replace("'", "'", $msg);
$msg = str_replace("%CONFIRM%", 'confirm', $msg);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
$headers .= 'From: '.$FROM_EMAIL."\r\n";
//mail($email, $obj->getTranslation(-13, $lang, "email_templates", "id", "subject"), $msg, $headers);
include "../../admin/php_mailer/class.phpmailer.php";
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $msg;
$body = eregi_replace("[\]",'',$body);
$mail->SetFrom($FROM_EMAIL);
$mail->AddAddress($email);
$mail->Subject = $obj->getTranslation(-13, $lang, "email_templates", "id", "subject");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
die("Mailer Error: " . $mail->ErrorInfo);
} else {
//echo "Message sent!";
}
// ----------------------------------
} else {
echo 'response=false';
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGISTER_LATER'");
$res = $db->loadResult();
echo 'errorhide='.urlencode($res->{"name".$lang});
}
} else {
// 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});
}
} else {
//if ($one_registration_per_email == true)
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'"; //else $sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_REGISTRATION'";
// get warning message from db
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGFORM_PROBLEM'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
?>
note : "register.php" requires two files so maybe the error is in one of them
settings.php :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "qazqazqaz1";
$db_name = "coco";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
db.php:
<?php
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "qazqazqaz1";
var $_DBname = "cocol";
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;
}
?>
I tried to solve it myself but I lost hope , so please tell me the accurate solution in steps .
thanks.
The error is referring to $obj->get. Basically you're executing the get method on a null variable, meaning it doesn't exist. After looking through all the code you have there, you aren't declaring $obj at any point.
I think you might need to check how you're passing in your settings to your Database object. For example:
$db = new database($db_server, ... , ...);
Updated:
You're hardcoding your connection anyway, just don't pass anything to the DB object.
Change this:
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
To this:
$db = new database();

Generic PHP function to get data from MySQL database

I'm creating a web application that relies heavily upon getting data from MySQL using PHP. In ~50 functions I have very similar code requesting single data values from MySQL:
function get_profile_picture($whatmember) {
global $connection;
$whatmember = mysql_prep($whatmember);
$query = "SELECT picture_location FROM members WHERE member_id={$whatmember} LIMIT 1";
$returnval = mysqli_query($connection,$query);
if(!$returnval) {
return "Query failed: " . mysqli_error($connection);
}
if(mysqli_num_rows($returnval) > 0 ) {
$row = mysqli_fetch_assoc($returnval);
return $row["picture_location"];
}
return false;
}
So my question is this: is there a generic AND safe way to make the function so that I can just input "SELECT what-value FROM what-database.what-table WHERE what-criteria=what-value" that allows for arrays of results as well as single values? I made an attempt with the following, but it obviously is a hack and slash method that only gets single values:
function get_single_value($database_name,$column_name,$table_name,$criteria,$criteria_value) {
$database_name = mysql_prep($database_name);
$column_name = mysql_prep($column_name);
$table_name = mysql_prep($table_name);
$criteria = mysql_prep($criteria);
$criteria_value = mysql_prep($criteria_value);
if(!empty($column_name) && !empty($table_name) && !empty($criteria) && !empty($database_name)) {
global $connection;
global $gamesconnection;
global $locationconnection;
if($database_name=="connection") {
$database_connection = $connection;
} else if ($database_name=="games") {
$database_connection = $gamesconnection;
} else if ($database_name=="locations") {
$database_connection = $locationconnection;
} else {
die("Database connection doesn't exist for {$database_name}.");
}
$query = "SELECT {$column_name} FROM {$table_name} WHERE {$criteria}='{$criteria_value}' LIMIT 1";
$result = mysqli_query($database_connection,$query);
if(!$result) {
die("Unable to get {$column_name} from {$table_name}. Error: " . mysqli_error($database_connection) . " Query: " . $query);
}
if(mysqli_num_rows($result)>0) {
$row = mysqli_fetch_assoc($result);
return $row[$column_name];
}
}
return false;
}
And my get_profile_picture() function would then look more like this:
function get_profile_picture($whatmember) {
return get_single_value("connection","picture_location","members","member_id",$whatmember);
}
I'm still pretty new to PHP and MySQL so any pointers to improve my code would be great as well. Thanks in advance!
Alright I wrote my own. It might not have all the security of PDO, but I don't have the learn another framework in order to use it.
function get_from_database($database_variable) {
//PASS IN $database_variable WHICH IS AN OBJECT CONTAINING THE FOLLOWING POSSIBLE VALUES
$database_name = $database_variable["database_name"]; //DATABASE NAME
$column_name = $database_variable["column_name"]; //COLUMN(S) BEING REQUESTED
$table_name = $database_variable["table_name"]; //TABLE BEING SEARCHED
$criteria = $database_variable["criteria"]; // 'WHERE X'
$limit = $database_variable["limit"]; //ANY LIMITS, IF REQUIRED
$group_by = $database_variable["group_by"]; //ANY GROUPING, IF REQUIRED
$order_by = $database_variable["order_by"]; //ANY SORT ORDERING, IF REQUIRED
if(!empty($column_name) && !empty($table_name)&& !empty($database_name)) {
global $connection;
global $gamesconnection;
global $locationconnection;
global $olddataconnection;
if($database_name=="connection") {
$database_connection = $connection;
} else if ($database_name=="games") {
$database_connection = $gamesconnection;
} else if ($database_name=="locations") {
$database_connection = $locationconnection;
} else if ($database_name=="olddata") {
$database_connection = $olddataconnection;
} else {
error_log("\nDatabase connection doesn't exist for {$database_name}." . get_backtrace_info());
return false;
}
if(is_null($limit)) {
//IF LIMIT NOT SUPPLIED, MAKE LIMIT 0, IE NO LIMIT
$limit = 0;
}
if(is_int($limit)==false) {
//NOT AN INTEGER
error_log("\nError in limit provided: " . $limit . get_backtrace_info());
return false;
}
$query = " SELECT {$column_name}
FROM {$table_name} " . (!empty($criteria) /*CHECK IF CRITERIA WAS REQUIRED*/ ? "
WHERE {$criteria} " : "") . (!empty($group_by) /*CHECK IF GROUP BY WAS REQUIRED*/ ? "
GROUP BY {$group_by} " : "") . (!empty($order_by) /*CHECK IF ORDER BY WAS REQUIRED*/ ? "
ORDER BY {$order_by} " : "") . ($limit!==0 /*CHECK IF LIMIT WAS REQUIRED*/ ? "
LIMIT {$limit} " : "");
$result = mysqli_query($database_connection,$query);
if(!$result) {
error_log("\nUnable to process query, got error: " . mysqli_error($database_connection) . "\nQuery: " . $query . get_backtrace_info());
return false;
}
if(mysqli_num_rows($result)>0) {
//RESULT SUPPLIED
$row_array = array();
while($row = mysqli_fetch_assoc($result)) {
$row_array[] = $row;
}
mysqli_free_result($result);
return $row_array;
}
}
return false;
}
Function to trace function call back to source:
function get_backtrace_info(){
//GET INFORMATION ON WHICH FUNCTION CAUSED ERROR
$backtrace = debug_backtrace();
$backtrace_string = "";
for($i=0;$i<count($backtrace);$i++) {
$backtrace_string .= '\n';
if($i==0) {
$backtrace_string .= 'Called by ';
} else {
$backtrace_string .= 'Which was called by ';
}
$backtrace_string .= "{$backtrace[$i]['function']} on line {$backtrace[$i]['line']}";
}
return backtrace_string;
}
Now I can request data from MySQL as follows:
Single value requested:
function get_profile_picture($whatmember) {
$linked_member_code = get_linked_member_code($whatmember);
return get_from_database([ "database_name" => "connection",
"column_name" => "picture_location",
"table_name" => "members",
"criteria" => "linked_member_code='{$linked_member_code}' AND team_id=0",
"limit" => 1
])[0]["picture_location"];
}
2 values requested:
function get_city_and_region_by_id($whatid) {
$row = get_from_database([ "database_name" => "locations",
"column_name" => "city, region",
"table_name" => "cities",
"criteria" => "row_id={$whatid}",
"limit" => 1
]);
return $row[0]["city"] . ", " . $row[0]["region"];
}
Unknown number of rows:
function get_linked_teams($linkedmembercode) {
return get_from_database([ "database_name" => "connection",
"column_name" => "team_id",
"table_name" => "members",
"criteria" => "linked_member_code='{$linkedmembercode}' AND team_id!=0"
]);
}

Is converting mysql to mysqli extremely necessary?

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.

Dynamically create a SQL statment from passed values in PHP

I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.

replace $_GET with array of $userslist

im using this script through $_GET to add user name to my db beside it to my twitter list the script function well
for examlpe when i call it at url domain.com/add.php?user=username
the function of adding executed 100% fine
My doubt is about adjust the code to add multi users at once through array or get list of user from file
any tips to adjust the code or modify it ?
<?php
session_start();
require_once('dbconnect.php');
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,TOKEN_KEY, TOKEN_SECRET);
$user = $_GET['user'];
if( !isset( $_GET['user'] ) )
die('You must enter a username');
$info = $connection->get( 'users/show', array("screen_name"=> $user
));
$var = $_GET['user'];
$individual = 1;
$protected = ($info->protected == "true")?1:0;
$query = sprintf("INSERT INTO tweeps VALUES('%s', '%s', %s, %s, '%s', '%s', '%s', %s ) ",
mysql_real_escape_string($info->screen_name),
mysql_real_escape_string($info->name),
$info->followers_count,
$info->statuses_count,
mysql_real_escape_string($info->location),
$info->created_at,
$info->profile_image_url,
$protected) ;
echo $query;
$result = mysql_query($query);
if(false)
echo "s";
else {
$list_id = get_latest_list();
$list = "Tweeps-" . $list_id;
echo "list $list";
mysql_free_result($result);
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET);
$result = $connection->post( 'friendships/create/' . $info->screen_name );
//var_dump($result); die();
$result = $connection->post( 'lists/members/create', array("screen_name"=> $info->screen_name,
"slug"=> $list,
"owner_screen_name"=> "Tweeps") );
if( !isset($result->error) ) {
$userid = $info->id;
$result = mysql_query("INSERT INTO followed_tweeps(screenname, userid, individual, list_id) VALUES('" . $info->screen_name . "', '" . $userid . "', $individual, $list_id)");
}
}
echo "SUCCESS";
function get_latest_list() {
$query = "SELECT count(*) cnt, list_id FROM followed_tweeps group by list_id order by list_id desc";
$result = mysql_query($query);
if(! $result ) {
die("Error: query is $query error is: " . mysql_error() );
}
$row = mysql_fetch_row($result);
$cnt = $row[0];
$free_slots = 500 - $cnt;
$list_id = ($freeslots > 0) ? $row[1]++ : $row[1];
return $list_id;
}
?>
PHP supports an array notation for multiple same-name query parameters:
<input type="text" name="name[]" />
^^--- tells PHP to treat 'name' as an array
You can then process this as:
if (isset($_GET['name']) && isarray($_GET['name'])) {
foreach ($_GET['name'] as $name) {
...
}
}
This works regardless for both POST and GET - you just have to include the [] on the field name.

Categories