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
Related
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);
I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.
You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';
First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}
Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}
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));
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;
}
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;
}