I have been doing a lot of work in learning how to return multidimensional arrays dynamically- but what I can't seem to figure out is how to nest them.
I have two tables, each has the identical format: ID, name.
Table one: SSC
- sscid
- sscname
Table two: SRV
- srvid
- srvname
What I am trying to do is print all of the items in table two under EACH item in the table one list.
The table one items are the headers, the table two items are returned as a checkbox (with the srvid as the value) and label(srvname).
I can get it to all print together, but it is a. one giant list of results and it's in a
| checkbox | table 1: name | table 2: name | format.
Not pretty at all (although it is progress for me to get this far).
After I run my query and get the result, my code looks like this:
Now, I've had a few additional thoughts about the design of the concept re:the database tables go, but everything I read indicates that they really need to be on their own tables, and they should be able to be referenced by the key from one table and the key from the other (eventually ended up in a joint table with user ID references) Because they are numerically indexed, I don't know why this would be an issue for me; however I simply can't seem to get this to work properly.
I should mention that when I alter the code to try to make the ssc_name span 2 cols and make it more like a header, it returns a header row for each checkbox/srv row, instead of for all of the checkbox/srv rows.
if($result) {
echo '<table border="1" align="center" cellspacing="3" cellpadding="3" width="300">
<tr><th colspan="2"><h3>Options</h3></th></tr>
<tr><td></td><td align="left"><b>Services</b></td></tr>';
$numfields = mysql_num_fields($result);
$data = array();
$flist = array();
for($i=0;$i<$numfields;$i++)$flist[] = mysql_field_name($result,$i);
$data[0] = $flist;
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
echo '<tr><td colspan="2" align="center"><b>' . $row['ssc_name'] .'</b><td></tr>
<tr><td align="center"><input type="checkbox" value="'. $row['ssv_id'] .'" / </td>
<td align="left">' . $row['ssvname'] . '</td>
</tr>';
}
echo '</table>';
}
Can anyone help me figure this out, please?
You are missing a > on this line
<tr><td align="center"><input type="checkbox" value="'. $row['ssv_id'] .'" / </td>
Should be
<tr><td align="center"><input type="checkbox" value="'. $row['ssv_id'] .'" /></td>
Something you might be able to pick up on with better formatting...
<?php
if ($result) {
echo <<<EOD
<table border="1" align="center" cellspacing="3" cellpadding="3" width="300">
<tr>
<th colspan="2"><h3>Options</h3></th>
</tr>
<tr>
<td></td>
<td align="left"><b>Services</b></td>
</tr>
EOD;
while ($row = mysql_fetch_assoc($result)) {
echo <<<EOD
<tr>
<td colspan="2" align="center"><b>{$row['ssc_name']}</b><td>
</tr>
<tr>
<td align="center"><input type="checkbox" value="{$row['ssv_id']}" /></td>
<td align="left">{$row['ssvname']}</td>
</tr>
EOD;
}
echo '</table>';
}
?>
And I'm not really sure what business any of those arrays have being in there.
Related
I have the following code for the echo of an HTML table. In the table is a delete button. I want to delete the user's input from the database when the user hits the delete button. In the database there are more rows from the same user with different values and these are also shown with this code. How do I delete the specific input from one output (the one where the user hits delete)? I've been at it all day and tried a lot of things but can't find a way to do it. I'm just a beginner..
$sql = "SELECT publicaties.pub_Id,publicaties.userid,publicaties.titel,publicaties.type,publicaties.linkwerk,publicaties.linkuitgever,publicaties.beschikbaar,publicaties.hierbewerkt, users.username,users.userid FROM publicaties, users WHERE publicaties.userid=users.userid AND publicaties.userid='$user' ORDER BY pub_Id DESC LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
if ($row["hierbwerkt"] ==1)
echo $row["hierbewerkt"];
else
{
echo" ";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "
<table width='415' border='0' class='tablepublicaties'>
<tr>
<td rowspan='2' bgcolor='#1E1E1E'> </td>
<td rowspan='2' bgcolor='#1E1E1E'><span class='user-imagelarge'><img src='Images/nopicture.png' alt='nopicture' width='273' height='381' class='user-imagelarge'></span></td>
<td valign='middle' nowrap bgcolor='#1E1E1E'><span class='linkkleur'>".$row["hierbewerkt"]."</td>
<td valign='middle' bgcolor='#1E1E1E'>".$row["username"]."</td>
</tr>
<tr>
<td valign='bottom' bgcolor='#1E1E1E'>Titel</td>
<td valign='middle' bgcolor='#1E1E1E'><span class='sterrenkleur'>".$row["titel"]."</span></td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td nowrap bgcolor='#1e1e1e'> </td>
<td bgcolor='#1E1E1E'>Type</td>
<td bgcolor='#1E1E1E'>".$row["type"]."</td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'>Publicatie</td>
<td bgcolor='#1E1E1E'><a href='$row[linkwerk]'> ".$row["linkwerk"]."</a></td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'>Uitgever</td>
<td bgcolor='#1E1E1E'><a href='$row[linkuitgever]'> ".$row["linkuitgever"]."</a></td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td nowrap bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'>Beschikbaar</td>
<td bgcolor='#1E1E1E'>".$row["beschikbaar"]."</td>
</tr>
<tr>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'><input type='image' class='backgroundgreyfotoos' src='Images/Icons/crossorangebutton.png' alt='Submit Form' width='15' height='15' border='0'/ ></td>
<td bgcolor='#1E1E1E'><img src='Images/lijntransparant.png' width='70' height='1' alt='lijn'></td>
<td bgcolor='#1E1E1E'><img src='Images/lijntransparant.png' width='224' height='1' alt='lijn'></td>
</tr>
</table>
<br>";
}
}
mysql_close($conn);
Your PHP-Script has to handle this deletion. For example you can define a GET-Parameter called action which defines what should be done:
$action = ( isset( $_GET['do'] ? $_GET['do'] : 'index' );
if( $action == 'index') {
// Print your Table
}elseif( $action == 'delete' ) {
// Send a SQL-Query to the database-server like 'DELETE FROM TABLE WHERE
// DELETE FROM publicaties WHERE publicaties.pub_Id = $pub_id [...]
}
For the deletion, you can link to yourscript.php?do=delete&pubId=123 so that the entry you've passed by pubId (accessable by $_GET['pubId']) gets deleted. The advanced version would be using ajax. Its more user-friendly and you can safe ressources because it's not necessary to reload the entire page. You keep on the table-page, make a ajax-request to yourscript.php?do=delete&pubId=123 in the background. When it was successfull, you can delete the table-row by manipulating the DOM. A library like jQuery would make those thinks much easier.
But as beginner it will be a good idea to skip the ajax-part initially and do it like the simple way I explained first. This is easier and you don't need any Javascript which is necessary for ajax.
As a second tip you should get information about SQL-Injections. Building dynamic SQL-Querys like
$query = 'DELETE FROM table WHERE id = ' . $_GET['id'];
is very insecure because every visitor can manipulate the Query by passing valid SQL as the parameter. HTTP-POST is not even better, it's only a bit more difficult because POST-Data is send in the HTTP-Body. You should at least filter input from outside by escaping it. Numeric values can also be casted like (int)$_GET['id']. But the best way is to use prepared statements because by manual escaping you may forget to escape correctly which can result in a security risk. By using prepared statements, you're not inserting variable data like from GET or POST directly in the query-string. Instead you're using placeholders, which gets replaced later. The replacing with these values is done by php automatically, so that you can't forget the escaping.
<?php
// is the page requested in the post method?
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// if we have received an x coordinate from the delete-button then it is pressed.
if(isset($_POST['delete_x']))
{
// make your delete query here
echo 'Now its time to delete record with id=' . $_POST['id'];
// if everything is working i recommand that you reload the page in the normal GET method.
// Then you need to uncomment the two following lines
//header('Location: ' . $_SERVER['SCRIPT_NAME']);
//exit;
}
// dump the $_POST array. Just for learning or debugging
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
// dummy variabele, comes normal from your database
$row['id'] = 12;
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<input type="image" src="cross.png" name="delete">
</form>
The entire HTML form (last 4 lines) needs to be rendered for each row in the table!
I am trying to populate a table with the query results I receive from a function. I am able to populate the table however my table header keeps repeating in each row. Is the any way I can stop this from happening?
You need to put table header outside of your while loop:
echo '<table border="1" style="width:100%">';
echo '<tr><td> Dep</td><td> Style</td> <td> Colour</td><td> Description</td> <td> Price</td></tr>';
while($row = mysql_fetch_assoc($get5star)){
echo'<tr><td> '.$row['departmentid']. '</td><td>'.$row['style']. '</td> <td> '.$row['colour']. '</td> <td> '.$row['description']. '</td> <td>'.$row['price'].'</td> </tr>';
}
echo '</table>';
because your table's head part is inside of loop
you should do like this
for example we get book names and writer's name :
<table>
<thead>
<th>book></th>
<th>writer</th>
</thead>
<tbody>
<?php
while($row = mysql_fetch_assoc($get5star)){
echo'
<tr><td> '.$row['book']. '</td><td>'.$row['writer']. '</td> </tr>
';
}
?>
</tbody>
</table>
however my table header keeps repeating in each row
That's because it's inside the loop. The general structure of a loop is:
(stuff that happens once)
while (some condition) {
(stuff that happens many times)
}
(stuff that happens once)
If the UI table header should happen only once (which it should), then it needs to go in one of those (stuff that happens once) locations. In this case, the first one:
// happens once
echo '<table border="1" style="width:100%">';
echo '<tr><td> Dep</td><td> Style</td> <td> Colour</td><td> Description</td> <td> Price</td></tr>';
while($row = mysql_fetch_assoc($get5star)){
// happens many times
echo'<tr><td> '.$row['departmentid']. '</td><td>'.$row['style']. '</td> <td> '.$row['colour']. '</td> <td> '.$row['description']. '</td> <td>'.$row['price'].'</td> </tr>';
}
// happens once
echo '</table>';
You have the table head code inside the loop:
while($row = mysql_fetch_assoc($get5star)){
echo '<tr><td> Dep</td><td> Style</td> <td> Colour</td><td> Description</td> <td> Price</td></tr>';
You should put that outside the while loop, like this:
echo '<table border="1" style="width:100%">';
echo '<tr><td> Dep</td><td> Style</td> <td> Colour</td><td> Description</td> <td> Price</td></tr>';
while($row = mysql_fetch_assoc($get5star)){
echo'<tr><td> '.$row['departmentid']. '</td><td>'.$row['style']. '</td> <td> '.$row['colour']. '</td> <td> '.$row['description']. '</td> <td>'.$row['price'].'</td> </tr>';
}
echo '</table>';
Worth noticing that you shouldnt use mysql , to access the Database. Use PDO ( i prefer them ) or mysqli .
My code:
<?php
require_once('auth.php');
require_once('connection.php');
$value1 = $_POST['value1'];
$qry=mysql_query("SELECT * FROM table WHERE (`value1` LIKE '%".$value1."%')") or die(mysql_error());
if(mysql_num_rows($qry) > 0){
while ($result = mysql_fetch_array($qry)){
$value1 = $result['value1'];
$value2 = $result['value2'];
}}else{die ("can't find ".$value1."");}
?>
<br />
<table width="700" border="0">
<tr>
<td colspan="2" align="center"><strong>Info for <?php echo $value1; ?></strong></td>
</tr>
<tr>
<td width="100">Some text:</td>
<td width="590"><?php echo $value2;?></td>
</tr>
The code is working great when there is only one row with the same value of value1. If there are 2,3 or more rows with the same value for value1 the script displays only the values from the last row in my table found with the queried value. I want it to display separate tables with entries from all queried rows.
I've searched online for help, but all I could find is how to retrieve the values from my database, nothing helpful for me
you should move your html block to inside the while loop. try this
<br />
<table width="700" border="0">
<?php
if(mysql_num_rows($qry) > 0){
while ($result = mysql_fetch_array($qry)){
$value1 = $result['value1'];
$value2 = $result['value2'];
?>
<tr>
<td colspan="2" align="center"><strong>Info for <?php echo $value1; ?></strong></td>
</tr>
<tr>
<td width="100">Some text:</td>
<td width="590"><?php echo $value2;?></td>
</tr>
<?php
}}else{die ("can't find ".$value1."");}
?>
</table>
I moved the <table> code to before the while loop, moved the table rows to inside the loop and the table close tag after the loop. this way you get all rows.
If you don't want to show the table at all if there is no rows you can move the <table ..> and </table> tags to inside the if statement block.
Edit:
if(mysql_num_rows($qry) > 0){
?>
<br />
<table width="700" border="0">
<?php
while ($result = mysql_fetch_array($qry)){
$value1 = $result['value1'];
$value2 = $result['value2'];
?>
<tr>
<td colspan="2" align="center"><strong>Info for <?php echo $value1; ?></strong></td>
</tr>
<tr>
<td width="100">Some text:</td>
<td width="590"><?php echo $value2;?></td>
</tr>
<?php
}
echo '</table>';
}else{die ("can't find ".$value1."");}
?>
You're assigning values from the returned rows to $value1 and $value2. So each iteration of the loop replaces the last stored values in these variables.
This will effectively only give you the last row values found (last values assigned to the variables.)
You either need to push these values into a collection/array and re-loop through them to build your table, or put the table code in the initial loop.
I'm trying to print out a list of products on a page. This is cake so far..
However Some of my items share names but have different attributes.
Example would be like...:
product:
keyboard
keyboard
size:
25 inches
23 inches
color:
red
blue
My table looks something like this:
id, product, size, color, so on...
So my .php I'm doing my query and print from looks something like this
<div id="accordion">
<?php
$letter = $_GET['letter'];
//echo "$id";
include("database.php");
$result = mysql_query("SELECT UPPER(product) AS upperName, PRODUCTS.* FROM PRODUCTS WHERE product LIKE '$letter%' ORDER BY UPPER(product) ");
$prodName = "";
while($row = mysql_fetch_array($result))
{
if ($row['upperName'] != $prodName)
{
print('<div style="background-color:#666; padding-bottom:25px; margin-bottom:25px;">');
print ("<h1>" . "$row[product]" . "</h1>");
}
print ("$row[ndc]" . "<br />");
print ("$row[size]" . "<br />");
print ("$row[strength]" . "<br />");
print ("$row[imprint]" . "<br />");
print ("$row[form]" . "<br />");
print ("$row[color]" . "<br />");
print('</div>');
$prodName = $row['upperName'];
}
mysql_close($linkID);
?>
</div>
My problem comes from trying to style the attributes..
Do you see that /div tag?
I want to style that stuff within an accordion however that stuff repeats for each product that shares the same name in that accordion. So if i include the div there, it prints out for 3 times with the same name 3 end div tags (hence breaking all my html nooo!!)
Is there a way to maybe loop? or use some kind of conditional logic to print that top stuff, once for the product name that all the products share, then the loop and print all the different attributes, then when each attribute is finished, to then include my closing html?
So if i have 6 products and half are named "keyboard", and the other half are named "shoes"
could i get it to print out
TABLE
product name: KEYBOARD
table for all my attributes
end table for all my attributes
end TABLE
TABLE
product name: SHOES
table for all my attributes
end table for all my attributes
end TABLE
That way i can style all my attributes.
I'm really sorry if this isn't correctly explained I'm still learning.
Any help is appreciated!
Extra stuff that you may not need to figure out my problem just an example of a table i'm printing to and why the way the attributes print is a problem. the 1-2-3-4-5-6-7-8-9 are data for the attributes.
<table cellspacing="0" cellpadding="0" border="0" width="649">
<tr>
<td width="180" height="10" valign="top"></td><td width="36" height="10" valign="top"></td><td width="433" height="10" valign="top"></td>
</tr>
<tr>
<td width="180" valign="top"><img src="images/slide1.gif" width="180" height="200" border="0" /></td>
<td width="36" valign="top"></td>
<td width="433" valign="top"><table cellspacing="0" cellpadding="0" border="0" width="433">
<tr>
<td valign="top"><span class="in-table-head">Name:</span></td>
<td valign="top"><span class="in-table-name">$row[name]</span></td>
</tr>
<tr>
<td valign="top"><span class="in-table-head">Therapeutic Category:</span></td>
<td valign="top"><span class="in-table-name">$row[therapeutic]</span></td>
</tr>
<tr>
<td colspan="2" valign="top"><span class="in-table-providers">Information for Providers</span></td>
</tr>
</table></td>
</tr></table>
<table cellspacing="0" cellpadding="0" border="0" width="649">
<tr>
<td><span class="in-table-att">NDC#:</span></td>
<td><span class="in-table-att">Strength:</span></td>
<td><span class="in-table-att">Size:</span></td>
<td><span class="in-table-att">Imprint:</span></td>
<td><span class="in-table-att">Form:</span></td>
<td><span class="in-table-att">Color:</span></td>
<td><span class="in-table-att">Shape:</span></td>
<td><span class="in-table-att">Pack Size:</span></td>
<td><span class="in-table-att">Rating:</span></td>
</tr>
</table>
<table cellspacing="0" cellpadding="0" border="0" width="649">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
Thank you again to anyone who looks at this problem!
stop matching by name but start using sku’s as a selector. that way you’re always spot on, no matter how many keyboards you have.
set up your pages to pass the sku instead of generic name.
otherwise you need to add more criteria to your where statement like dimensions, weight, color, price etc... to get ta reliable result.
-- Update --
An example.
page.php?product_type=keyboard
<?php
// set up database
$db = mysqli_connect("localhost", "user", "pass", "database_name");
// Just using mysql escape string, you should consider adding more securty checking to prevent injection
$producttype = mysql_real_escape_string($_GET['product_type']);
$result = $db->query("SELECT * FROM `products` WHERE `products`.`type`='$producttype'");
$features["width"][]
$features["height"][]
$features["color"][]
$features["whatever"][]
while ($row = $result->fetch_assoc())
{
$features["width"][] = $row["width"];
$features["height"][] = $row["height"];
$features["color"][] = $row["color"];
$features["whatever"][] = $row["whatever"];
}
// printing the features
echo "You have selected $producttype<BR>";
echo "The following widths can be selected<BR><UL>";
foreach($features["width"] as $width)
echo "<LI>$width</lI>";
echo "</UL><P>The following heights can be selected<BR><UL>";
foreach($features["heights"] as $height)
echo "<LI>$height</lI>";
echo "</UL><P>The following colors can be selected<BR><UL>";
foreach($features["colors"] as $color)
echo "<LI>$color</lI>";
echo "</UL><P>The following whatevers can be selected<BR><UL>";
foreach($features["whatevers"] as $whatevers)
echo "<LI>$whatevers</lI>";
echo "</UL>";
echo "have a nice day";
?>
I am making a php app to parse HTML contents. I need to store a certain table column in php variables.
Here is my code:
$dom = new domDocument;
#$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(0)->getElementsByTagName('tr');
$flag=0;
foreach ($rows as $row)
{
if($flag==0) $flag=1;
else
{
$cols = $row->getElementsByTagName('td');
foreach ($cols as $col)
{
echo $col->nodeValue; //NEED HELP HERE
}
echo '<hr />';
}
}
In each row, first col is the KEY, second is the VALUE. How to create key value pairs from the table and store them as arrays in php.
I tried many things but everytime I am just getting DOMElement Object() as value.
Any help is deeply appreciated...
HTML as requested:
<table align='center' border='0' cellpadding='0' cellspacing='0' style='border-collapse: collapse' width='780' height=100%>
<tr><td height=96% align=center><BR><BR>
<html>
<head>
</head>
<body style="background:url(uptu_logo1.gif); background-repeat:no-repeat; background-position:center">
<p align="center" style="font-size:18px"><span style='font-size:20px'>this text is unimportant gibberish that is not required by my app</span><br/><span style='font-size:16px'>this text is unimportant gibberish that is not required by my app</span><br/><u>B.Tech. Third Year Result 2009-10. this text is unimportant gibberish that is not required by my app</u></p>
<br/>
<table align="center" border="1" cellpadding="0" cellspacing="0" bordercolor="#E3DDD5" width="700" style="border-collapse: collapse; font-size: 11px">
<tr>
<td width="50%"><b>Name:</b></td>
<td width="50%">John Fernandes </td>
</tr>
<tr>
<td><b>Fathers Name:</b></td>
<td>Caith Fernandes </td>
</tr>
<tr>
<td><b>Roll No:</b></td>
<td>0702410099</td>
</tr>
<tr>
<td><b>Status:</b></td>
<td>REGULAR </td>
</tr>
<tr>
<td><b>Course/Branch:</b></td>
<td>B. Tech. </td>
</tr>
<tr>
<td><b>Institute Name</b></td>
<td>Imperial College of Science and Technology</td>
</tr>
</table>
My PHP code outputs:
Name:John Fernandes <hr />
Fathers Name:Caith Fernandes <hr />
Roll No:0702410099<hr />
Status:REGULAR <hr />
Course/Branch:B. Tech. Computer Science and Engineering (10)<hr />
Imperial College of Science and Technology<hr />
Also how to get rid of this silly  ? I saw in the original HTML so I tried to sanitize using PHP function html_entity_decode() But its still there...
What is the HTML that you are loading? I am assuming that it's something simple like so:
<table>
<tr>
<td>heading</td>
<td>heading</td>
</tr>
<tr>
<td>key</td>
<td>value</td>
</tr>
</table>
Looks like the first tr is skipped (the headings), and then you have just 2 columns that you want to pair up as KEY => VALUE;
$cols = $row->getElementsByTagName('td');
$key = $cols->item(0)->nodeValue; // string(3) "key"
$val = $cols->item(1)->nodeValue; // string(5) "value"
The above code will return the items you want.