PHP - Alternatives To 'return' Method (so I Don't Print Result)
I am trying to do the following. Except I know that 'return' is not the right method to use, as it stops the script, so what ends up happening is only one row is returned, instead of the three that are there. With return, the data is being passed without being immediately printed, and I end up with the data (but not all of it, because the script stops) in correct place in the page.
If I replace return () with echo(), it works fine, in terms of returning the correct data. However, with the way things are setup, if I use echo, the results print at the head of my page. I am using function CreateSideMenu to establish the values for content, and then another function, later on the index.php page, actually creates the page. So what I need is to have something, similar to return (), that passes the information on, but does not immediately print it. Do I make sense? see code below: function CreateSideMenu () { // open CreateSideMenu function include ('/Users/max/Sites/rdbase-llc/hidden/defin/kinnect01.php'); $query = "SELECT content_element_title, content_element_short_text FROM content_main"; $result = mysql_query ($query, $dbc); while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) { return ("<p>" . $row[content_element_title] . "</h2>\n<p>" . $row[content_element_short_text] . "</p>"); } Thanks ahead of time. Similar TutorialsNow i use a very complex normal for, how i can use a foreach? Hi I have a problem with the following: Code: [Select] <?php class ClassA { public $propertyClassName = "ClassB"; public function methodClassName() { return "ClassB"; } } class ClassB { public function bmethod() { echo "great!"; } } //works $a = new ClassA(); $b = new $a->propertyClassName(); $b->bmethod(); //doesn't work $a = new ClassA(); $b = new $a->methodClassName(); $b->bmethod(); ?> Of course I could do Code: [Select] <?php $a = new ClassA(); $className = $a->methodClassName(); $b = new $className; $b->bmethod(); ?>but isn't there a way to do this without saving the method's return to a variable? Thanks in advance flolam Any thoughts as to why I'm getting an error for this line of code? Code: [Select] if (isset($this->input->post('bcc[]'))) Error reads: Fatal error: Can't use method return value in write context If someone knows can they explain it to me so I understand it please. I am using this code to search my database plus it has a paginate which all works fine. The problem is i have a row count which for some reason counts all records in the database and not just the ones returned from the search query. How to i fix this. Code: [Select] $term = $_GET['term']; $cat = $_GET['cat']; //max display per page $per_page = 4; //get start variable $start = $_GET['start']; // cout records $record_count = mysql_num_rows(mysql_query("SELECT * FROM Table WHERE productname like '%$term%' and category like '%$cat%'")); //count max pages $max_pages = $record_count / $per_page; //may count as decimal if (!$start) $start =0; $sql="SELECT * FROM table WHERE productname like '%$term%' and category like '%$cat%' LIMIT $start, $per_page"; $result = mysql_query($sql); $sql = mysql_query ("SELECT COUNT(*) FROM table"); list($number) = mysql_fetch_row($sql); if (!mysql_num_rows($result)) { die("NO RECORD FOUND") ; exit; } else { echo "Your Search for: <b>$term</b> in <b>$cat</b><br><br>"; } while ($row = mysql_fetch_array($result)){ $num_rows = mysql_num_rows($number); if (!$i++) echo "Total records $number"; ?> <br /> <br /> <?php echo 'ID: '.$row['id']; ?> <br /> <?php echo '<br/> Product Name: '.$row['productname'];?> <br /> <?php echo '<br/> Price: '.$row['price']; ?><br /> <?php echo '<br/> category: '.$row['category']; ?> <br /> <?php } ?> <?php //setup prev and next variables $prev = $start - $per_page; $next = $start + $per_page; // show prev button if(!($start<=0)) echo " <a href='ttr.php?start=$prev'>Prev </a>"; //set var for first page $i=1; for ($x=0;$x<$record_count;$x=$x+$per_page) { if ($start!=$x) echo "<a href='ttr.php?start=$x'>$i</a> "; else echo "<a href='ttr.php?start=$x'><b>$i</b></a> "; $i++; } //show next button if (!($start>=$record_count-$per_page)) echo " <a href='ttr.php?start=$next'>Next</a>"; ?> I've done pretty much everything I can come up with. The method itself works fine, if I print_r(); just before returning it, it successfully returns the array. But once returned, it's empty. Heres my code: Code: [Select] <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_database.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php"; ?> <?php class User { private $database; public function __construct(MySqlDatabase $database) { //Type Hinting $this->database = $database; } public function hash_password($password) { $result = hash(sha512, $password . SUOLA); return $result; } public function find_all() { $result = $this->database->db_query("SELECT * FROM users"); $final = mysqli_fetch_array($result); return $final; } public function find_by_id($id=1) { $result = $this->database->db_query("SELECT * FROM users WHERE id={$id}"); $final = mysqli_fetch_array($result); return $final; } public function check_required($array) { // this method gets called first if (empty($array['username']) || empty($array['first_name']) || empty($array['last_name']) || empty($array['password']) || empty($array['email']) || empty($array['secret_question']) || empty($array['password2']) || empty($array['secret_answer']) || !($array['email'] === $array['email2']) || !($array['password'] === $array['password2'])) { die("Fill required fields!" . "<br />" . "<a href='javascript:history.go(-1)'>Go back</a>"); } else { $this->database->array_query_prep($array); // it then continues to the next method automatically } } public function create_user($array) { $date = date('d-m-Y H:i:s'); $sql = "INSERT INTO users (username, first_name, "; $sql .= "last_name, password, email, secret_question, "; $sql .= "secret_answer, create_time) VALUES "; $sql .= "('{$array['username']}', '{$array['first_name']}', '{$array['last_name']}', "; $sql .= "'{$array['password']}', '{$array['email']}', '{$array['secret_question']}', '{$array['secret_answer']}', "; $sql .= "'{$date}');"; $this->database->db_query($sql); } } ?> Code: [Select] <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_user.php"; ?> <?php class MySqlDatabase extends MySQLi { function __construct() { //Check if constants are missing if (!defined("DB_USERNAME") || !defined("DB_SERVER") || !defined("DB_PASSWORD") || !defined("DB_NAME")) { die("One or more of the database constants are missing!"); } //Establish connection if constants are present using the parent class parent::__construct(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); //Echo error message if connection has failed if ($this->connect_errno) { die("Database connection has failed: " . $this->connect_errno); } } public function db_query($sql) { $result = $this->query($sql); if (!$result) { die("Database query failed: " . $this->errno); } } public function array_query_prep($array) { // continues to this method $result = array_map(array($this, 'real_escape_string'), $array); if (!$result) { die("Preparing query failed: " . $this->errno); } // if i print_r here, it returns the array as it should return $result; } } ?> Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" type="text/css" href="../stylesheets/main.css"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body class="main_body"> <div id="container"> <div id="header"> <div id="top"> <div id="login"> <form action="" method="post" target="/login/"> <label for="username">Username:</label><br /> <input name="username" type="text" class="text" maxlength="20" /><br /> <label for="password">Password:</label><br /> <input name="password" type="password" class="text" maxlength="30" /><br /> <input name="submit" type="submit" class="loginbtn" value="Login" /></form> </div> </div> <div> <h1>Welcome to _________ website!</h1> </div> <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/functions.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_database.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_user.php"; ?> <?php $database = new MySqlDatabase(); $user = new User($database); if (isset($_POST['submit'])) { $result = $user->check_required($_POST); //this is where I get nothing back $user->create_user($result); die("Registration was successful!"); } else { $username = ""; $first_name = ""; $last_name = ""; $password = ""; $email = ""; $email2 = ""; $secret_question = ""; $secret_answer = ""; unset($_POST); } ?> <form action="" method="post" target="_self"> Username: <input type="text" name="username" class="text" maxlength="20" value="<?php echo htmlentities($username); ?>" /><br /> First Name: <input type="text" name="first_name" class="text" maxlength="20" value="<?php echo htmlentities($first_name); ?>" /><br /> Last Name: <input type="text" name="last_name" class="text" maxlength="20" value="<?php echo htmlentities($last_name); ?>" /><br /> Password: <input type="password" name="password" class="text" maxlength="30" value="<?php echo htmlentities($password); ?>" /><br /> Enter again: Password: <input type="password" name="password2" class="text" maxlength="30" value="<?php echo htmlentities($password2); ?>" /><br /> Email: <input type="text" name="email" class="text" maxlength="30" value="<?php echo htmlentities($email); ?>" /><br /> Enter again: Email: <input type="text" name="email2" class="text" maxlength="30" value="<?php echo htmlentities($email2); ?>" /><br /> Secret Question: <input type="text" name="secret_question" class="text" maxlength="35" value="<?php echo htmlentities($secret_question); ?>" /><br /> Secret Answer: <input type="text" name="secret_answer" class="text" maxlength="35" value="<?php echo htmlentities($secret_answer); ?>" /><br /> <input type="submit" name="submit" class="submitbtn" value="Submit" /> <?php ?> </div> </div> </body> </html> [/quote] Any ideas? I have a class ServerBridge which is used to proxy browser ajax requests received by a web server to another API server. To update a record (or create a record is similar): Browser client makes PUT request to web server. Web server modifies the uri path and passes the body plus headers connection, accept, accept-encoding, accept-language, content-type, content-length only to the API server. The API server does work and returns the location of the resource on itself to the web server. The web server modifies the location header to point to the resource location on itself, and returns all received headers except Date, Server, X-Powered-By, Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers to the browser client. Browser client makes another undesired PUT request to web server.Why is step 5 occurring and how do I prevent it? I don't really mind the browser client making another request to the resource, but it would need to be GET and not PUT. Also, is my white-list headers to forward to api server and black-list headers to return to browser client appropriate? I haven't posted the ServerBridge script (but can if needed), but did include the requests and headers related to the browser client, web server, and api server below. Browser client JavaScript $('.edit-record').simpleEdit('/api/accounts'); jQuery.fn.extend({ simpleEdit: function(url, options) { var dOptions={type: 'text', ajaxOptions: {type: "PUT"}, placement: 'right', send: 'always' }; options=options?options:{}; return this.each(function() { var $t=$(this); var o=Object.assign({ url: url+'/'+$t.closest('tr').data('id'), title: 'Enter '+$t.data('name') }, dOptions, options); $t.editable(o); }); } }); Web-server index.php $c['serverBridge'] = function ($c) { return new \Greenbean\ServerBridge\ServerBridge( new \GuzzleHttp\Client([ 'base_uri' => $c['settings']['server']['scheme'].'://'.$c['settings']['server']['host'], 'headers' => ['X-Secret-Key' => $c['settings']['server']['key']], 'timeout' => 30, 'allow_redirects' => false, ]), new \Greenbean\ServerBridge\SlimHttpClientHandler() ); }; $app->put('/api/accounts/{id:[0-9]+}', function (Request $request, Response $response) { return $this->serverBridge->proxy($request, $response, function(string $path):string{ return substr($path, 4); //Remove "/api" from uri }, function(array $headers):array{ if(!empty($headers['Location'])) { $headers['Location'] = ['/api'.$headers['Location'][0]]; //Add "/api" to redirect header if it exists } return $headers; } ); }); $app->POST('/api/accounts/{id:[0-9]+}', function (Request $request, Response $response) {/*Similar to PUT*/});
<?php class ServerBridge { public function __construct(\GuzzleHttp\Client $httpClient, ?HttpClientHandlerInterface $httpClientHandler=null){ $this->httpClient=$httpClient; $this->httpClientHandler=$httpClientHandler; //Whether to use Slim or Sympony HTTP requests and responses } public function proxy($clientRequest, $clientResponse=null, \Closure $modifyPath=null, \Closure $modifyHeaders=null) { //Accept a Slim or Sympony HTTP request, forward it to API server via cURL, and return the cURL response //$modifyPath will modify REQUEST_URI before sending to API server //$modifyHeaders will modify response headers before sending to calling client return $response; } } API Server index.php $app->put('/accounts/{id:[0-9]+}', function (Request $request, Response $response, $args) { $this->accounts->update($args['id'], $request->getParsedBody()); return $response->withRedirect('/accounts/'.$args['id'], 302); }); $app->post('/accounts', function (Request $request, Response $response) { $account = $this->accounts->create($request->getParsedBody()); return $response->withRedirect('/accounts/'.$account['id'], 302); });
Web Server
Why does this return null rather than 'john must write the book'? Code: [Select] <? abstract class User { protected $name; protected $role; function __construct($name,$role){ $this->name = $name; $this->role = $role; } abstract function run_errand(); } class Author extends User { public function run_errand(){ echo $this->name . "must write the book"; } } class Editor extends User { public function run_errand(){ echo $this->name . "must edit the book"; } } class Boss { private $users = array(); public function review(User $user){ $this->user[] = $user; } public function delegate(){ if(count($this->users)){ foreach($this->users as $user){ if($user->role == "author"){ echo $user->run_errand(); } } } } } //client code $boss = new Boss(); $boss->review(new Author('John','author')); var_dump($boss->delegate()); //returns null ?> I have found postings close, but not close enough to find my error. I am looking up data from a MySql table and putting it in a dropdown box on a form. I can select the item, but apparently not really. I am not able to echo it, or post it to a record. I'm sure I am missing something simple, but... Code attached if anyone can show me the errors of my ways. Thank you. Say a script has ignore_user_abort(true); set. If the user aborts the connection and print is called, the buffer doesn't get written anywhere. So shouldn't print() return false in this case? To clarify, I know it doesn't, but shouldn't it? If not, why not? Hello, I am fairly new to PHP and I found some php code to print an array of numbers that create a combination - however, its slams all the numbers together without a space or a comma separator. How can I separate the numbers in this array with the given code? Ive attached a photo of the code.
My script has 3 classes (that are relevant to this discussion): DB, User and Validate. They are all in independent files and loaded automatically, when required, by an autoloader.
The error messages I am getting a Any pointers as to what I am doing wrong, or what I should be doing, would be most welcome. I created had created a website between me and a couple friends. On the website I made an Ajax\Javascript\Php Instant Messenger. It works fine for something small. Each user has a contact list and currently I am saving each individual conversation between each user into an Sql table { senderId, RecieverId, Message } and reading it back. Now I know its no problem for something small but obviously it leaves security risks and sends too many requests to the server. Any of you guys have any alternative Idea's for this messenger? I don't necessary need to save the conversations, I'm simply using that method to send and receive them. I have a buddy who does his messenger through J.S sockets but I would like to keep to php if possible. Any comments or suggestions would be much appreciated. Uploaded with ImageShack.us I'm wondering if there's any alternatives to redirecting. For example, after the registration process, I have a fully loaded User object with all of the information I need to load the user's profile (the place that logging in/registering takes you to). I can call the profile action of the user controller and pass in the User object and it will display just fine. The problem is that since the URL is still pointing to the register action if the user refreshes their page its going to try sending the previous form again. Alternatively I could redirect to the profile and have it load that way, but then I'm fetching data from the database seemingly unnecessarily since I had all of the data I needed already fetched prior to redirecting. Is there anyway that I could do the first process but change the url and forget the previous form data so that if they refresh its just refreshing the profile and not resending the previous request? Thanks in advance for any help. Sometimes I have various data which I wish to be available to all scripts. Typically, they are constants which are related, and using PHP's constants makes them difficult to group.
As such, my solution has been to create a single global variable such as $GLOBALS['myGlobalVariable'], and dump them all in it.
Are there better ways to implement this? For instance, using a singleton? Please provide rational why one solution is better than the other.
Thank you
<?php class mySinglton { private static $instance = NULL; private function __construct() {} private function __clone(){} public static function mySinglton($values=null) { if (!self::$instance) { self::$instance = new stdClass(); foreach ($values as $key=>$value) { self::$instance->$key=$value; } } return self::$instance; } } class someClass { public $a=1,$b=2,$c=3; } $globals=array( 'foo'=>'bar', 'daysOfWeek'=>array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'), 'someClass'=>new someClass ); $GLOBALS['myGlobalVariable']=$globals; mySinglton::mySinglton($globals); testIt(); function testIt() { echo('<pre>'.print_r($GLOBALS['myGlobalVariable'],1).'</pre>'); echo('<pre>'.print_r($GLOBALS['myGlobalVariable']['foo'],1).'</pre>'); echo('<pre>'.print_r(mySinglton::mySinglton(),1).'</pre>'); echo('<pre>'.print_r(mySinglton::mySinglton()->foo,1).'</pre>'); } ?> I am really lost here with this date issue of mine. The below code is the last part of a query: Code: [Select] $defendercheck_3 = $row_checkifattacked3['atdate']; $defendercheck1_3 = strtotime("$defendercheck_3"); $defendercheck2_3 = date("D", $defendercheck1_3); The query does not return any results as expected, but when echoing the various steps I get following: echo "$defendercheck3"; = nothing (as expected) echo "$defendercheck1_3"; = nothing (as expected) echo "$defendercheck2_3"; = result! (NOT expected) why does it return anything on "date("D", $defendercheck1_3)" when "$defendercheck1_3" is blank? If I want to load some user information from the database into an object/array and share it throughout my application, what's the best approach for this? Here is what I thought of doing: - I can call a function (e.g user_info() ) that will return the user information whenever I need it , but It'll have to run a DB query each time I call it. - Load user information once from the DB, assign it into a global array/object, then call that object whenever I need it. A lot of people recommended against using global variables, but I think performance wise it's better than running a query each time. Are there any better alternatives than the above approaches? I am using API-Platform, Doctrine, and Symfony with entities that utilize class type inheritance to extend an abstract entity. I've been running into one issue after another primarily related to the serialization process (serialization groups, parent annotations not propagated to the child, etc), and while I am sure user error on my part is part of the culprit, it appears that API-Platform and potentially Symfony and Doctrine don't fully support entity inheritance. My reason for thinking so is the incredibly sparse amount of documentation on the subject and remarks on quite a few github issues posts and other blogs how it is "bad practice". For instance, say I have Mouse, Cat, and Dog which all extend AbstractAnimal, and each has a bunch of common properties such as birthday, weight, etc, and methods such as eats(), sleeps(), etc. Sorry in advance for using hypothetical entities but I don't think doing so distracts. I like how inheritance allows me to keep all common properties in a single table, but can let that go. More importantly, the subset mouse, cat, and dog table shares an ID from the animal table allowing me to associate all animals to some other table (i.e. many-to-one to person whether they are their pet or many-to-many to country whether they are native to a country), and to retrieve a list of animals and filter by some property or type as needed without a bunch of unions. To me, this sounds like inheritance, but if the products I am using don't support it very well, it doesn't matter. First question. Is entity inheritance considered bad practice? And even if not, is it common for frameworks to limit their level of support for them? If so, what can I do about it? Maybe favor composition over inheritance? Okay, great, I now have a single animal table which makes all my SQL concerns issues go away and I am pretty confident that my serialization issues will also go away. All I need to do is inject each animal with some "thing" to make them a mouse, cat, or dog. But what do I call this thing? I've struggled with this topic for a while and asked the same question regarding how to deal with BarCharts, PieCharts, GaugeCharts, LineCharts, etc all being charts but all acting slightly differently, and never really came to any conclusion. For a non-hypothetical scenario, I have BacnetGateway and ModbusGateway which extend AbstractGateway. Okay, this one is easy and I change to just having a Gateway and inject either BacnetProtocol or ModbusProtocol. For another non-hypothetical scenario, I have PhysicalPoint which represents some real environmental parameter, VirtualPoint which represents combining one or more PhysicalPoints or VirtualPoints, and TransformedPoint (feel free to provide a better name) which represents performing some time function such as integrating over a given time. Currently, they all extend AbstractPoint, but if I was trying to do so with composition, I could inject PointType but don't think doing so makes sense. For my hypothetical scenario, do I make a DNA interface and inject an Animal with DogDNA to get a dog? I really need to get my head around this once and for all. Thanks Hello again, So, after messing around with gettext, and having found the solution to my previous post (https://forums.phpfreaks.com/topic/310383-gettext-for-multilangual-not-working-for-me/), I've come to the conclusion that I need to use something else than gettext in order to make my site multilingual.
Problem I have with gettext is that I absolutely need to have my desired languages (i.e. fr_FR, nl_NL, etc) installed on my server's system (in my case, a NAS for now). I can see which locales I have on my server with 'locale -a'. I am in no way able to install new locales on my NAS. It's too limited... too much locked down. So, I'm looking for an alternative to gettext. Any suggestions for me perhaps ? Thanks for any advice. Pat
This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=326703.0 here is what i am trying to do. i have a url in my browser like this: http://localhost/jmla/index.php?option=com_content&view=article&id=1295:sovereign-a-country-risk-workshop as usuall we get elements form the url using the $_GET method, but here when i try to get id from the above url. i can get 1295:sovereign-a-country-risk-workshop. whereas the id is only 1295 and the other part is alias which i want to get seperately. is there a way to do so? |