Php echo variables from a function outside the function when calling it - php

I have this php function which looks up rows from a database table
if (!function_exists("ContactLookup")) {
function ContactLookup($column, $clause, $value, $limit1=0, $limit2=1)
{
global $conn;
$ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
$ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
while ($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs)) {
$foremame =$ContactLookup_Result["forename"];
$surname = $ContactLookup_Result["surname"];
}
}
}
This just echoes the results but if I wanted to put the results into a select element how would I do this
Within the while loop would I create the variables then echo the variables when I call the function? Or is there another way around this?
Like:
<?php ContactLookup("company_sequence", "=", $result["contact"],"0","10"); ?>
><select name="contactsequence" id="contactsequence">
<option value=""><?php echo $forename; ?></option>
</select

Make your function return an array
function ContactLookup ($column, $clause, $value, $limit1=0, $limit2=1) {
global $conn;
$ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
$ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
$results = [];
while($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs))
{
$results[] = [
'forename'=> $ContactLookup_Result["forename"],
'surname'=> $ContactLookup_Result["surname"]
];
}
return $results;
}
Then you can loop through it:
<?php
$names = ContactLookup("company_sequence", "=", $result["contact"],"0","10");
echo '<select name="contactsequence" id="contactsequence">';
foreach($names AS $name){
echo '<option value="">'.$name['forename'].'</option>';
}
echo '</select>';

Change the function to return the results as a variable, rather than echo them.
function ContactLookup ($column, $clause, $value, $limit1=0, $limit2=1) {
global $conn;
$ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
$ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
$results=array();
while($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs))
{
$results[] = array('forename'=>$ContactLookup_Result["forename"],'surname'=>$ContactLookup_Result["surname"];
}
return $results;
}
Then in your display loop,
<?php $contacts=ContactLookup("company_sequence", "=", $result["contact"],"0","10"); ?>
<select name="contactsequence" id="contactsequence">
foreach($contacts as $k=>$contact){?>
<option value="<?php echo $k;?>"><?php echo $contact['forename']; ?></option>
<?php
}
</select>

Related

Get values ​from select2 with php without jquery

I have a registration system where there are several fields. One of the registration fields is Segments and they come from the database:
public function comboSegmentos($key)
{
$sqlMostrar = mysqli_query($this->conexao, "SELECT * FROM loja_segmentos;");
if (mysqli_num_rows($sqlMostrar) == 0)
{
$mostrar = "<div style='color: red'>Nenhuma segmento cadastrado até o momento.</div>";
}
else
{
$mostrar = "<select name='Segments[]' id='segmentos' class='form-control select2' multiple='multiple' style='width: 35%'>";
while ($jmMostrar = mysqli_fetch_object($sqlMostrar))
{
$mostrar .= "<option value='".$jmMostrar->Segmentos."' ".$selected.">".$jmMostrar->Segmentos."</option>";
}
$mostrar .= "</select>";
}
return $mostrar;
}
So that the method doesn't have too many parameters, I did it like this:
<?php
...
$dados = array_filter($_POST);
echo $metodos->cadastrarProdutos($dados);
Method cadastrarProdutos($dados)
But I'm not able to get the values ​​of the Segments even using foreach().
<?php
public function cadastrarProdutos(array $dados)
{
...
$segments = $dados["Segments"];
foreach($segments as $seg)
{
$segm = $seg;
}
...
}
How can I get the values ​​of the select2 field and get them using a PHP method without Jquery?
I managed to solve it as follows:
<?php
public function cadastrarProdutos(array $dados)
{
...
$segments = $dados["Segments"];
$segm = array();
foreach($segments as $seg)
{
$segm[] = $seg;
}
$segments = implode(',',$segm);
...
}

foreach or while only displays last result

