return array in function - php

I want to translate each words in array:
$myarray = array("hi","bro");
So I wrote a translate function like this:
function translate($word) {
foreach ( $word as $key_translate ) {
$array = array();
$sql = mysql_query("SELECT * FROM `translate` WHERE name = '".$key_translate."' ");
if ( mysql_num_rows($sql) == 1 ) {
$row = mysql_fetch_array($sql);
$name = $row['fa_name'];
return $name;
//retuen array($name);
}
else {
return $key_translate;
//return array($key_translate);
}
}
}
And using this to show translated array:
print_r (translate($myarray));
But it's not returning array, it's just showing first key as string.
How can I return array in function?

Don't return inside the loop, that exits the whole function immediately and just returns that one element. Accumulate the results in an array, and return that.
function translate($word) {
$result = array();
foreach ( $word as $key_translate ) {
$sql = mysql_query("SELECT fa_name FROM `translate` WHERE name = '".$key_translate."' ");
if ( mysql_num_rows($sql) == 1 ) {
$row = mysql_fetch_array($sql);
$result[] = $row['fa_name'];
}
else {
$result[] = $key_translate;
}
}
return $result;
}
Also, there's no reason to use SELECT * if you're only interested in fa_name.

Try this:
function translate($word) {
foreach ($word as $key => $translate) {
$sql = mysql_query("SELECT * FROM `translate` WHERE name = '" . $translate . "' ");
if (mysql_num_rows($sql) == 1) {
$row = mysql_fetch_array($sql);
$word[$key] = $row['fa_name'];
}
}
return $word;
}

Related

How to assign array value into variable inside foreach loop in codeigniter

I have an array of users with different userIds and I am trying to loop these array using a foreach loop. Inside that loop I am calling a function to get values of each users by passing their userid into a function. But its only passing one index of array.
My code
public function getDailyReportTest($orgId, $date)
{
$query = $this->db->query("SELECT * FROM `organization_users` WHERE orgId='7'");
$timestamp = strtotime($date);
$day = date('l', $timestamp);
$data = array();
$i = 0;
foreach ($query->result_array() as $row) {
$data[$i]['date'] = $date;
$data[$i]['day'] = $day;
$data[$i]['user_id'] = $row['orgUserId'];
$data[$i]['user_name'] = $row['orgUserName'];
$data[$i]['workingHours'] = self::getUserWorkingHours($data[$i]['user_id'],$date);
$delayTime=self::getUserDelayTime($row['orgUserId'],$date);
$shortTime=self::getUserShortTime($row['orgUserId'],$date);
$overTime=self::getUserOverTime($row['orgUserId'],$date);
$data[$i]['delayTime'] =$delayTime;
$data[$i]['shortTime'] =$shortTime;
$data[$i]['overTime'] =$overTime;
$data[$i]['shift1_start'] = self::getUserShiftStartTime($row['orgUserId'], $date);
$i=$i+1;
}
//return $data;
print_r($data);
die();
}
public function getUserShiftStartTime($userId, $date)
{
$query = $this->db->query("SELECT * FROM `office_employee_assigned_shifts` WHERE employeeId='$userId' &&shiftdate='$date'");
$entry = $query->num_rows();
$data = $query->result_array();
if($entry==0)
{
return NULL;
}
else
{
$shiftId = $data[0]['shiftId'];
$shiftquery = $this->db->query("SELECT startTimeSpan, endTimeSpan FROM `office_shift_time` WHERE officeShiftId='$shiftId'");
$dataShift = $shiftquery->result_array();
$startSpan = $dataShift[0]['startTimeSpan'];
$endSpan = $dataShift[0]['endTimeSpan'];
$firstPunchQuery = $this->db->query("SELECT punchTime AS firstPunch FROM `employee_punch_log` WHERE punchDate='$date' && employeeId='140' && punchTime BETWEEN '$startSpan' AND '$endSpan' AND punchType='1' LIMIT 1");
$punchEntryCount = $firstPunchQuery->num_rows();
if($punchEntryCount>0)
{
$dataFirstPunch = $firstPunchQuery->result_array();
$firstPunchStartTime = $dataFirstPunch[0]['firstPunch'];
return $firstPunchStartTime;
}
else
{
return "AB";
}
}
// return $entry;
}
It only passes the $data[1]['user_id'].
I want to pass $data[0]['user_id'], $data[1]['user_id'], $data[2]['user_id'] to the function
named getUserShiftStartTime($userId, $date)
Any Help?
Thanks for the help in advance
Then pass the current variable to your method:
self::getUserShiftStartTime($data[$i]['user_id'], $date);

