Php arrays -- one title a few record - php

i have a problem with php in arrays.
i have a db table like that , it shows applications to job.
What i want is to order job titles with their files for example
title must be shown :
WEB Tasarım Uzmanı
noktamedya.com/CVs/zsdfsdfsdfsdfsdf.docx
noktamedya.com/CVs/zsdfsdfsdfsdfsdf.docx
İçerik Yöneticisi
noktamedya.com/CVs/abc.docx
noktamedya.com/CVs/abc.docx
i have a class which takes to important record from db
public function getAllRec()
{
$query = "SELECT * FROM applyRecords ";
$resultDb = $this->db->query ($query);
$jobs = array ();
while ( $row = $resultDb->fetchObject () ) {
$job = new Job ();
$job->title = $row->jobTitle;
$job->url = $row->file;
$jobs [] = $job;
}
return $jobs;
}
i have here to file and jobTitle.
in admin inc. i call this function like that
$jobs3 = $jobHome->getAllRec();
and try to order with their jobTitle but have error and dont understand
foreach($jobs3 as $job)
{
$groupJobs = [$job->title][$job->url] = $job;
}
what's wrong here?

I think this is what you are trying to do:
Group job applications by title of job applying to
$groupJobs = array();
foreach($job3 as $job){
if(!isset($groupJobs[$job->title])){
$groupJobs[$job->title] = array();
}
$groupJobs[$job->title][] = $job; // add job to group
}

Instead of ordering in PHP, order in SQL, and then continue.
Instead of
"SELECT * FROM applyRecords "
try
"SELECT * FROM applyRecords ORDER BY jobtitle "

Try something like this:
$groupJobs[$job->title] = array(
$job->url => $job
);
The groupJobs Array Must be defined as Array before foreach.
And remember, $job is an object.

Just sort the records at the time of database fetch
"SELECT * FROM applyRecords ORDER BY jobTitle"

