PHP: Function to iterate results from another function and output - php

Seems like this would be pretty simple, however, I'm running into an issue:
Here's the code:
function getValidCustomers() {
global $db;
$getCustomers = $db->GetAll("SELECT * from customers where CustomerActive='1' AND protected IS NULL or protected=0;");
foreach($getCustomers as $customer) {
echo $customer['CustomerID']."\n";
}
}
function updateValidCustomers() {
$customers = getValidCustomers();
for ($i = 0; $i < sizeof($customers); $i++) {
echo "DEBUG: $customers[$i]\n";
}
}
updateValidCustomers();
Basically, the output right now is a list of the CustomerIDs (from updateValidCustomers()). I just want updateValidCustomers() to get the data from getValidCustomers() and then loop through it, so that I can run another query on it that will actually manipulate the database.
Any ideas?

getValidCustomers doesn't return anything, maybe you mean this:
function getValidCustomers() {
global $db;
$getCustomers = $db->GetAll("SELECT * from customers where CustomerActive='1' AND protected IS NULL or protected=0;");
foreach($getCustomers as $customer) {
echo $customer['CustomerID']."\n";
}
return $getCustomers;
}

getValidCustomers() doesn't return anything - it just echoes
Add return $getCustomers to the end of getValidCustomers()

Add return $getCustomers; to getValidCustomers() :D

Related

Efficient way to reuse the same call to the same sql table

