php array output with for loop dosent come as it should - php

I am trying to retrive data from database using FECH_ASSOC in order the output will took like this
last1 first1 last2 first2 & last3 first3
last4 first4 & last4 first4
this is the database i have:
ID index first last
--------------------------
1 1 first1 last1
2 1 first2 last2
3 1 first3 last3
4 2 first4 last4
5 2 first5 last5
Each output row shoud defined by the index value.
as you can see in the output example I need the organ before the last one in any array to be separetad because i need to put the & before it.
this is the code i came up with:
//HERE I RETRIVE ALL THE DATA FROM THE DATABASE.
$sql = "SELECT COUNT( * ) FROM table WHERE index= $index";
$result = $dbh->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
//ASSOC DEFINITION
$sth = $dbh->prepare("SELECT * FROM table WHERE index= $index);
$sth->execute();
$value = $sth->fetch(PDO::FETCH_ASSOC);
//THIS IS WHERE I CALL ALL THE ROWS BY THEIR VALUE
$return = "";
$fname = $value['fname'];
$lname = $value['lname'];
$numRow = $number_of_rows-2; // THE ITEM BEFORE THE LAST ONE IN THE ARRAY
$lastItem = $number_of_rows - 1; //LAST INDEX IN THE ARRAY
for($counter = 0; $counter <= $numRow; $counter++){
$value = $sth->fetch(PDO::FETCH_ASSOC);
$fname[$counter] = !empty($fname[$counter]) ? $fname[$counter] : '';
$return .= $lname. ', ' . $fname;
}
$fname[$counter] = !empty($fname[$lastItem]) ? $fname[$lastItem] : '';
$return .= "&" . $fname. ', ' . $lname;
$return .= ' ';
return $return;
this is the output i get:
last3 first1 last1 first1 & last2 first1
last5 first4 & last4 first4
I cant figure out what i am doing wrong.
I tryied using foreach but i didnt manage to separete the last pair of values here.
I am stuck with this this for a few days.
any help would be great.

Related

PHP Table Column name

I have an script for getting a table from a DB which is written in PHP.
I am trying to add name for each column to be in the first row:
A part of the Code is:
$rows = [];
foreach (range(1, 4) as $row) {
$rows[$row] = "";
}
$rows["Name"] = $order->user->aFirstName;
$rows["Last Name"] = $alumn->aLastName;
$rows["Age"] = $alumn->aAge;
$rows["Gender"] = $alumn->aGender;
$string = "";
foreach ($rows as $r) {
$string .= $r . "\t";
}
what I want to get is
1 | Name | Last Name | Age | Gender
2 | John | Des | 45 | Male.
What I get now is the data in 1st row.
1 | John | Des | 45 | Male.
Any suggestion? Thanks
You can create a new first element in $rows using https://www.php.net/manual/de/function.array-unshift.php
$labels = ["Name" => "NameLabel", "Last Name" => "Last NameLabel" ...];
array_unshift($rows, $labels);
So the first element of the $rows array are the labels. Now when the table is generated is will display the labels at the top.
You are loading the arrays incorrectly.
I assume you dont want to get the column names from the meta data available to you, and are happy to add the column names manually, if not let me know
$rows = [];
// add labels
$rows[] = ["Name", "Last Name", "Age", "Gender"];
#$rows[] = [$order->user->aFirstName, $alumn->aLastName, $alumn->aAge, $alumn->aGender];
// I dont have your data, so this is to simulate the above line
$rows[] = ['John', 'Des', 45, 'Male'];
$string = '';
foreach ($rows as $i => $row) {
$n = $i+1;
$string .= "$n\t";
foreach ($row as $col){
$string .= $col . "\t";
}
$string .= '<br>'. PHP_EOL;
}
print_r($string);
RESULTS, as you can see a Tab is not really enough to correctly format the table
1 Name Last Name Age Gender <br>
2 John Des 45 Male <br>

Can I get value from mysql table and set it as variable?

I have attribute_description like in the image :
on table I have for cap_tabel values: d, lt, lu, amb, coada
I want to get them and make it variable and set the value equal to the attribute_id.
eg:
$d = 1;
$lt = 2;
$coada = 9;
I think i can create a function.php file where this variables are created and use them where is needed.
Is this possible or I have to create a script where I name the variable myself and set it the right value like:
$amb_ext = mysqli_fetch_array(mysqli_query($connect,"SELECT attribute_id FROM attribute_description WHERE cap_tabel='amb'"));
$amb = $amb_ext['attribute_id'];
What do you think is the best solution?
In the end I want to create a product table where in th will be value from cap_tabel and in td to get the right value with the correct th cell
You could use variable variables:
$res = mysqli_query($connect,"SELECT attribute_id, cap_tabel FROM attribute_description");
while ($row = $res->fetch_assoc()) {
$var = $row['cap_tabel'];
$$var = $row['attribute_id'];
}
// you now would have variables $d, $lt, etc
$result = mysqli_query($connect,"SELECT attribute_id, cap_tabel FROM attribute_description");
while ($aValue = mysqli_fetch_array($result)) {
${$aValue['cap_tabel']} = $aValue['attribute_id'];
}
echo ' $d = ' . $d . ', $lt = ' . $lt . ', $coada = ' . $coada;
To get result like this :
$d = 1, $lt = 2, $coada = 9

Combine 2 while loop results

We have 2 while loops , we are displaying 2 different results with both.
we need to combine or without combining we need to merge 2 results.
in below image ,
1st while loop result = > 1st, 2nd, 6th rows.
2nd while loop result = > 3rd, 4th, 5th rows.
we need 3rd , 4th & 5th rows results in 1st, 2nd 6th rows in last 2 columns [ Paid status & commission ].
1st while results coming from Database 1 & 2nd while results are coming from Database 2 with table [order_details]
$stmt = $user_home->runQuery("SELECT * FROM order_details");
$stmt->execute(array(":uid" => $_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute();
$i = 0;
foreach($order as $orderData)
{
$k = 0;
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
/* 1st while */
while ($k < count($orderitemsarray))
{
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details");
$stmtorders->execute(array(":dorder_id" => $orderData['entity_id']));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
$dorderStatus = $roworders['dpaid_status'];
$productdetail = Mage::getModel('catalog/product')->load($orderitemsarray[$k]);
$designer_id = $productdetail->getDesignerID() ;
if($accountType == "admin")
{
$designerName = getDesignerName($productdetail->getDesignerID()) . " -(" . $productdetail->getDesignerID() . ")";
$responce[] = array(
$orderData->getIncrementId() ,
$orderitemsarray[$k],
$productdetail->getName() ,
$designerName,
$orderData['status'],
$data['dpaid_status'],
$data['commission'],
$sDate
);
}
}
$k++;
$i++;
}
/* 2nd while */
while($data = $stmt->fetch())
{
$responce[] = array(
$data['dorder_id'],
$data['dpaid_status'],
$data['commission']
);
$k++;
}
}
I tried below code , but it results as below image - means only 2 rows displayed instead of 23 rows....
while (($k < count($orderitemsarray)) && ($data = $stmt->fetch()))
Full page looks as below :
I am new to php world & tried lot before posting here....
The thing is whenever you use empty brackets [] an index is automatically assigned which is equal to the next available numeric value and your data ends up in a next position so correct index is equired to solve this issue .
In while (($k < count($orderitemsarray)) && ($data = $stmt->fetch()))
If either of condition fails then loop ends and your $data probably has only three entries it's showing only that many even though $orderitemsarray has many more , i am not sure but you can prolly replace while with if statement and change index like this to make those stuff append on same row
$indx=0;
foreach($order as $orderData)
{
$k = 0;
//.. Stufff
/* 2nd while */
if($indx == 0 || $indx == 1 || $indx == 5)
{
if($data = $stmt->fetch())
{
$size = count($responce); // get size from that get its last index
$responce[$size-1] = array(
$data['dorder_id'],
$data['dpaid_status'],
$data['commission']
);
$k++; //<-- not sure why it's here but doesn't matter may be some magento stuff?
}
}
$indx++
}
EDIT:sry my bad , ignore my last comment try this instead
$responce[$size-1] = array_merge($responce[$size-1] , array(
$data['dorder_id'],
$data['dpaid_status'],
$data['commission']
) );

Get the next and before words from a word

I have tb words in a database :
=====================
= id = kata = posisi
=====================
= 1 = you = 1 =
= 2 = should= 2 =
= 3 = eat = 3 9 20 =
etc
Column posisi shows the positions of words in a sentence, that can be has 2 or more position for every word that I separated their position with space in its coloumn. The table comes from indexing process for sentence :
You should eat two bananas before lunch and eat two before your dinner and then consume one banana. i eat banana
I wanna get 5 words before and 5 next words from a keyword.
for example I submit keyword and I will get result :
eat two bananas before lunch and eat two before your dinner
and
eat two before your dinner and then consume one banana. i
here's the code I've tried :
require_once 'connection.php';
function getPosition ($keyword) {
$key = strtolower($keyword);
$query = mysql_query("SELECT * FROM words WHERE kata = '$key' ") or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
$position = $row['posisi'];
}
return $position;
}
$key= 'And';
$and = getPosition($key);
$explode = explode (' ', $and);
foreach ($explode as $data => $datas){
for ($i = 1 ; $i < 6 ;$i++){
$nextdata[$i] = (int)$datas + $i;
$databefore[$i] = (int)$datas - $i;
$queryNext = mysql_query("SELECT kata FROM words WHERE posisi = '$nextdata[$i]' and posisi =$databefore[$i] ") or die(mysql_error());
while ($row = mysql_fetch_array($queryNext)) {
$position = $row['kata'];
}
//print_r($position);
}
}
But it doesn't work, maybe the problem is when it meet the column with has many position, it can't be read it. Please help me. Thank You :)