This structure will have several pages only foreach or while is only showing the last result, this problem occurred after I made this function, I've seen several questions and is something related to matriz
class Layout {
private $sql, $row;
private function set_layout($cond, $cond_r) {
$this->sql = $this->select("*", "table", "".$cond."", array($cond_r));
foreach ($this->sql as $this->row) :
return $this->row['name'];
endforeach;
}
public function get_layout($cond, $cond_r) {
return $this->set_layout($cond, $cond_r);
}
}
echo $midia->get_layout("WHERE status != ? ORDER BY id DESC", 0);
I'm not sure but I think you're looking for something like:
class Layout {
private $sql, $row;
private function set_layout($cond, $cond_r) {
$this->sql = $this->select("*", "table", "".$cond."", array($cond_r));
$rows = array();
foreach ($this->sql as $this->row) :
$rows[] = $this->row['name'];
endforeach;
return implode($rows); //Return array of rows AFTER loop
}
public function get_layout($cond, $cond_r) {
return $this->set_layout($cond, $cond_r);
}
}
echo $midia->get_layout("WHERE status != ? ORDER BY id DESC", 0);

Print same code twice in two locations in one php file

I need two print the same rows which retrieved from the db, in two different locations in same php file.
I know it is better to have a function. It tried, It doesn't work properly.
I am using the below code print the said rows/
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
I need to print exactly the same code twice in two different location in a php file.
I think it is not a good idea to retrieve data twice from the server by pasting the above code twice.
Is there any way to recall or reprint the retrieved data in second place which I need to print.
Edit : Or else, if someone can help me to convert this to a function?
I converted this into a function. It prints only first row.
Edit 2 : Following is my function
unction getGroup($dbconn)
{
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($dbconn ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$groupData = "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
return $groupData;
You can store the records coming from the DB in array and use a custom function to render the element
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
$options = []; //store in an array
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$options[$groups['profile_gid']] = $groups['profile_gname'];
}
}
Now you can use the $options array many times in your page
echo renderElement($options);
function renderElement($ops){
$html = '';
foreach($ops as $k => $v){
$html .= "<option value={$k}>{$v}</option>";
}
return $html;
}
If the data is same for both places, put the entire string into variable, then echo it on those two places.
instead of
echo "here\n";
echo "there\n";
do
$output = "here\n";
$output .= "there\n";
then somewhere
echo $output
on two places....
Values are being stored in groups array, hence you can use a foreach loop elsewhere to get values from the array:
$groups = array();
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
// use here
foreach($groups as $group)
{
echo $group['profile_gid'] . " ". $group['profile_gname'] . "<br/>";
}
class ProfileGroups
{
public $profile_groups_options;
public static function get_profile_groups_options($condb) {
$get_g = "SELECT * FROM profile_groups";
if( isset( $this->profile_groups_options ) && $this->profile_groups_options != '') {
return $this->profile_groups_options;
}
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$this->profile_groups_options .= "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
$this->profile_groups_options .= '<option value="">Empty - No Groups!!</option>';
}
return $this->profile_groups_options;
}
}
ProfileGroups::get_profile_groups_options($condb);

Set selected value on dynamic dropdown list