Database values with PHP function

I want to call a php function, returns database values.
public function readdata() {
$id = "";
$name = "";
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
foreach ($sth as $s) {
$id .= $s->id;
$name .= $s->name;
}
return compact('id', 'name');
}
$rd = readdata();
$get_id = $rd['id'];
$get_name = $rd['name'];
echo $get_id;
echo $get_id.$get_name.'<br>';
When I execute the code, it shows the output as:
7891011
7891011Text1Text2Text3Text4Text5
But I want as a single value vertically displayed. Do I need to explode ' | '
I guess you can easily change your existing code slightly and get what you expected,
<?php
public function readdata() {
$id = "";
$name = "";
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
foreach ($sth as $s) {
$array[$s->id] = $s->name; # building id => name structure
}
return $array;
}
$rd = readdata();
# now readdata() will return data as below array
$array = [7=>'text1',8=>'text2',9=>'text3',10=>'text4',11=>'text5'];
foreach($array as $k=>$v){
$result[] = $k." ".$v;
}
echo implode("\n", $result);
?>
DEMO: https://3v4l.org/PusI4

Executing pre-build-up array with PDO Execute

I am trying to pass through any query to a function using PDO.
I have build up the array through a loop function and try to insert it into the execute(array(....)) function, but it's not getting through.
FUNCTION CODE
public function ShowData($sql,$variable)
{
$execute_string = "";
echo "<pre>";
print_r($variable);
echo "</pre>";
$q = $this->conn->prepare($sql);
for($i = 0; $i < sizeof($variable); $i++)
{
if($i != 0) $execute_string .= ",";
$placeholder = $i + 1;
$execute_string .= "':$placeholder' => '".$variable[$i]."'";
}
echo $sql."<br>";
echo $execute_string;
$q->execute(array($execute_string));
echo "<br>Execute Succeeded";
return $row = $q->fetchAll();
}
VIEWPAGE CODE
$author = "Nemoza";
$name = "MBICO_mailer";
$project = $data->ShowData("SELECT * FROM mbico_projects WHERE author=:1 AND name=:2", array($author,$name));
OUTPUT FROM FUNCTION W/ DEBUGGING
Array
(
[0] => Nemoza
[1] => MBICO_mailer
)
SELECT * FROM mbico_projects WHERE author=:1 AND name=:2
':1' => 'Nemoza',':2' => 'MBICO_mailer'
However, the 'Execute Succeeded' text is not being printed, and the execute(array...)) is not actually executing.
What am I doing wrong, and how else should I do it?
here's an example you can use:
public function ShowData($sql,$variable) {
$bind = [];
foreach ($variable as $key => $value) {
$ph = $key+1;
$bind[":" . $ph] = $value;
}
$stmt = $this->conn->prepare($sql);
$stmt->execute($bind);
return $stmt->fetchAll();
}
it's used like this:
$sql = 'select * from users where username = :1 or username = :2';
$bind = ['123', '456'];
$db->ShowData($sql, $bind);
as mentioned in the comments to your question, you need to send an array to execute() function, and not a string.
Managed to do it like this:
public function ShowData($sql,$variable)
{
$execute_string = array();
$q = $this->conn->prepare($sql);
foreach($variable as $item)
{
$execute_string[] = $item;
}
$q->execute($execute_string);
return $q->fetchAll();
}
$project = $data->ShowData("SELECT * FROM mbico_projects WHERE author=? AND title=?", array($author, $title));

Memcache results and while loop