Counter inside while loop every X times increase

I'm not really sure how to work this question, but I currently have a while loop outputting <li></li>.
Let's say that there are 35 rows and I want the counter to increase every five times.
So the output would be something like this.
- 1 Name
- 1 Name
- 1 Name
- 1 Name
- 1 Name
- 2 Name
- 2 Name
- 2 Name
- 2 Name
- 2 Name
- 3 Name
- 3 Name
- 3 Name
- 3 Name
- 3 Name
- 4 Name and so on...
I've tried counting throughout the loop and comparing the number to see if it was less than five and if not then increasing it, but I know that's not correct. Just can't seem to figure out the best solution.
while ($stmt->fetch()) {
$HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";
}
To try to make this clearer...basically I would like to have a counter variable running. Starting at 1, but every fifth time through the while loop, I would like to increase this count variable by one.
$count = $rows = 0;
while ($stmt->fetch()) {
if ($rows % 5 == 0)
$count++;
$rows++;
$HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";
}
You could use array_fill() (psuedo code):
<?php
$li = "<li>Item</li>";
$row = array_fill(0, 5, $li);
$list = array_fill(0, 35, $row);
print_r($list);
?>
http://codepad.org/ETCv3GBK
As in:
$count = 0;
while ($stmt->fetch() && $count++) {
$HTML .= implode('', array_fill(0, 5, "<li data-id='$id' data-name='$name'>$count Name</li>"));
}
Another demo (ignite.io may not be working on save, though):
https://ignite.io/code/514a9bf5ec221ee821000005
for($i=1; $i <= 20; $i++){
$array[] = "Name " . $i;
}
$count = 1;
$output = 1;
for($i=0; $i < 20; $i++){
if($count++ < 5)
echo $output . ". " . $array[$i] . "<BR>";
else{
$count = 1;
echo $output++ . ". " . $array[$i] . "<BR>";
}
}
returns
Name 1
Name 2
Name 3
Name 4
Name 5
Name 6
Name 7
Name 8
Name 9
Name 10
Name 11
Name 12
Name 13
Name 14
Name 15
Name 16
Name 17
Name 18
Name 19
Name 20
$i=1
while ($stmt->fetch()) {
if($i%5==0){
$HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";
}
$i++;
}

Categories