PHP - Specifying Default Values For Bitmask Constants
I sometime pass configuration settings as an associate array... public function __construct(JsonValidatorMethods $methods, array $options) { foreach($options as $option) { //validate whether valid and if so set $this->$option. Options not provided will default to their private $strictMode=true value } } $validator=new JsonValidator($methods, ['sanitize'=>true, 'strictMode'=>true, 'setDefault'=>false]); And other times pass them as individual arguments... public function __construct(JsonValidatorMethods $methods, bool $sanitize=false, bool $strictMode=false, bool $setDefault=true) {} $validator=new JsonValidator($methods, true, true, false); I have a class which I was doing the later and also which I wish to allow them to be first set in the constructor but also specified when calling some of the public methods. It became a pain to pass all the individual flags to each private method, so I thought I would give bitmask constants a try as shown below. I recognize that this approach only allows booleans to be passed, but I am okay with this. The part I am not sure about is how best have default values. For instance, maybe the default is $this->options=0b0110, 0b1100 is passed to the constructor, and 0b1 (aka 0b0001) is passed is passed to the public method. The high three bits in 0b0001 just are not provided, but how can I not interpret them as explicitly false? Also, a little off topic, but am I implementing this bitmask approach correctly, and any strong options whether one of these three approaches or some totally other approach is best? Thanks class JsonValidator { //Use provided options const SANITIZE = 0b0001; //Whether to sanitize (i.e. 'false' is changed to false) const STRICTMODE = 0b0010; //Currently only enfources that boolean is true/false (instead of 1/0 or "true"/"false") const SETDEFAULT = 0b0100; //If true, type double and value "nan" will be converted to 0, etc. private $methods, $options; static public function create(int $options=0):self { return new self(new JsonValidatorMethods, $options); } static public function getOption(array $options):int { $o=0; foreach($options as $option) { if(!defined("self::$option")){ throw new JsonValidatorErrorException((is_string($option)?$option:'given constant').' is not valid'); } $o=$o|constant("self::$option"); } return $o; } public function __construct(JsonValidatorMethods $methods, int $options=0) { $this->methods=$methods; $this->options=$options; } public function validate(array $input, array $rules, int $options=0){ $options=$options|$this->options; if($options & self::SANITIZE) { $value=$this->sanitize($input, $rules, $options); } } private function sanitize(array $input, array $rules, int $options=0){} } $validator=new JsonValidator($methods, JsonValidator::SANITIZE|JsonValidator::SETDEFAULT); Edited June 27, 2019 by NotionCommotion Nevermind => Maybe I should start my constants with high bit set such as const SANITIZE = 0b1000; Similar Tutorials
Table Issue - Multiple Location Values For User Pushes Values Out Of Row Instead Of Wrapping In Cell
What is the difference between declaring values at the top of a class versus in between the parenthesis of a method? Class MyClass { private $table = 0; public $field = "name"; // etc... Class MyClass { private $_table; public $field; public function myFunction($_table=0, $field="name") {} This topic has been moved to HTML Help. http://www.phpfreaks.com/forums/index.php?topic=316203.0 I would like to define two constants to switch where my "Web Root" is located so I can go between my laptop and web host. I created a "config.inc.php" Code: [Select] <?php // Constants for Web Roots. define('DEV_ROOT', '/00_MyWebsite/'); define('PROD_ROOT', 'w w w.MyWebsite.com/'); ?> and then in my "checkout.php" page I have... Code: [Select] <body> <!-- Access Web Root Constants --> <?php require_once "../config.inc.php"; echo 'DEV _ROOT = ' . DEV_ROOT; echo 'PROD _ROOT = ' . PROD_ROOT; ?> But that doesn't seem to work so far. I know what I'm trying to do, but am getting stuck on how to do it?! Can someone help straighten me out?? Thanks, Debbie Hey all, Another OOP question from me Is using constants in a class a bad idea? For example I have a config file and have this in a class: header("Location: ".LOGIN_LOCATION); Also is it OK to define $_SERVER variables in a construct? For example I have: class whatever { private $_remote_addr; private $_user_agent; function __construct() { $this->_remote_addr = $_SERVER['REMOTE_ADDR']; $this->_user_agent = $_SERVER['HTTP_USER_AGENT']; } .. or is it OK just to use $_SERVER for example in a mysql query? Thanks for all the help so far. Getting there! Does anyone know how to echo a defined constant without using concatenation? something like Code: (php) [Select] <?php define("CONST", "VALUE"); echo <<<END Some html and my Const = CONST END; ?> This works but I want the var to be const Code: (php) [Select] <?php $CONST = "VALUE"; echo <<<END Some html and my Const = $CONST END; ?> Thanks for your replies I've been working on a registration form and it seems like the better I get at solving more complex issues the smaller issues plague me the most. I've got the following function: //process database actions function process_database($post) { global $table; //connect to database $connect_db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); //check database connection if ($connect_db->connect_error) { return false; } else { if ($stmt = $connect_db->prepare( "INSERT INTO $table (firstname, lastname, username, email, password) VALUES ( ?, ?, ?, ?, ? )" ) ) { $stmt->bind_param(NULL, $firstname, $lastname, $username, $email, $password); $firstname = $post['firstname']; $lastname = $post['lastname']; $username = $post['username']; $email = $post['email']; $password = $post['password']; if (!$stmt->execute()) { return false; } } } return true; } This is in a functions.php file. The issue is in the $connect_db assignment that has the constants from the config.php file in it. That file looks like this: <?php ob_start(); session_start(); $timezone = date_default_timezone_set("America/xxxxxxx"); $whitelist = array('username', 'email', 'email2', 'password', 'password2'); //TODO here I've removed firstname and lastname from the whitelist as they're optional //may add them back and try to iterate around them in the future $table = 'users'; define('DB_HOST', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'means'); $conn = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); if($conn->connect_errno) { printf("Connect Failed: %s\n", $conn->connect_error); exit(); } ob_end_flush(); ?> The constants defined in config.php are not being recognized in functions.php. I understand that constants are global and available throughout a script. I've connected to two files with the following line: //require config file require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php'); as I have the config/config.php outside htdocs. I know this works because of a db query to check uniqueness of username that works properly. Why are these constants coming back as undefined in the process_database().function.php? Nothing I've tried works and I've run out of ideas. TIA Often in the very beginning of index.php, I will define a bunch of constants. To make sure I can quickly identify them as being one of my defined constants, I will often include some sort of prefix.
define ('xzy_somecontant',123); define ('xzy_anothercontant',321);Sometimes I have a bunch of constants that are related; define ('xzy_id_for_page1',123); define ('xzy_id_for_page2',231); define ('xzy_id_for_page3',312);It would be nice to somehow group them into say "xzy_page_ids", and then access them by some index such as "page1" or "1" (or whatever makes sense for the given naming structure). Is this possible? Is there another defacto way of doing so such as a static class or something? Thanks Some questions about PHP Constants... 1.) What make a Constant "come to life"? 2.) What is the life of a Constant? 3.) Can you define a Constant in "file_1.php" and use the Constant in "file_2.php" and "file_3.php"?? Debbie Hi, I have a small CMS I coded and developped on my local WAMP server and everything worked fine but when I decided to export everything to my hostgator server I realized that the constants I define in some of my includes are not being defined.. Here is one of the errors I get : Code: [Select] Fatal error: require_once() [function.require]: Failed opening required 'LIB_PATHDSdatabase.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/nethox/public_html/photo_gallery/includes/photograph.php on line 2 You can see that LIB_PATH is not defined and even the .DS. is not working.. Here is a sample of the code I made : Code: [Select] <?php // Defining core paths // Defining them as absolute paths to make sure that require_once works as expected // DIRECTORY_SEPARATOR is a PHP pre-defined constant // (will do \ for Windows, / for Unix) defined('DS') ? null : define('DS', '/'); defined('SITE_ROOT') ? null : define('SITE_ROOT', 'http://www.lemontree-designs.com'.DS.'photo_gallery'); defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.'/includes'); defined('LOG_PATH') ? null : define('LOG_PATH', SITE_ROOT.DS.'logs'); defined('PUBLIC_AREA') ? null : define('PUBLIC_AREA', 'http://www.lemontree-designs.com'.DS.'photo_gallery'.DS.'public'); // Load config file first require_once(LIB_PATH."/config.php"); // Load basic functions next so that everything after can use them require_once(LIB_PATH.DS."functions.php"); // Load core objects require_once(LIB_PATH.DS."session.php"); require_once(LIB_PATH.DS."database.php"); require_once(LIB_PATH.DS."pagination.php"); // Load database-related classes require_once(LIB_PATH.DS."user.php"); require_once(LIB_PATH.DS."photograph.php"); require_once(LIB_PATH.DS."comment.php"); ?> Any help is appreciated! EDIT : For the sake of debugging, I've changed the defined value of DS to '/' instead of DIRECTORY_SEPARATOR to see if it's what caused an issue.. Code: [Select] <?php class constantTest { const HELLOWORLD = 'maybe not'; function __construct() { echo HELLOWORLD; // Output: HELLOWORLD echo constant('HELLOWORLD'); // Output: Warning: constant() [function.constant]: Couldn't find constant HELLOWORLD echo self::HELLOWORLD . "\n"; // Output: maybe not } } $bob = new constantTest(); I have read through the manual but as far as I can see all three methods should output the constant rather than just the last one. Question: Why? This is probs. an easy one but I have in my database some values, these values are defined constants in my php code. How do I display the value of the constant not the text (constant name)? Hey guys Anyone know the correct syntax to put a constant inside a header? this is driving me crazy with RPATH being my constant header("Location: ".RPATH."admin/monitor.php"); Can you echo class constants? This does not work for me. echo “here is a class constant: self::CLASS_CONSTANT”; // using double quotesInstead I *must* concatenate it: echo ‘here is a class constant: ‘ . self::CLASS_CONSTANT;But of course I do not have to do this with a normal variable, which will echo a variable fine: echo “my name is $name_variable”;Am I doing something wrong or is this normal behavior? Edited by E_Leeder, 30 October 2014 - 11:04 AM. I am following a book and need help setting up Path Constants. Here is the script I need to adjust... // Constants define('BASE_URI', '/path/to/Web/parent/folder/'); define('BASE_URL', 'www.example.com'); define('MYSQL', '/path/to/mysql.inc.php'); Since I am working in NetBeans, I do not have access above my Project Folder which serves as my "Web Root". So if my Project Folder is called "MyProjectFolder", and I want both BASE_URI and BASE_URL to point to that directory on my laptop, what should I put? I'm thinking something like this... // Constants define('BASE_URI', '/'); define('BASE_URL', '/'); define('MYSQL', '/includes/mysql.inc.php'); TomTees I have defined my database connection data as constants in a separate file for security reasons. How can I simply access the data stored in those constants. I have to call the file to get the value of the constants. If I inadvertently call the file twice in a script using an include or require statement, I get an error that I am trying to define the constants again. Can I somehow just call the constants without including the file where they are defined? --Kenoli What is the best practice for using site-wide constants in a class? E.g. COMPANY_NAME is set in a config file and used on many pages. How would it be best to use this in a class. I'm guessing just calling COMPANY_NAME anywhere in the class would not be considered best practice. Thanks. Well hello there, I want to create a script that writes a few PHP constants to a file called config.php. It does not work however, with the way I wrote it as below: Code: [Select] $configdata = "<?php //Configuration File \define("DBHOST", $dbhost); //DB Hostname \define("DBUSER", $dbuser); //DB Username \define("DBPASS", $dbpass); //DB Password \define("DBNAME", $dbname); //Your database name \define("DOMAIN", $domain); //Your domain name (No http, www or . ) \define("SCRIPTPATH", $scriptpath); //The folder you installed this script in \define("PREFIX", $prefix); ?>"; $file = fopen('../inc/config.php', 'w'); fwrite($file, $configdata); fclose($file); I am getting this error 'syntax error, unexpected T_STRING in ...', and I have no idea how to fix it. Strangely the below codes using PHP variables work flawlessly: Code: [Select] $configdata = "<?php //Configuration File \$dbhost = '{$dbhost}'; //DB Hostname \$dbuser = '{$dbuser}'; //DB User \$dbpass = '{$dbpass}'; //DB Password \$dbname = '{$dbname}'; //Your database name \$domain = '{$domain}'; //Your domain name (No http, www or . ) \$scriptpath = '{$scriptpath}'; //The folder you installed this script in \$prefix = '{$prefix}'; ?>"; //Write the config.php file... $file = fopen('../inc/config.php', 'w'); fwrite($file, $configdata); fclose($file); This confuses me, all I did was to change the string to output from a list of variables to a list of constants, and it gives weird errors that I have absolutely no idea how to fix. Can anyone please lemme know what I did wrong? Thanks. Dear All Members here is my table data.. (4 Columns/1row in mysql table)
id order_no order_date miles How to split(miles) single column into (state, miles) two columns and output like following 5 columns /4rows in mysql using php code.
(5 Columns in mysql table) id order_no order_date state miles 310 001 02-15-2020 MI 108.53 310 001 02-15-2020 Oh 194.57 310 001 02-15-2020 PA 182.22
310 001 02-15-2020 WA 238.57 ------------------my php code -----------
<?php
if(isset($_POST["add"]))
$miles = explode("\r\n", $_POST["miles"]);
$query = $dbh->prepare($sql);
$lastInsertId = $dbh->lastInsertId(); if($query->execute()) {
$sql = "update tis_invoice set flag='1' where order_no=:order_no"; $query->execute();
} ----------------- my form code ------------------
<?php -- Can any one help how to correct my code..present nothing inserted on table
Thank You Edited February 8, 2020 by karthicbabuHi, My company has 240+ locations and as such some users (general managers) cover multiple sites. When I run a query to pull user information, when the user has multiple sites to his or her name, its adds the second / third sites to the next columns, rather than wrapping it inside the same table cell. It also works the opposite way, if a piece of data is missing in the database and is blank, its pull the following columns in. Both cases mess up the table and formatting. I'm extremely new to any kind of programming and maybe this isn't the forum for this question but figured I'd give it a chance since I'm stuck. The HTML/PHP code is below: <table id="datatables-column-search-select-inputs" class="table table-striped" style="width:100%"> <thead> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th>Username</th> <th>Phone #</th> <th>Location</th> <th>Title</th> <th>Role</th> <th>Actions</th> </tr> </thead> <tbody> <?php //QUERY TO SELECT ALL USERS FROM DATABASE $query = "SELECT * FROM users"; $select_users = mysqli_query($connection,$query);
// SET VARIABLE TO ARRAY FROM QUERY while($row = mysqli_fetch_assoc($select_users)) { $user_id = $row['user_id']; $user_firstname = $row['user_firstname']; $user_lastname = $row['user_lastname']; $username = $row['username']; $user_phone = $row['user_phone']; $user_image = $row['user_image']; $user_title_id = $row['user_title_id']; $user_role_id = $row['user_role_id'];
// POPULATES DATA INTO THE TABLE echo "<tr>"; echo "<td>{$user_id}</td>"; echo "<td>{$user_firstname}</td>"; echo "<td>{$user_lastname}</td>"; echo "<td>{$username}</td>"; echo "<td>{$user_phone}</td>";
//PULL SITE STATUS BASED ON SITE STATUS ID $query = "SELECT * FROM sites WHERE site_manager_id = {$user_id} "; $select_site = mysqli_query($connection, $query); while($row = mysqli_fetch_assoc($select_site)) { $site_name = $row['site_name']; echo "<td>{$site_name}</td>"; } echo "<td>{$user_title_id}</td>"; echo "<td>{$user_role_id}</td>"; echo "<td class='table-action'> <a href='#'><i class='align-middle' data-feather='edit-2'></i></a> <a href='#'><i class='align-middle' data-feather='trash'></i></a> </td>"; //echo "<td><a href='users.php?source=edit_user&p_id={$user_id}'>Edit</a></td>"; echo "</tr>"; } ?>
<tr> <td>ID</td> <td>FirstName</td> <td>LastName</td> <td>Username</td> <td>Phone #</td> <td>Location</td> <td>Title</td> <td>Role</td> <td class="table-action"> <a href="#"><i class="align-middle" data-feather="edit-2"></i></a> <a href="#"><i class="align-middle" data-feather="trash"></i></a> </td> </tr> </tbody> <tfoot> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th>Username</th> <th>Phone #</th> <th>Location</th> <th>Title</th> <th>Role</th> </tr> </tfoot> </table>
Hi all, I'm a first time poster here and I would really appreciate some guidance with my latest php challenge! I've spent the entire day googling and reading and to be honest I think I'm really over my head and need the assistance of someone experienced to advise the best way to go! I have a multi dimensional array that looks like (see below); the array is created by CodeIgniter's database library (the rows returned from a select query) but I think this is a generic PHP question as opposed to having anything to do with CI because it related to working with arrays. I'm wondering how I might go about searching the array below for the key problem_id and a value equal to a variable which I would provide. Then, when it finds an array with a the matching key and variable, it outputs the other values in that part of the array too. For example, using the sample data below. How would you recommend that I search the array for all the arrays that have the key problem_id and the value 3 and then have it output the value of the key problem_update_date and the value of the key problem_update_text. Then keep searching to find the next occurrence? Thanks in advance, as above, I've been searching really hard for the answer and believe i'm over my head! Output of print_r($updates); CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id] => Resource id #35 [result_array] => Array ( ) [result_object] => Array ( ) [current_row] => 0 [num_rows] => 5 [row_data] => ) Output of print_r($updates->result_array()); Array ( [0] => Array ( [problem_update_id] => 1 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Some details about a paricular issue [problem_update_active] => 1 ) [1] => Array ( [problem_update_id] => 4 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Another update about the problem with an ID of 3 [problem_update_active] => 1 ) [2] => Array ( [problem_update_id] => 5 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of four [problem_update_active] => 1 ) [3] => Array ( [problem_update_id] => 6 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of 6 [problem_update_active] => 1 ) [4] => Array ( [problem_update_id] => 7 [problem_id] => 3 [problem_update_date] => 2010-10-12 [problem_update_text] => Some new update about the problem with the ID of 3 [problem_update_active] => 1 ) ) |