PHP - search_array - php

I have one Multiple Array...
File "user.php" --> imports the data from the "zebra_output_input.json" File and outputs a Zebra-Style Table with a list of all users and projects. One user can have more then one project, so it can have more then one line of text in the table (more then one array).
I have a sessions assigned to different users ("$loggedUser = $_SESSION["user"];") after the successful login, so I should now be able to filter the output so that only the data (lines of text - array) that matters for each user shows up.
Something like: first two lines (Arrays 0 and 1) gets User1, second one goes to the User2 ... last two ones for User5.
There is no databank involved in preprocessing the data. Right now, every user has its own JSON file (like it would be if the databank would give me the results). That's a bit impractical in this case since there is a project list for all users + one extra list for each and every user.
Some way to do it?
Array:
[{"Nr":"146","Kuerzel":"COUVERTIC","Projekttitel":"Arbeiten Output Management","Kunde":"COUVERTI","User":"User1"},{"Nr":"147","Kuerzel":"CEBILL","Projekttitel":"Vom PDF zur eRechnung","Kunde":"COUVERTI","User":"User1"},{"Nr":"157","Kuerzel":"KALAIDOS","Projekttitel":"Kurse bei Kalaidos","Kunde":"KFS","User":"User2"},{"Nr":"158","Kuerzel":"LPCH","Projekttitel":"Einsatz Harald M\u00fcller als Syst. Eng & W'Inform","Kunde":"LP","User":"User3"},{"Nr":"152","Kuerzel":"INFONOVA","Projekttitel":"PrintMachine","Kunde":"NEOPOST","User":"User4"},{"Nr":"1","Kuerzel":"AB","Projekttitel":"Allgemeine B\u00fcroarbeiten","Kunde":"INTERN","User":"User5"},{"Nr":"2","Kuerzel":"KA","Projekttitel":"Krank, Arzt","Kunde":"INTERN","User":"User5"}]
Processing file:
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<title>unbenannt</title>
<style>
table {background-color:white;}
th {background-color:#58ACFA;}
.cssEven {background-color:#E0ECF8;}
.cssOdd {background-color:#b8d3ef;}
</style>
</head>
<body>
<br><br>
<h1><img class="fehleranimation" src="../img/key36.png"> Willkommen im geschützten Bereich '<?= $_SESSION["user"]?>'.</h1>
<br><br>
<table>
<tr>
<th width="50" align="right">Nr</th>
<th width="150" align="left">Kuerzel</th>
<th width="350" align="left">Projekttitel</th>
<th width="150" align="left">Kunde</th>
<th width="100" align="center">User</th>
</tr>
<?php
$loggedUser = $_SESSION["user"];
//$userfile = file_get_contents('projekte_'.$loggedUser.'.json');
$userfile = file_get_contents('zebra_output_input.json');
$jsonarray = json_decode($userfile);
$index = count($jsonarray);
for ($i = 0; $i < $index; $i++) {
$style = "cssOdd";
//$_SESSION['user'] = $jsonarray[$i]->User;
if ($i % 2 != 0) {
$style = "cssEven";
}
if($loggedUser === $jsonarray[$i]->User) {
echo
'<tr class="'.$style.'">
<td align="right">'. $jsonarray[$i]->Nr.' </td>
<td>'. $jsonarray[$i]->Kuerzel.' </td>
<td>'. $jsonarray[$i]->Projekttitel.' </td>
<td>'. $jsonarray[$i]->Kunde.'</td>
<td align="center">'. $jsonarray[$i]->User.' </td>
</tr>';
}
}
?>
</table>
</body>
</html>
Edited

Some points to consider.
If you are fetching the data from the database do the filtering there and no need to fetch all the data and then filter in php.
If you are reading this array from some other source, like a file maybe, then just loop through each one of the array and check if the user matches the user stored in $_SESSION.

I think you're looking for an identifier.
You need to match the $_SESSION['user'] with the corresponding
$jsonarray[$i]->User.
Hope it helps!
$loggedUser = $_SESSION["user"];
$userfile = file_get_contents('projekte_'.$loggedUser.'.json');
$jsonarray = json_decode($userfile);
$index = count($jsonarray);
for ($i = 0; $i < $index; $i++) {
$style = "cssOdd";
if ($i % 2 != 0) {
$style = "cssEven";
}
if($loggedUser === $jsonarray[$i]->User) {
echo
'<tr class="' . $style . '">
<td align="center">' . $jsonarray[$i]->User . ' </td>
<td align="right">' . $jsonarray[$i]->Nr . ' </td>
<td>' . $jsonarray[$i]->Kuerzel . ' </td>
<td>' . $jsonarray[$i]->Projekttitel . ' </td>
<td>' . $jsonarray[$i]->Kunde . '</td>
</tr>';
}
}

Related

Ordering data in the table

I have three tables created by uploaded data from the previous file. I would like to insert data in defined places, so that each service is a separate record in the table and has a separate quantity and amount assigned.
My php function:
function listService()
{
$service_chcecked = $_POST['service_chcecked'];
$quantity = $_POST['quantity_chcecked'];
$net_price = $_POST['net_price_chcecked'];
for ($x = 0; $x < count($service_chcecked); ++$x) {
echo '<tr><td>id:' . $x . '</td><td>name:' . $service_chcecked[$x] . '</td>';
for ($y = 0; $y < count($net_price); ++$y) {
echo '<td>price:' . $net_price[$y] . '</td>';
for ($z = 0; $z < count($quantity); ++$z) {
echo '<td>quantity:' . $quantity[$z] . '</td>';
};
};
echo '</tr>';
}
}
And my html place:
<div class='services'>
<table>
<tr>
<th><span>NO.</span></th>
<th><span>Service name</span></th>
<th><span>Net price</span></th>
<th><span>Quantity</span></th>
</tr>
<?php listServiceName(); ?>
</table>
</div>
Now it displays to me this way, with repeated data at the end :/
broken table
That's because you are nesting your for loops. You create the <tr> and the "id" and "name" <td> for each item in service_chcecked. Then you create a "price" <td> for each service_chcecked * net_price_chcecked. And your 3rd nested loop creates a "quantity" column for each service_chcecked * net_price_chcecked * quantity_chcecked. That's why you end up with that broken table. It depends on how you receive the POST data, but if your three arrays always have the same length, you could do it all in one loop:
function listService()
{
$service_chcecked = $_POST['service_chcecked'];
$quantity = $_POST['quantity_chcecked'];
$net_price = $_POST['net_price_chcecked'];
for ($x = 0; $x < count($service_chcecked); ++$x) {
echo '<tr><td>id:' . $x . '</td><td>name:' . $service_chcecked[$x] . '</td>';
echo '<td>price:' . $net_price[$x] . '</td>';
echo '<td>quantity:' . $quantity[$x] . '</td>';
echo '</tr>';
}
}
Its hard to understand whats happening but less is more and try not to mix your data & html inside your function its going to confuse you later on.
<?php
$services = $_POST['service_checked'];
$qtys = $_POST['quantity_checked'];
$prices = $_POST['net_price_checked'];
?>
<div class='services'>
<table>
<tr>
<th>NO.</th>
<th>Service name</th>
<th>Net price</th>
<th>Quantity</th>
</tr>
<? foreach($services as $k=>$service){?>
<tr>
<td><?=$k?></td>
<td><?=$service?></td>
<td><?=$qtys[$k]?></td>
<td><?=$prices[$k]?></td>
</tr>
<? }?>
</table>
</div>

How to display multiple rows one after the other repeating a sequence depending on how many rows I get?

My idea is to create a Q&A section under a product profile, just like on eBay or Amazon or whatever. The idea is to send a question and then get the owner of the article to reply.
The table has these columns: pid (product ID), id (question ID), question, answer, date (date posted), username.
So if I post a question, I get the ID of the product in which I'm posting and create a question. The the owner just sends the answer to the row that matches the question.
Here's my PHP code to retrieve all the info from that table:
$qanda = '';
$link = mysql_connect("localhost", "youknowwhat", "youknowwhat");
mysql_select_db("youknowwhat", $link);
$qandaq = mysql_query("SELECT * FROM questions WHERE id='$id2' ORDER BY date", $link);
$count = mysql_num_rows($qandaq);
if($count >= 1){
while($rows = mysql_fetch_array($qandaq)){
$date = $rows['date'];
$q = $rows['question'];
$a = $rows['answer'];
$usrname = $rows['username'];
}
$qanda .= '<div id="answers" align="center">
<table cellspacing="0" align="center">
<tr align="center">
<td width="200">' . $date . '</td>
<td rowspan="2" width="400"><strong>' . $q . '</strong><br>' . $a . '</td>
<td width="200">Delete</td>
</tr>
<tr align="center">
<td>' . $usrname . '</td>
<td>Report</td>
</tr>
</table>
</div>';
} else {
$qanda = '<div id="answers" align="center">
No questions for this product.
</div>';
}
Now... what you see as a table in the variable $qanda I want to repeat it over and over again but displaying different row data but the concatenation isn't working and I can only get the last row to be displayed. I just can't seem to find out why this isn't working! Am I missing something?
All you have to do is append your divs (.=) while you're inside the while loop that mysql_fetch_array() rows.
Then you'll have a new div for each row your database returns, and you can populate it easily.
$qanda = '';
while($rows = mysql_fetch_array($qandaq)){
$date = $rows['date'];
$q = $rows['question'];
$a = $rows['answer'];
$usrname = $rows['username'];
$qanda .= '<div id="answers" align="center">
<table cellspacing="0" align="center">
<tr align="center">
<td width="200">' . $date . '</td>
<td rowspan="2" width="400"><strong>' . $q . '</strong><br>' . $a . '</td>
<td width="200">Delete</td>
</tr>
<tr align="center">
<td>' . $usrname . '</td>
<td>Report</td>
</tr>
</table>
</div>';
}

Changing column in HTML table to hyperlink

for ($i=0; $i<=$lines; $i++)
{
//get each line and exlplode it..
$part = explode('|', $file[$i]);
//now start printing ..
echo'<tr>
<td width="20%">'.$part[0].'</td>
<td width="20%">'.$part[1].'</td>
<td width="20%">'.$part[2].'</td>
<td width="20%">'.$part[3].'</td>
<td width="20%">'.$part[4].'</td>
</tr>';
}
This is my code, it read's from a text file and explode in table, but I have a little problem here cause this one needs to be link.
<td width="20%">'.$part[2].'</td>
.$part[2]. is just a word from file but it has query like www.somesite.com/?q= There at the end I need to have that
word from file
that kind of code did not work for me
<td width="20%"> <a herf='www.somesite.com/?q=''.$part[2].'> '.$part[2].' </a> </td>
I realy need some help with this...
<?php
//first, get the file...
$file = file('req.txt');
//now count the lines ..
$lines = count($file);
//start the table here..
echo'<table border="2" width="100%">';
echo'<tr>
<td width="20%">Naslov</td>
<td width="20%">Vrsta</td>
<td width="20%">IP</td>
<td width="20%">Dodano (DD.MM.YY - HH.MM)</td>
<td width="20%">Status</td>
</tr>';
//start the loop to get all lines in the table..
for ($i=0; $i<=$lines; $i++) {
//get each line and exlplode it..
$part = explode('|', $file[$i]);
//now start printing ..
echo'<tr>
<td width="20%">'.$part[0].'</td>
<td width="20%">'.$part[1].'</td>
<td width="20%">'.$part[2].'</td>
<td width="20%">'.$part[3].'</td>
<td width="20%">'.$part[4].'</td>
</tr>';
}
//close the table so HTML wont suffer :P
echo'</table>';
?>
This should produce this but ip column need to be link...
I think vprintf() is your friend.
<?php
$fmt = '<tr>
<td>%1$s</td>
<td>%2$s</td>
<td>%3$s</td>
<td>%4$s</td>
<td>%5%s</td>
</tr>';
for ($i=0; $i<=$lines; $i++)
{
// get each line and explode it..
$part = explode('|', $file[$i]);
// now start printing ..
vprintf($fmt, $part);
}
And put the width="20%" into your CSS.
I solve it alone with changing some values in input script "file writer"
$savestring = $title . "|" . $genre . "|<a href=http://www.example.com/ip?ip=" . $ip . ">" . $ip . "|" . $date . "|Za Naložit \n";
it works now ty anyway :)

Order list/ while loop php issue

I have put together a basic order list for admin users in php for checking order contents placed by logged in users.
The aim of this script is to retrieve the order details (item, quantity, price) as well as the user’s first name and surname (where ‘Order for:’ is).
The script below does everything ok in that it retrieves the order (and orders if there are more than one) and it’s/their item, quantity and price.
However, it doesn’t display the user’s name and surname.
I know the problem is that where I am trying to display the name is outside the while loop but Im a little stuck in where it should sit. Any suggestions? Code is below:
<?php
$page_title = 'View Individual Order';
include ('includes/header.html');
// Check for a valid user ID, through GET or POST.
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
{ // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
{ // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/header.html');
exit();
}
?>
<h1>Order Details</h1>
<?php
require_once ('database.php'); // Connect to the db.
// Retrieve the user's, order and product information.
$query = "SELECT us.users_id, us.users_sales_id, us.users_first_name, us.users_surname, us.users_dealer_name,
ord.order_id, ord.users_id, ord.total, ord.order_date,
oc.oc_id, oc.order_id, oc.products_id, oc.quantity, oc.price,
prd.products_id, prd.products_name, prd.price
FROM users AS us, orders AS ord, order_contents AS oc, products AS prd
WHERE ord.order_id=$id
AND us.users_id = ord.users_id
AND ord.order_id = oc.order_id
AND oc.products_id = prd.products_id
";
$result = mysql_query ($query) or die(mysql_error());
if (mysql_num_rows($result)) { // Valid user ID, show the form.
echo '<p>Order for:<strong>' . $row[2] . ' ' . $row[3] . ' </strong> </p>
<table border="0" style="font-size:11px;" cellspacing="1" cellpadding="5">
<tr class="top">
<td align="left"><b>Product</b></td>
<td align="center"><b>Price</b></td>
<td align="center"><b>Qty</b></td>
</tr>';
$bg = '#dddddd'; // Set the background color.
while($row = mysql_fetch_array($result, MYSQL_NUM)) { // WHILE loop start
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row[15] . '</td>
<td align="center">' . $row[13] . ' pts</td>
<td align="center">' . $row[12] . '</td>
</tr>';
echo '';
}// end of WHILE loop
echo '</table>
<p> Here:</p>
<br><br>
<p> << Back to Orders</p>
<p> </p>
<p> </p>
<p> </p>
';
} else { // Not a valid user ID.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
}
mysql_close(); // Close the database connection.
?>
<p>Footer here</p>
<?php
include ('./includes/footer_admin_user.html'); // Include the HTML footer.
?>
One way you could do it is grab the row first, and then use a do/while loop instead of just a basic while loop. Like this:
if (mysql_num_rows($result)) { // Valid user ID, show the form.
/*********** I added this line ***********/
$row = mysql_fetch_array($result, MYSQL_NUM);
echo '<p>Order for:<strong>' . $row[2] . ' ' . $row[3] . ' </strong> </p>
<table border="0" style="font-size:11px;" cellspacing="1" cellpadding="5">
<tr class="top">
<td align="left"><b>Product</b></td>
<td align="center"><b>Price</b></td>
<td align="center"><b>Qty</b></td>
</tr>';
$bg = '#dddddd'; // Set the background color.
/*********** I changed this from a while loop to a do-while loop ***********/
do { // WHILE loop start
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row[15] . '</td>
<td align="center">' . $row[13] . ' pts</td>
<td align="center">' . $row[12] . '</td>
</tr>';
echo '';
} while($row = mysql_fetch_array($result, MYSQL_NUM)); // end of WHILE loop
It looks like the problem is when you're trying to display the user's name:
echo '<p>Order for:<strong>'.$row[2].' '.$row[3]
The $row variable doesn't exist yet. Not seeing your database or the result from your database query, my guess is that the user's name is repeated next to every single item in their order, so it might be as simple as just starting the WHILE loop, and checking to see if you've printed their name yet:
$lastUser = NULL;
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
if ($row[0] !== $lastUser) {
if (isset($lastUser)) {
// finish up the report for the previous user
}
// echo the stuff for the current user's name
$lastUser = $row[0];
}
// go on echo-ing their order information
}
// after the while loop is over,
// close up the last user's report
But like I said, this is just a guess, and might be totally off.
The problem is that you tried to access $row[2] and $row[3] before mysql_fetch_array(). Since you are already echo'ing HTML tags, why don't you "buffer" your output first like this?:
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
$order = '<tr bgcolor="' . $bg . '">
<td align="left">' . $row[15] . '</td>
<td align="center">' . $row[13] . ' pts</td>
<td align="center">' . $row[12] . '</td>
</tr>';
$orders[$row[2] . " " . $row[3]][] .= $order;
}
Then do a second foreach loop for the $orders
foreach($orders as $name => $orderList)
{
echo "Order for: $name";
echo "<table ...>";
foreach($orderList as $order)
{
echo $order;
}
echo "</table>";
}

Unexpected output when comparing database column to variable

I have code which retrieves information about players from a MySQL database. I want to apply a special case to the HTML output if their ranking changes. I want it to look like this: http://i27.tinypic.com/f406tz.png
But i cant get it to be like i want, instead it prints the rank on every row:
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = "<tr><td> </td>\n";
}
echo " <td>$g->name</td></tr>\n";
}
What I want:
<tr>
<td>One</td>
<td>Kraven the Hunter</td>
</tr>
<tr>
<td> </td>
<td>Kull the Conqueror</td>
</tr>
<tr>
<td> </td>
<td>Zazi The Beast</td>
</tr>
<tr>
<td>Vice-leader</td>
<td>Igos du Ikana</td>
</tr>
<tr>
<td> </td>
<td>Saint Sinner</td>
</tr>
<tr>
<td> </td>
<td>Midvalley the Hornfreak</td>
</tr>.......................
What I get:
<tr><td>One</td>
<td>Tester</td></tr>
<tr><td>One</td>
<td>Kraven the Hunter</td></tr>
<tr><td>One</td>
<td>Kull the Conqueror</td></tr>
<tr><td>One</td>
<td>Zazi The Beast</td></tr>
<tr><td>Vice-Leader</td>
<td>Midvalley the Hornfreak</td></tr>
<tr><td>Vice-Leader</td>
<td>Saint Sinner
</td></tr>
<tr><td>Vice-Leader</td>
<td>Igos du Ikana</td></tr>
$old_rank is never equal to $g->rankname because the way you are setting $old_rank, it will contain HTML tags, and the $g->rankname that you get from the DB will never have HTML tags.
Try changing your if statement to something like this:
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = $g->rankname;
} else {
echo "<tr><td> </td>\n";
}
It prints the rank name if it's a new rank name, else it prints empty space.
The following (notwithstanding typos) separates out the display logic from the database loop. This has the advantages:
- You don't need to depend on the order of the results returned
- You don't need to maintain dodgy logic (like 'old_rank')
- You can display them more nicely (with a rowspan for repeated ranks
I believe the total code is more compact too.
// fill ranks array
$ranks = array();
while ( $g = mysql_fetch_object($q) ) {
if ( !in_array($g->rankname, $ranks) ) {
$ranks[htmlentities($g->rankname)] = array();
}
$ranks[$g->rankname][] = htmlentities($g->name);
}
// do other program logic here
// end of program
?>
<!-- display the page -->
<table>
<tr>
<th>Rank</th><th>Users</th>
</tr>
<?php foreach($ranks as $rankName => $userList): ?>
<tr>
<td rowspan="<?php echo (string)sizeof($userList); ?>">
<?php echo $rankName; ?>
</td>
<td> <?php echo implode('</td></tr><tr><td>', $userList); ?> </td>
</tr>
<?php endforeach; ?>
</table>
I prefer breaking things up a bit more than that. Keeping things separate makes it easier to modify. This should work.
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
echo '<tr>' . "\n";
echo '<td>';
if ($g->rankname != $old_rank) {
$old_rank = $g->rankname;
echo $old_rank;
} else {
echo ' ';
}
echo '</td>';
echo '<td>' . $g->name . '</td>' . "\n";
echo '</tr>' . "\n";
}

Categories