I have the below code, so the user can select the language he desire:
<label style="float: left; width: 50%;" for="system_language">Select Language:</label>
<select id="system_language" class="selectbox float-right" onChange="switchLanguageLogin(); ">
<? echo getLanguageList(); ?>
</select>
This is the function of the languages!
function loadLanguage($lng, $units = '')
{
global $ms, $la, $gsValues;
// always load main english language to prevet error if something is not translated in another language
include ($gsValues['PATH_ROOT'].'lng/english/lng_main.php');
// load another language
if ($lng != 'english')
{
$lng = $gsValues['PATH_ROOT'].'lng/'.$lng.'/lng_main.php';
if (file_exists($lng))
{
include($lng);
}
}
Added the Language Function
function getLanguageList()
{
global $ms, $gsValues;
$result = '';
$languages = array();
$q = "SELECT * FROM `gs_system` WHERE `key`='LANGUAGES'";
$r = mysqli_query($ms, $q);
$row = mysqli_fetch_array($r);
$languages = explode(",", $row['value']);
array_unshift($languages , 'english');
foreach ($languages as $value)
{
if ($value != '')
{
$result .= '<option value="'.$value.'">'.ucfirst($value).'</option>';
}
}
return $result;
}
The first (and default) option on the dropdown menu is English. The problem is that if I choose Spanish, it translates to Spanish, but on the dropdowm menu it leaves the default value which is English. This concludes that the page is in Spanish, but the value from the dropdown shows "English".
How can i solve this?
You do not use your $lng variable in the global scope, so it is not visible for your function. A solution would therefore be to provide the selected language as parameter to the getLanguageList function and set the equal value as selected:
function getLanguageList($selected = 'english') {
//...
foreach ($languages as $value) {
if ($value !== '') {
$result .= '<option value="'.$value.'" ' . ($selected === $value ? ' selected="selected"' : ''). '>' . ucfirst($value) . '</option>';
}
}
//...
}
Like this the selection is kept for the dropdown and therefore for the HTML.
In your view you would then need to provide $lng and call <? echo getLanguageList($lng); ?>.
Check in your init.php file should have a comment
// gets language from cookies
If there is not such comment, write it just before MySQL connection and add the following code after it
if (isset($_COOKIE['gs_language']))
{
$gsValues['LANGUAGE'] = $_COOKIE['gs_language'];
}
else
{
$expire = time() + 2592000;
setcookie('gs_language', $gsValues['LANGUAGE'], $expire, '/');
}
// puts selected language into cookies
if (isset($_GET['lng']))
{
$gsValues['LANGUAGE'] = $_GET['lng'];
$expire = time() + 2592000;
setcookie('gs_language', $gsValues['LANGUAGE'], $expire, '/');
}
Then go to fn_common.php file and change the getLanguageList function to
function getLanguageList()
{
global $ms, $gsValues;
$result = '';
$languages = array();
$q = "SELECT * FROM `gs_system` WHERE `key`='LANGUAGES'";
$r = mysqli_query($ms, $q);
$row = mysqli_fetch_array($r);
$languages = explode(",", $row['value']);
array_unshift($languages , 'english');
$currentLang = $gsValues['LANGUAGE'];
foreach ($languages as $value)
{
if ($value != '')
{
$result .= '<option value="'.$value.'" ' . ($currentLang === $value ? ' selected="selected"' : ''). '>' . ucfirst($value) . '</option>';
}
}
return $result;
}

function returning only once, why?

During my coding I really got stuck into this problem.
I ran a foreach loop and for every item I had to get a certain value from a function.
But I got only one returned. I could not figure out what was happening. I hope you guys surely will.
Below is the short version of my program.
Database structure is given at last.
<?php
function opendb() {
mysql_connect("localhost", "root", "root");
mysql_select_db("something_db");
}
function sql_query($sql) {
$datas = array();
if ($res = mysql_query($sql)) {
$x = 0;
while ( $data = mysql_fetch_assoc($res) ) {
$datas[$x] = $data;
$x += 1;
}
}
return $datas;
}
function get_parent_id($table, $parent, $cid) {
// cid=>child id
$sql = "SELECT * FROM $table WHERE id=$cid";
$datas = sql_query($sql);
$pid = $datas[0]['parent'];
$p_id = $datas[0]['id'];
if ($pid != 0) {
get_parent_id($table, $parent, $pid);
} else {
return $p_id;
}
}
opendb();
$datas_pkg = sql_query("SELECT * FROM tbl_packages WHERE 1");
foreach ( $datas_pkg as $data_pkg ) {
echo $data_pkg['destination_id'] . '-->';
echo $parent_id = get_parent_id('tbl_destinations', 'parent', $data_pkg['destination_id']);
echo '<br/>';
}
?>
Database structure..
tbl_destinations
+--------+-------------------------+-----------+
| id(int)|destination_name(Varchar)|parent(int)|
+--------+-------------------------+-----------+
tbl_packages
+-------+---------------------+-------------------+
|id(int)|package_name(varchar)|destination_id(int)|
+-------+---------------------+-------------------+
If I did not clear my question please let me know so that I can help you to help me.
if($pid!=0)
{
get_parent_id($table,$parent,$pid);
}
You call the function, but never use its value.

Categories