$groupJobs = [$job->title][$job->url] = $job;
This is not valid php syntax. I can't even see what are you trying to do here but I make a wild guess:
$groupJobs[] = array(
"title" => $job->title,
"urls" => array($job->url1, $job->url2)
);
About the ordering: You should add a parameter for this and let sql do to ordering:
public function getAllRec($order)
{
$query = "SELECT * FROM applyRecords ";
if ($order) $query .= " ORDER BY " . $order;
$resultDb = $this->db->query ($query);
...

My final answer is below
$groupJobs = array();
foreach($jobs3 as $job)
{
$groupJobs[$job->title][] = $job;
}
foreach($groupJobs as $key => $value){
$key . "<br />";
foreach($value as $node){
$node->url;
$node->name;
}
}
Thank you all.

Related

Assign output of PHP function to a variable

Here's my current code:
function get_coins() {
global $conn;
$new_sql = "SELECT * FROM marketcaps ORDER BY cap DESC LIMIT 25";
$new_result = $conn->query($new_sql);
while ($row = $new_result->fetch_assoc()) {
$id = $row["id"];
$coin = $row["coin"];
$cap = $row["cap"];
echo $coin . '~USD,';
}
}
$coins = get_coins();
Here's what I can't figure out:
The line $coins = get_coins(); is echoing all of the data from my function and I don't understand why. I know that my function has this line: echo $coin . '~USD,';
But why is it echoing when I add $coins = get_coins();?
Shouldn't I have to add this instead?
$coins = get_coins();
$echo coins;
Basically I don't want to echo anything, I just want to assign the output to a variable. Is there a simple way to do that?
You need to add a return statement to your function, and as you are dealing with multiple rows, collate them into an array (index by ID).
http://php.net/manual/en/function.return.php
function get_coins()
{
global $conn;
$coins = array();
$new_sql = "SELECT * FROM marketcaps ORDER BY cap DESC LIMIT 25";
if( $new_result = $conn->query($new_sql) )
{
while( $row = $new_result->fetch_assoc() )
{
$coins[ $row["id"] ] = $row["coin"] . '~USD,';
}
}
return ( !empty( $coins ) ) ? $coins : null;
}
Here are the principles that I have baked in with my solution which returns the full resultset array:
Don't use global, pass $conn as a parameter to the function.
Don't declare single use variables, unless it dramatically improves readability or assists in the debugging process.
Only query for the specific columns and rows that you intend to process.
Suggested Code:
function get_coins($conn): array {
return $sql
->query("SELECT id,coin,cap
FROM marketcaps
ORDER BY cap DESC
LIMIT 25")
->fetch_all(MYSQLI_ASSOC);
}
foreach (get_coins($conn) as $row) {
// ... reference $row['id'] , $row['coin'] , $row['cap'] during your processes
}

N1QL prepared statement not working 100%

I have a problem where some variables are probably (I can't know for sure) not inserted into the final statement. Here is my example:
Works:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING('.$field.') LIKE "%'.$searchterm.'%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
//$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
//$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug Output:
debug01
Does not work:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING($field) LIKE "%$searchterm%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug output:
debug02
Basically the second example returns no result, while the first one works just fine.
Any idea why?
You are not using N1QL parameters correctly. You must decide if you are evaluating your parameters in PHP or in N1QL.
The field name cannot be a N1QL parameter, so you evaluate it in PHP:
TOSTRING('.$field.') LIKE ...
The search term should be a N1QL parameter, so you add wildcards in PHP and then pass it to N1QL as a parameter:
$searchterm = '%'.$searchterm.'%'
TOSTRING('.$field.') LIKE $searchterm ...

PHP Array not being delivered

I have some data in a database column called "gcmregid".
I access this data by calling:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
while ($row = mysql_fetch_array($r)) {
$result = array(
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
Correct me if I'm wrong, but this should deliver an array, due to result = array?
I took this logic from here: Getting Resource id #3 Error in MySql
.Then I thaught using a loop would be helpful, such as:
$userCount = $db->getUserCount(); // counting said table
$registation_ids = array(); // again create array
for($i=0; $i < $userCount; $i++)
{
$gcmRegId = $db->getGCMRegID($selUsers[$i]);
$row = mysql_fetch_assoc($gcmRegId);
//Add RegIds retrieved from DB to $registration_ids
array_push($registation_ids, $row['gcmregid']); // this creates an array consisting of gcmregid s ?
}
It doesn't work either.
Any input would be really appreciated right now...
Thanks
I'm not sure what's going wrong, but if the problem is that it's returning a single item: that's because you keep making a new array with every iteration, discarding the old one. If you want to collect all the rows, make a new array outside of the loop and then add the results to it:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
$result = array();
while ($row = mysql_fetch_array($r)) {
$result[] = array (
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
You should consider working more on how you name your functions. If you are trying to get gcmregid, the method should not say getAllUsers. Anyway, did you try the following:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$row = mysql_fetch_array($query_result);
return $result[0]['gcmregid'];
}
OR if you are trying to get all gcmregid in one shot:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$i=0;
while ($row = mysql_fetch_array($query_result)){
$result[$i++] = $row['gcmregid'];
}
return $result;
}

PHP list to an Array to a foreach Joomla Module

I have the following PHP, that needs to take a list of article ids and run it through a function to get them all from the database.
I am very much a beginner in PHP so far I have:
list($slide1, $slide2, $slide3, $slide4, $slide5) = explode(" ", $params->get('id'));
$a = array(
$item => $slide1,
"two" => $slide2,
// "three" => $slide3,
// "four" => $slide4,
// "five" => $slide5
);
foreach ($a as $k) {
$args['id'] = $k;
$item = ModArticleSlider::getArticles($args);
}
and the class:
class ModArticleSlider {
public function getArticles($args){
$db = &JFactory::getDBO();
$item = "";
$id = $args['id'];
if($id > 0){
$query = "select * ";
$query .= "FROM #__content WHERE id =".$id." AND state=1 " ;
//echo $query;
$db->setQuery($query);
$item = $db->loadObject();
}
return $item;
}
}
How would i get it so that instead of specifying $item to have it almost dynamic so that i can get all the selected articles and place them in different variables.. or would i have to place them in a array?
Any Advice/Answers Greatly Appreciated.
Another approach, and possibly more performant as it would require only one database query (versus one for each article), would be to use http://docs.joomla.org/JDatabase::loadObjectList
So, you could instead pass an array of your articles ids as $ids to your class like:
public function getArticles($ids){
if ($ids) {
$db = JFactory::getDbo();
$query = "SELECT * FROM #__content WHERE id IN (" . implode(',', $id) . ") AND state=1 " ;
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
return FALSE;
}
$rows is returned as an array so you can then process it as needed.
i am also beginner of PHP.
Please Try this:
foreach ($a as $k => $val) {
$args = $val;
$item[] = ModArticleSlider::getArticles($args);
var_dump($item);
}
in your class
simply
$id = $args;
i hope it will help you!
Store the articles into an array, you can try this:
$slides = explode(" ", $params->get('id'));
$articleArray = array();
foreach($slides as $slide) {
$articleArray[] = ModArticleSlider::getArticles($slide);
}
var_dump($articleArray);

Undefined index ONLY when using array

I want to have a SelectAll function which takes in a few arguments (class, table, sort field, and sort order.) The comments explain what is going on (or what is supposed to.)
public static function SelectAll($class, $table, $sort_field, $sort_order = "ASC")
{
/* First, the function performs a MySQL query using the provided arguments. */
$query = "SELECT * FROM " .$table. " ORDER BY " .$sort_field. " " .$sort_order;
$result = mysql_query($query);
/* Next, the function dynamically gathers the appropriate number and names of properties. */
$num_fields = mysql_num_fields($result);
for($i=0; $i < ($num_fields); $i++)
{
$fetch = mysql_fetch_field($result, $i);
$properties[$i] = "'".$fetch->name."'";
}
/*echo [$properties[0]; echo "<br />";}*/
/* Finally, the function produces and returns an array of constructed objects. */
while($row = mysql_fetch_assoc($result))
{
for($i=0; $i < ($num_fields); $i++)
{
$args[$i] = $row[$properties[$i]];
}
$array[] = call_user_func_array(new $class, $args);
} return $array; }
Now, the problem I am having is that $row[$properties[$i]] results in 'undefined index.'
Right after the function gathers the number/names of the fields and stores them in an array, I can echo the value of $properties[0] and it shows as it should, 'id', but $row[~anything here~] will simply not work unless I manually enter the value, such as $row['id']. As you can imagine very frustrating and confusing.
Why won't this work? Are there any solutions, or alternate ways of accomplishing this function?
As I see your $properties[$i] array items have quoted values like "'id'",
so $row[$properties[$i]] <==> $row["'id'"] != $row["id"];
And you might want to check $result === false after $result = mysql_query($query);
Anyway, I think you could replace your function to this (unless you constructed it for demonstration only):
public static function SelectAll($class, $method_name, $table, $sort_field, $sort_order = "ASC"){
/* First, the function performs a MySQL query using the provided arguments. */
$query = "SELECT * FROM " .$table. " ORDER BY " .$sort_field. " " .$sort_order;
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
$array[] = call_user_func_array(array($class,'__construct'), $row);
return $array;
}

Categories