So I search for this title hoping someone would have already answered it however, I came across similar topics on other languages but not PHP so maybe this will help others.
I am constantly using this following script to call on the database but how can I create it so that I can make it just once at the top of the class for example and use it in every method on the class page that needs it. Example: An single page may not have all of the data it needs from the same table but if the table contains 50% of the data or more for that page, how can I modify this so that I can just say it once and let the rest of the following scripts display the data it extracted in the first place by calling it all just once?
Here's what I have now.
<?php
if($res = $dbConn->query("SELECT Column FROM Table")){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
?>
I want to call on this without the printf(" "); collect and store the data so that I can then call the results while printing or echoing the results with the HTML in other methods. What os the most efficient way? I don't want to make the same call over and over and over... well, you get the point.
Should I use fetch_array or can I still do it with fetch_assoc?
not very sure if it's the answer you want.
you can use include/include_once/require/require_once at the top of the page you want to use the function
for example:
general_function.php:
-----
function generate_form( $dbConn, $sql ) {
if($res = $dbConn->query("SELECT Column FROM Table")) {
while($d = $res->fetch_assoc()) {
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}
and for those pages you want to use the function, just put
include "$PATH/general_function.php";
and call generate_form
Try this:
class QueryStorage {
public static $dbConn = null;
public static $results = [];
public static function setConnection($dbConn) {
self::$dbConn = $dbConn;
}
public static function query($query, $cache = true) {
$result = (array_key_exists($query, self::$results))?
self::$results[$query] : self::$dbConn->query($query);
if($cache) {
self::$results[$query] = $result;
}
return $result;
}
public static function delete($query) {
unset(self::$results[$query]);
}
public function clean() {
self::$results = [];
}
}
usage:
at top somewhere pass connection to class:
QueryStorage::setConnection($dbConn);
query and store it:
$result = QueryStorage::query("SELECT Column FROM Table", true);
if($result){
while($d = $result->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
reuse it everywhere:
$result = QueryStorage::query("SELECT Column FROM Table", true); // it will return same result without querying db second time
Remember: it's runtime cache and will not store result for second script run. for this purposes You can modify current class to make it
work with memcache, redis, apc and etc.
If I understood you correctly, then the trick is to make an associative array and access with its 'key' down the code.
$dataArray = array();
// Add extra column in select query for maintaining uniqness. 'id' or it can be any unique value like username.
if($res = $dbConn->query("SELECT Column,id FROM Table")){
while($d = $res->fetch_assoc()){
$dataArray[$d['id']] = $d['Column'];
}
}
//you have value in the array use like this:
echo $dataArray['requireValueId'];
//or , use 'for-loop' if you want to echo all the values
You need a function which takes in the query as a parameter and returns the result.
Like this:
public function generate_query($sql) {
if($res = $dbConn->query($sql)){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}

How do I share same variable between independent functions

How do I share same variable between independent functions? I don't want to use globals and at the moment, I'm not using OO. This example only works within nested functions:
$example = function() use ($id){
echo 'id is: ' . $id;
};
Is there a way to access (read: to call) that nested function from a different function? I could then return $id.
Main issue: I'm retrieving an ID from a database and I want the moderator to be able to edit material based on the ID that is being retrieved from the database.
As mentioned in my comment , I'm not 100% what exactly you mean by independent and nested function but here is PHP's manual on (anonymous function)[http://php.net/manual/en/functions.anonymous.php].
Anyway I have put a sample together assuming you are really meaning nested functions
<?php
function wrapperOne($id) {
$newId = function($id) {
return $id * 2;
};
return $newId($id);
}
function wrapperTwo($id) {
$doSomething = function() use(&$id) {
$id *= 3;
};
$doSomething();
return $id;
}
echo wrapperOne(2); // 4;
echo PHP_EOL;
echo wrapperTwo(2); // 6;
You can use passing by reference read this
function changeMyID(&$id)
{
$id = 1;
}
function printMyID($id)
{
echo $id;
}
$id = 2;
changeMyID($id);
printMyID($id); // this will output 1;

How to search for multiple values in a single field of mysql table using codeigniter active record?

I have to search for multiple values in a field using mysql in codeigniter. Here follows my code.
In Controller
public function vpsearch()
{
$data['info'] = $this->psearch_m->emp_search_form();
$this->load->view("employer/result",$data);
}
IN Model
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
$jrole = $this->input->post('ps_jobrole'));
if ( $jrole !== NULL)
{
return $this->db->get('js_edu_details');
$this->db->like('js_skills','$skill');
}
}
In view i.e, (../employer/result)
foreach($info->result() as $row)
{
echo $row->js_id."<br/><br/>" ;
}
However I am getting all the records in 'js_edu_details' table instead of fields having searched 'skills'.
Where I am going wrong? Any help wud b appreciated, thanx in advance.
Try:
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
//$skill = $this->input->post('ps_skills', true); other short way of getting the above result with `xss clean`
if ( $jrole !== NULL)
{
$this->db->like('js_skills',$skill); #remove the single quote around the `$skill`
$res = $this->db->get('js_edu_details');
echo $this->db->last_query(); #try to print the query generated
return $res;
}
}
Return statement should be after the like statement
You should arrange the code properly like this
public function emp_search_form()
{
$ps_skills = $this->input->post('ps_skills')
$skill = $this->security->xss_clean($ps_skills);
if ( $jrole !== NULL)
{
$this->db->like('js_skills','$skill');
return $this->db->get('js_edu_details');
}
}
Also you should note the condition will never meet. It will always give error undefined variable $jrole

How to correctly return an array for further use?

I have the following code on my site:
$statusMessageSQL = "SElECT * FROM statusmessages";
$statusMessagePrepare = $db->prepare($statusMessageSQL);
$statusMessagePrepare->execute();
$statusMessageResult = $statusMessagePrepare->fetchAll();
foreach($statusMessageResult as $row){
$row['username']=$db->getUsername($db->getUserNameById($row['posterID']));
$results[] = $row;
$smarty->assign('results', $results);
}
It works without any problems, but now I wanted to put most of this in my database class to work more object oriented. But I have some problems returning the array. I have done this
$statusMessage = $db->getStatusMessages();
var_dump($statusMessage);
The function:
function getStatusMessage(){
$statusMessageSQL = "SElECT * FROM statusmessages";
$statusMessagePrepare = $db->prepare($statusMessageSQL);
$statusMessagePrepare->execute();
$statusMessageResult = $statusMessagePrepare->fetchAll();
foreach($statusMessageResult as $row){
$row['username']=$db->getUsername($db->getUserNameById($row['posterID']));
$results[] = $row;
}
return $results;
}
But this just tells me, that my array is null. so there have to be an problem with my returning. How do I do it correctly?
My database entries are statusID, posterID, statusMessage, dateTime, sumRating and sumVotes.
And what do I do if I want to also return an entry of another table? Like, I have the givenName and familyName of the poster (posterID) on another table. How do I also return this data?
Okay I got it. First of all, I made the mistake, that I - as #slugonamission said - that I made a spelling mistake in the function name. Then, I changed my forloop in the home.php from
$statusMessage = $db->getStatusMessage();
for($i = 0; $i < sizeof($statusMessage); $i++){
$smarty->assign('results', $statusMessage[$i]);
}
to this, because the [$i] at the end made the forloop only use the last entry of the database and from that only the first letter.
$statusMessage = $db->getStatusMessage();
for($i = 0; $i < sizeof($statusMessage); $i++){
$smarty->assign('results', $statusMessage);
}
Now what I'm working on is how to get data from other tables, too.
function getStatusMessage(){
global $db; // this is what you actually need to make function work
$sql = "SElECT s.*, username FROM statusmessages s JOIN users u ON posterID.=u.id";
$stm = $db->prepare($sql);
$stm->execute();
return $stm->fetchAll();
}
note that you have to use JOIN to get associated info
You have to parse your $db variable to your function:
function my_function() {
global $db;
// some code
}
or to use it like this:
class myClass {
private $db;
public function __construct() {
$this->db = new MySQLi("host","user","pass","db");
}
public function my_function() {
$my_db_query = $this->db->query('query');
}
}

Working with multiple objects of the same type (PHP)

What is the corecte way to handle with al lot objects of the same type?
Example:
When i get a list of notes from the database with zend framework i get a rowset which contains an array with note data.
If the number of notes in the database is 20 records large it's no problem to create a note object for every note in the database. But if the database contains 12.500 note records what shall i do than? Try to create 12.500 objects is possible but it's shure isn't quick enough.
Ty, Mark
This is the code i use.
Code to get the data from the database:
if (is_numeric($id) && $id > 0) {
$select = $this->getDao()->select();
$select->where('methode_id = ?', $id);
$select->order('datum DESC');
$rowset = $this->getDao()->fetchAll($select);
if (null != $rowset) {
$result = $this->createObjectArray($rowset);
}
}
createObjectArray function:
protected function createObjectArray(Zend_Db_Table_Rowset_Abstract $rowset)
{
$result = array();
foreach ($rowset as $row) {
$model = new Notes();
$this->populate($row, $model);
if (isset($row['id'])) {
$result[$row['id']] = $model;
} else {
$result[] = $model;
}
}//endforeach;
return $result;
}
Populate function
private function populate($row, $model)
{
// zet de purifier uit om overhead te voorkomen
if (isset($row['id'])) {
$model->setId($row['id']);
}
if (isset($row['type'])) {
$model->setType($row['type']);
}
if (isset($row['tekst'])) {
$model->setLog($row['tekst']);
}
if (isset($row['methode_id'])) {
$model->setSurveyMethodId($row['methode_id']);
}
if (isset($row['klant_id'])) {
$model->setCustomerId($row['klant_id']);
}
if (isset($row['gebruiker_aangemaakt_tekst'])) {
$model->setCreatedByUser($row['gebruiker_aangemaakt_tekst']);
}
if (isset($row['gebruiker_gewijzigd_tekst'])) {
$model->setUpdatedByUser($row['gebruiker_gewijzigd_tekst']);
}
if (isset($row['gebruiker_aangemaakt'])) {
$model->setCreatedByUserId($row['gebruiker_aangemaakt']);
}
if (isset($row['gebruiker_gewijzigd'])) {
$model->setUpdatedByUserId($row['gebruiker_gewijzigd']);
}
if (isset($row['datum_aangemaakt'])) {
$model->setDateCreated($row['datum_aangemaakt']);
}
if (isset($row['datum_gewijzigd'])) {
$model->setDateUpdated($row['datum_gewijzigd']);
}
$model->clearMapper();
return $model;
}
You could page your requests, so you only get a set amount of notes back each time. Although I can't see a problem with "only 12,500" objects, unless your object creation is doing something costly, i.e more queries on the database etc.
I am not so sure about your question.
For eg :
//Create a single object
$obj = new NoteObject();
//Set the properties if it differs
$obj->setX( $row );
//Make use of the method
$obj->processMethod();
So this way you just need a single object. Lets see the code if its not to give you a right answer.
Edit :
What I thought was in
protected function createObjectArray(Zend_Db_Table_Rowset_Abstract $rowset)
{
$result = array();
//Create the model here
$model = new Notes();
foreach ($rowset as $row) {
//Yes populate the values
$this->populate($row, $model);
/*
And not like saving the object here in array
if (isset($row['id'])) {
$result[$row['id']] = $model;
} else {
$result[] = $model;
}*/
//Do some calculations and return the result in array
$result[$row['id']] = $this->doSomething();
}//endforeach;
return $result;
}
I am not sure why you are keeping this object there itself. Any reuse ? the probably paginate and do :-)

Categories