I wrote this function for caching queries:
function get_cached($query, $type = 1) {
$key = md5(strtolower($query));
$cached = $memcache->get($key);
if($cached) {
$res = unserialize($cached);
} else {
$r = mysql_query($query);
if($mode == 1) {
$res = mysql_fetch_object($r);
} else {
$res = mysql_fetch_array($r);
}
$memcache->store($key, serialize($res));
}
return $res;
}
And it kinda works, i can cache simple queries. But i have problem with queries that operate within loops.
I really can't understand how to get around this, and "port" this to use my get_cached() function first.
$ref = mysql_query("query");
while($res = mysql_fetch_object($ref)) {
//do something with results
}
How i can do it through cache?
You cannot store the mysql result object but you can fetch all rows into an array and cache the array. like
function get_cached($query, $type = 1) {
$key = md5(strtolower($query) . $type);
$cached = $memcache->get($key);
if($cached) {
return unserialize($cached);
} else {
$r = mysql_query($query);
$data = array();
if($mode == 1) {
foreach($row = mysql_fetch_object($r)) {
$data[] = $row;
}
} else {
foreach($row = mysql_fetch_array($r)) {
$data[] = $row;
}
}
$memcache->store($key, serialize($data));
}
return $data;
}
don't forget to store the type of your functions as cache key too, otherwise you fetch a results set with type==1 and in return you get the elements as array

Function foreach is only returning last array

I have this being put into a table listing and what it does is the first function populates the first three rows and then the second function populates the 4th row based on the match of the first function.
public function function1($start = 0, $max = 10, $use_result = false) {
$sql = 'SELECT itemnum, descrip FROM TABLENAME
WHERE itemnum LIKE "__-_____"
AND cms_item_id IS NULL
ORDER BY itemnum ASC
LIMIT ' . (int)$start . ',' . (int)$max .'';
$result = $this->registry->db->query($sql);
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = $row;
}
return $return;
}
/**
* Get matches
* #return array
*/
public function function2(){
$product = $this->getList();
foreach($product as $key) {
$sku = $key['itemnum'];
list(, $sku) = explode("-", $sku);
}
$sql = 'SELECT product_sku, long_name
FROM TABLENAME
WHERE product_sku = "' . $sku . '"';
$result = $this->registry->db->query($sql);
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = $row;
}
return $return;
}
What is happening is the 3 rows are returning fine. But the 4th row is only returning the last $sku not anything matching. I know the foreach loop is being overwriting each time and the final one is being put into the variable $sku...but how else could I do this to get what I need?
Make an array of all the SKUs, and use IN instead of = to match them.
public function function2(){
$product = $this->getList();
$skus = array();
foreach($product as $key) {
$sku = $key['itemnum'];
list(, $sku) = explode("-", $sku);
$skus[] = $sku;
}
$sku_string = implode(', ', array_map(function($x) {return "'$x'"; }, $skus));
$sql = 'SELECT product_sku, long_name
FROM TABLENAME
WHERE product_sku IN (". $sku_string .")';
$result = $this->registry->db->query($sql);
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = $row;
}
return $return;
}
Perhaps a better solution would be to combine your queries into one:
SELECT itemnum, descrip, long_name
FROM table1 t1
JOIN table2 t2 ON t2.product_sku = substring_index(itemnum, '-', -1)
WHERE itemnum LIKE "__-_____"
AND cms_item_id IS NULL
ORDER BY itemnum ASC
LIMIT ' . (int)$start . ',' . (int)$max
try this:
public function function2(){
$product = $this->getList();
$sku = array(); //Make an empty $sku array
foreach($product as &$key) {
$sku = $key['itemnum'];
list(, $sku) = explode("-", $sku);
$key['sku'] = $sku;
$skus[] = $sku;
}
$selectValues = implode(',', $skus);
$sql = "SELECT product_sku, long_name FROM TABLENAME WHERE product_sku IN($selectValues)";
$result = $this->registry->db->query($sql);
$return = array();
$long_names = array();
while($row = $result->fetch_assoc()) {
$long_names[$row['product_sku']] = $row['long_name'];
}
foreach ($product as &$key) {
$key['long_name'] = $long_names[$key['sku']];
}
return $product;
}

Categories