PHP - Method Doesn't Return An Array, It Returns Nothing.
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? Similar TutorialsWhy 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 ?> Hi all, Why when i set my method to returns by reference its giving me a notice that only variables should return by reference while where is not set to return by reference it don't. Fro example: interface i { function &m(); } class a implements i { public function &m() { return $v; } } $v = new a(); $v->m(); So i just return empty $v. Is this a good practice or should i just ignore the notice First time post, be easy on me...
I'm using preg_match_all to return an array with all the matches. I know I'm missing something fundamental, but I either keep looking past it or am more screwy than I know.
Sample String
CC-BY-ND-NCI'm using the following code preg_match_all("/cc|creative commons|copyright|by|sa|nc|nd/i",$exifmeta['copyright'],$cmeta)I would expect to see Array ( [0] => Array ( [0] => CC [1] => BY [2] => ND [3] => NC ) )What I get is Array ( [0] => Array ( [0] => CC [1] => BY [2] => ND [3] => NC [4] => sa ) ) 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 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. 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
Hello, My current server setup :
PHP version: 7.1.4
From what I read, in order to have MySQL return native datatypes (as opposed to just strings) : Now, I do have mysqlnd, but a simple PDO Prepared statement still returns me all strings, even though some columns are set as INT, VARCHAR, DATETIME, etc.. $stmt = $pdo->prepare("SELECT * FROM tbl_users WHERE id=1"); $stmt->execute(); $user = $stmt->fetch(); var_dump($user); OUTPUT: array(13) { ["id"]=> string(1) "1" ["is_admin"]=> string(1) "1" ["is_active"]=> string(1) "1" ["username"]=> string(5) "jdoe" ... }
I'm not sure what to look for to resolve this issue if I want it to return INT as INT and not STRING, etc. Does having `extension_loaded('mysqlnd') == true`, make my system automatically use this native mysql driver? How can I tell ? Could this be a version problem perhaps?
Much thanks! Pat
I created a function called converter. My code doesn't look like it processes anything after the first if . This is what is displayed in browser. Convert a String original string: roses Are red, violets are blue.... converted string: roses are red, violets are blue.... converted string: roses are red, violets are blue.... converted string: roses are red, violets are blue.... <html> <head> <title>Create a PHP Function to Convert a String</title> </head> <body bgcolor="pink"> <h2>Convert a String</h2> <?php $phrase = "roses Are red, violets are blue...."; function converter($arg1, $arg2){ if($arg1="lower"){ return strtolower($arg2); } elseif ($arg1="upper"){ return strtoupper($arg2); } else /* if($arg1="title")*/{ return ucwords($arg2); } } print "original string: ".$phrase."<br />"; print "converted string: ".converter("upper",$phrase)."<br />"; print "converted string: ".converter("lower",$phrase)."<br />"; print "converted string: ".converter("title",$phrase)."<br />"; ?> </body> </html> friends if an array returns results as Array() how could i set an error message to it? i tried to do a if statement to the $variable but not working In the following code: echo $text[2] returns the word at that index but echo $key returns a blank. Can someone explain why is array-search not working in this indexed array? It does work when I test it with a key => value type array. <?php $myfile = fopen("test.txt", "r") or die("Unable to open file!"); while(!feof($myfile)) { $text[] = fgets($myfile); } fclose($myfile); $word = $_POST['word']; $key = array_search($word, $text); echo $key ?> Hey guys tried to search for this but didn't find anything usefull about the issue. So what i have is mssql_fetch_array in a while loop in the loop i have it assign a specified row as a variable that i can print later on in the page. Code: [Select] while($row = mssql_fetch_array($query) { $tables = "<tr>"; $tables .= "<td> {$row['specifiedrow']} </td>"; $tables .= "</tr>"; }Then i call it in the html table as Code: [Select] <? php echo $tables; ?> I have done this with mysql_fetch_array before and it would print the entire database row associated with that row in the table. But as it is now it only returns the last row from the database. Is there something i am missing. Thanks for any help in my code below the **data is extracted correctly for the first foreach but doesn't return anything for 2nd foreach though selected one present inside the 2nd foreach** i still get the error Warning: Invalid argument supplied for foreach() for line `foreach ($authorlist as $post)`... however the 2nd foreach returns data correctly as soon as i remove the first foreach loop. In my code I call PEAR::isError to see if there was an error in the SQL Query so I can log it but its always returning this error. Does anyone know a fix? I have tried to search google it and found http://pear.php.net/bugs/bug.php?id=9950 but it does not say how to fix it. Does anyone have any ideas? Error Non-static method PEAR::isError() should not be called statically $query = "SELECT Column FROM TableName"; $res = $db['database']->query($query); if (PEAR::isError($res)) { $logger->err("Error pulling results from DB. Query:" . $query); } Hi everyone for my end of studies projects I decided to do a little e-commerce problem on the filter .. I use an ajax request at the click of the checkbox this goes to my controller which calls a method of my Model class but the concern is that .. if the array $ _POST ['brands'] has several elements then only the last one is returned to me? I thought I saw one day that if the same variable is in a url then the last value will be returned to me is for security but how can I do ... I have been there for too long .. and finally despair. . Help me please... :') request payload: brands%5B%5D=arai&brands%5B%5D=bell reply :
<- prepare var_dump ()
string (4) "arai" <- bind
var_dump () of my fetchAll () since the last value taken into account is bell then I get two items of the bell brand from my bdd but no arai ... Edited October 24, 2020 by jcb789error Hi, I'm trying to implement multithreading using Threadi https://github.com/danielpoe/Threadi Here is a sample code to what I'm trying to do: Code: [Select] require_once(dirname(__FILE__).'/../Loader.php'); class Worker { public function fetchAWebsite($url) { $content = file_get_contents($url); return "fetched website $url - lenght ".strlen($content).PHP_EOL; } } $worker = new Worker(); $startTime = microtime(TRUE); $thread1 = Threadi_ThreadFactory::getReturnableThread(array($worker,'fetchAWebsite')); $thread1->start('http://www.google.de'); $thread2 = Threadi_ThreadFactory::getReturnableThread(array($worker,'fetchAWebsite')); $thread2->start('http://www.aoemedia.de'); $joinPoint = new Threadi_JoinPoint($thread1, $thread2); $joinPoint->waitTillReady(); echo $thread1->getResult(); echo $thread2->getResult(); echo "Time needed in seconds: ". ( microtime(TRUE)-$startTime).PHP_EOL; The problem that I'm having is that I need to call each thread separately by name. Creating 10 or more threads makes a lot redundant code. How can I assign Threadi_ThreadFactory::getReturnableThread to an indexed variable(array) ? I tried something in this lines but with no success: Code: [Select] $hArr = array();//handle array for ($i=0;$i<THREADS;$i++) { $thread[$i] = Threadi_ThreadFactory::getReturnableThread(array($worker,'fetchAWebsite')); $thread[$i]->start($site[$i]); array_push($hArr,$thread[$i]-); } $joinPoint = new Threadi_JoinPoint($hArr); $joinPoint->waitTillReady(); What I'm doing wrong? Thanks Hi,Dear Frnds...........................I Hope U r all fine. I am using php.Here is the problem in the Return array from function. This is the code. Code: [Select] <?php $store = array(); $test = get_my_links(); print_r($store); function get_my_links() { $my_array = array('e','f','g'); foreach($my_array as $key=> $list) { $store[] = $list; } return $store; } ?> Suppose the array is maked dynamically. please help me..THANKS... phpfreaks I am querying a database using pdo but I keep getting an array that returns two results. As you can see from the array below it returns the id and result and then repeats the result . I only want the keys with text to be returned. Any help would be great. Code: [Select] ( [0] => Array ( [Ticket_ID] => 2 [0] => 2 [Customer_id] => 1 [1] => 1 [Business_Name] => [2] => my database method is Code: [Select] private function queryFetchAllPDO($query) { try { $this->dataObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sth = $this->dataObj->prepare($query); $sth->execute(); echo"I am here"; $result = $sth->fetchAll(); print_r($result); // $stmt = $this->dataObj->query($query); // $stmt->setFetchMode(); // $result = $stmt->fetchAll(); } catch (PDOException $e) { $e->getMessage(); } return $result; } and the query method is Code: [Select] private function clieViewHome() { //find user id $sql = "SELECT Customer_id FROM customer WHERE Username='" . $this->user . "'"; $sessAccess = $this->connection->getQueryFetchPDO($sql); foreach ($sessAccess as $value) { $userID = $value; } //place into query $sql = "SELECT * FROM tickets WHERE Customer_id ='" . $userID . "'"; $tableArr = $this->connection->getQueryFetchAllPDO($sql); print_r($tableArr); foreach ($tableArr as $key => $value) { $return .= "<tr>\n"; foreach ($tableArr[$key] as $value2) { $return .="<td>" . $value2 . "</td>\n"; } $return .= "</tr>\n"; } return $return; } hello. im trying to get some results from a db and all i keep getting is the word ARRAY ?? I want to get all the placeholders that relate to a page. so if pageID=1 has place holder 1, place holder 2 and place holder 3 it will return 1, 2, 3 etc... in the db i have id pageID phNumber 1 1 1 2 1 2 3 1 3 etc.. this is the code i have Code: [Select] public function find_placeholders($pageID=0){ $sql = "SELECT phNumber FROM ".self::$table_name." WHERE pages_id=".$pageID.""; $result_array = self::find_by_sql($sql); return $result_array; } and on the page i have.. Code: [Select] <?php echo Placeholders::find_placeholders($pageID); ?> all i get is Quote Array once i solve this problem i will want to use each number in the array to find the content for each. so if i get 1,2,3 i will try and do some thing like. foreach placeholder number echo elements but 1 step at a time thanks for any help rick Hello. I'm new to php and need a little help please. I try to build a class that return an Array of all the table in my db. and be able to get all the data by there col name (like username, password....) but all i got is the last record from the db. here is the class: <?php class db{ function getall($table, $search){ $sql = "SELECT ". $search ." FROM " . $table; $result = mysql_query($sql) or die('Error, insert query failed' . mysql_error()); while($row=mysql_fetch_assoc($result)){ $data = $row; } return $data; } and this is in the html page: $data = $db->getall("users", "*"); foreach($data as $row){ echo $row['fullname']; echo "<BR>"; } can anybody help me with that? |