How to echo a variable into a div in php? - php

Im trying to echo a variable into an already existing DIV within a table.
EG:
<table>
<tr>
<td class="error"> </td>
</tr>
</table>
<?php
echo "<td class='error'>".$variable."</td>";
?>
Note: the error td tag is already style and positioned within a table.
The method above causes a lone td tag to be created and added to the top of
the page.
I realise it's probably best to echo php in HTML rather than vice versa but
I need echo HTML in this instance.
Is this possible ?

The simplest solution, if I am understanding correctly:
<table>
<tr>
<td class="error"><?php echo $variable; ?></td>
</tr>
</table>
You have to echo in-place.

Related

Getting a $value into a .php page form table for a calculator

Sorry if this is really basic programming knowledge, but if it is should only take a moment to help me. I've tried lots of things and searches already but can't get it to work.
I'm doing a tutorial from http://www.hungrypiranha.org/make-a-website/online-calculator
I'm making a settings page that will edit a config.php file with a simple price in it. I have set it to 5. I will work out some way to make that editable later with a user interface. One step at a time.
<?php
//config file
$price = "5";
?>
Next I put the calculator script into the index.php page,
but I want to draw out the $price value from the other file and put it into the form table. No matter what I try it doesn't go into the form table.
It goes anywhere I put the code <?php echo $price; ?>, but not into the form table.
<html>
<head>
<title>Net Calc</title>
<link rel="stylesheet" href="styles.css">
<meta name="viewport" content="width=300">
</head>
<body>
<div>
<?php include("config.php"); ?>
<?php echo '<p>Netting Price Calculator</p>'; ?>
<p>Current price per m2 is $<label><?=$price?></label></br>
link to Settings
<?php
if (isset($_POST['valuea'])) $valuea = $_POST['valuea'];
if (isset($_POST['valueb'])) $valueb = $_POST['valueb'];
$answer = $valuea * $valueb * $price;
echo <<<_END
<form method='post' action=''>
<table border='0' width='300px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading"><td colspan="2"><strong>Netting Price Calculator</strong></td></tr>
<tr class="calcrow"><td>Height</td><td align="left"><input type='text' name='valuea' value="$valuea"/></td></tr>
<tr class="calcrow2"><td>Width:</td><td align="left"><input type='text' name='valueb' value="$valueb"/></td></tr>
<tr class="calcrow"><td>Price:</td><td align="left"><?php echo $price; ?></td></tr>
<tr class="submit"><td colspan="2"><input type='submit' value='Calculate'/><input type='reset' value='Reset'/></td></tr>
_END;
?>
<tr class="calcrow">
<td><i>Total:</td>
<td align="left">$<?php echo $answer; ?></td></i>
</tr>
</table>
</form>
</br><?=$price?>
</br><?php echo $price; ?>
</br>
</div>
</body>
</html>
What I put into the $price variable doesn't want to show on the page.
Hope you understand. If you get what I'm asking and know of any better calculator tutorials please let me know.
It's better for everyone to write more readable code.
Also I suggest you to write html outsite php tag. So you will see easier debug.
Your problem is happen around echo <<<_END. So, I suggest you to do like this.
<?php
if (isset($_POST['valuea'])) $valuea = $_POST['valuea'];
if (isset($_POST['valueb'])) $valueb = $_POST['valueb'];
$answer = $valuea * $valueb * $price;
//your form was here but I move it outside of the php tag.
?>
<form method='post' action=''>
<table border='0' width='300px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading">
<td colspan="2">
<strong>Netting Price Calculator</strong>
</td>
</tr>
<tr class="calcrow">
<td>Height</td>
<td align="left">
<input type='text' name='valuea' value="<?php echo $valuea?>"/>
</td>
</tr>
<tr class="calcrow2">
<td>Width:</td>
<td align="left">
<input type='text' name='valueb' value="<?php $valueb?>"/>
</td>
</tr>
<tr class="calcrow">
<td>Price:</td>
<td align="left"><?php echo $price; ?></td>
</tr>
<tr class="submit">
<td colspan="2"><input type='submit' value='Calculate'/>
<input type='reset' value='Reset'/>
</td>
</tr>
I also update your input value from value="$valuea" to <?php echo $valuea?>
because I write it outside php tag. so when you want to display php variable just do <?php and ?> inside html.
I test this your varible inside table form work fine.
little thing
I suggest to put include at first line of file.
<?php include("config.php"); ?>
And if you really need and the script will not work without it. you better use require.
<?php require_once("config.php"); ?>
As I pointed out in comments; the problem here is that you're inside heredoc
and this <?php echo $price; ?> is literally printing that.
If you look(ed) at your HTML source, you would have seen
<td align="left"><?php echo $price; ?></td> rather than the parsed variable assigned.
Simply remove the <?php echo ; ?> and keep $price from inside the form.
However, you will receive undefined variable(s) notices for all the variables you have declared.
You will need to first check if they are set, and/or not empty.
References:
http://php.net/manual/en/function.empty.php
http://php.net/manual/en/function.isset.php
Or using a ternary operator: (See under Ternary Operator)
http://php.net/manual/en/language.operators.comparison.php
Example pulled from the manual on the ternary operator:
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
This can be adapted to variables also and replacing empty by isset.
Error reporting would have signaled that:
http://php.net/manual/en/function.error-reporting.php
HTML stickler:
</br> isn't a valid HTML markup tag; <br/> and <br> are.

Updating table information formatting based on a checkbox value

I have a table that contains a list of items taken from a SQL database using php. There is a checkbox, Done, that I want to tick off as the list is completed. I want the text of the associated item to update to grey or strikethrough as the box is ticked off.
I tried using one of the methods as above:
In CSS
:checked + span {
font-weight: bold;
}
In HTML
<table cellpadding="1" cellspacing="1" class="db-table">
<td><input type="checkbox" name="Done1" value="1" <?php if ($info['Done1'] ==1) echo 'checked'; ?>></td>
<span>
<td><?php echo $info['Seq1'];?></td>
<td><?php echo $info['Size1'];?></td>
</span>
</table>
It does not work. The table has further CSS formatting based on the class.
I take the same data, put it outside the table tags, and it works just fine.
Any suggestions of what to do here? Is the table class somehow overriding what I want to do?
Your markup is invalid, you can't nest a span directly within a table like that and you're also missing the <tr> tags.
However, even with valid markup, what you're asking isn't possible with CSS alone as it doesn't provide any means (yet) for selecting parent elements, which would need to be done here in order to target the sibling cells or parent row.
So, you're going to have to resort to a bit of JavaScript, toggling a class on the parent row each time a checkbox is clicked.
Before we get to the Snippet, here's what you'd need to do with your PHP in order to have the .done class applied to the table rows that require it initially:
<table cellpadding="1" cellspacing="1" class="db-table">
<tr<?php if ($info['Done1'] ==1) echo ' class="done"';?>>
<td>
<input<?php if ($info['Done1'] ==1) echo ' checked="checked"';?> type="checkbox" name="Done1" value="1">
</td>
<td><?php echo $info['Seq1'];?></td>
<td><?php echo $info['Size1'];?></td>
</tr>
</table>
And here's a working Snippet to demonstrate the solution:
var inputs=document.querySelector(".db-table").getElementsByTagName("input"),x=inputs.length;
while(x--)
inputs[x].addEventListener("click",function(){
this.parentNode.parentNode.classList.toggle("done");
},0);
.done td{
font-weight:bold;
}
/* Just some prettifying */table{border:1px solid #999;border-spacing:1px;font-family:arial;font-size:14px;margin:0 auto;width:50%;}td{line-height:20px;padding:5px;}td:first-child{text-align:center;width:20px;}tr:nth-child(odd) td{background:#eee;}tr:nth-child(even) td{background:#ddd;}
<table cellpadding="1" cellspacing="1" class="db-table">
<tr>
<td>
<input type="checkbox" name="Done1" value="1">
</td>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>
<input type="checkbox" name="Done2" value="1">
</td>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>
<input type="checkbox" name="Done3" value="1">
</td>
<td>text</td>
<td>text</td>
</tr>
</table>
Here is a working example. You're CSS will never show because your span is never inside of your checkbox (:check).
At this point you will start getting into DOM Elements. The following example uses JavaScript/jQuery. I set up a listener to listen for checkbox changes (ie is it checked or not). If the checkbox is checked then I add a "done" class onto .info classes.
In order to know which row I'm dealing with I've added to HTML tags. 1, I've added an id to the tr. This should always be unique to the row. 2, I've added a data-row to the checkbox element. This is used to identify the row.
JavaScript is great to use in this instance because you are wanting to change elements on the fly that are outside of the hierarchy that CSS allows.
It may be a little over the top, but it definitely gets the job done.
<?php
$info['Done1'] = 0;
$info['Seq1'] = 'Hello';
$info['Size1'] = 'World';
?>
<style type="text/css">
.done{color:#ccc;}
</style>
<table cellpadding="1" cellspacing="1" class="db-table">
<tr id="row1">
<td><input type="checkbox" name="Done1" value="1" data-row="1" <?php if ($info['Done1'] ==1) echo 'checked'; ?>></td>
<td class="info"><?php echo $info['Seq1'];?></td>
<td class="info"><?php echo $info['Size1'];?></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('input[name="Done1"]').change(function(){
if( this.checked ){
$('#row'+$(this).data('row')+' .info').addClass('done');
}else{
$('#row'+$(this).data('row')+' .info').removeClass('done');
}
});
});
</script>

echo html as text with PHP variable

I need to display a large amount of html as text(a table) which contains PHP variables. Now I would like to know if there is a command that echos the HTML as text, but keeps the PHP.
I know I can change the > with >. I'm just wondering if there is a better way to do this.
<table style="width:400px">
<tr>
<td><b style="font-size:27px;">$_POST['name']</b></td>
<td rowspan="2"> IMG</td>
</tr>
<tr>
<td><b style="font-size:23px;font-weight:400">$_POST['function']</b></td>
</tr>
</table>
This is only a part of it of course.
TL;DR: I want to echo the above text(as text, not code) but the variables from PHP need to execute as code.
Pushing it through the htmlentities function when you output the data should work. The function will convert whatever string you put in into one that looks exactly the same when rendered in HTML, which seems to be what you want.
Use htmlspecialchars and add curly braces around PHP variables:
$string = "<table style=\"width:400px\">
<tr>
<td><b style=\"font-size:27px;\">{$_POST['name']}</b></td>
<td rowspan=\"2\"> IMG</td>
</tr>
<tr>
<td><b style=\"font-size:23px;font-weight:400\">{$_POST['function']}</b></td>
</tr>
</table>";
echo htmlspecialchars($string);

I can't get div id displayed in loop in Code Igniter

I have a command that creates a loop:
foreach($cart as $line=>$item).
When it displays, it shows the HTML quoted below. I have tried to add a div id below the loop, as I want to create a getElementById() function. However, it creates a loop above on its own. Also, I cannot change the tr statement. I have actually done a search and replace on every tr statement in Code Igniter and it is still there. I am quite a novice, and would really appreciate any advice, as this has been baffling me for three days now.
<tbody id="cart_contents">
<?php
if(count($cart)==0)
{
?>
<tir><td colspan='8'>
<div class='warning_message' style='padding:7px;'><?php echo $this->lang->line('sales_no_items_in_cart'); ?></div>
</tr></tr>
<?php
}
else
{
echo "</tr><tir>";
foreach($cart as $line=>$item)
{
?>
<td id = " <?php echo $item['name'];?>" style="align:center;" ><?php echo $item['name']; ?></td>
<?php if ($items_module_allowed)
{
?>
<td><?php echo form_input(array('name'=>'price','value'=>$item['price'],'size'=>'6'));?></td>
<?php
}
else
{
?>
<td><?php echo $item['price']; ?></td>
<?php echo form_hidden('price',$item['price']); ?>
<?php
}
?>
<td>
<?php
if($item['is_serialized']==1)
{
echo $item['quantity'];
echo form_hidden('quantity',$item['quantity']);
}
else
{
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2'));
}
?>
</td>
<td><?php echo to_currency($item['price']*$item['quantity']-$item['price']*$item['quantity']*$item['discount']/100); ?></td>
<?php
if($item['allow_alt_description']==1)
{
}
else
{
if ($item['description']!='')
{
}
else
{
}
}
?>
</td>
<td> </td>
<td style="color:#2F4F4F";>
<?php
if($item['is_serialized']==1)
{
}
?>
</td>
<td colspan=3 style="text-align:left;">
<?php
if($item['is_serialized']==1)
{
}
?>
</td>
</tr>
<tr style="height:3px">
<td colspan=8 style="background-color:white"> </td>
</tr> </form>
<?php
}
}
?>
</tbody>
</table> </div>
This is the HTML output from the original loop.
<tr><td id=" test" style="align:center;">test</td>
<td><input type="text" name="price" value="150.00" size="6"></td>
<td>
etc...
</td>
</tr>
I don't believe your problem is with your php, I think it is your html.
Your html opening and closing tags do not all match up. You have several unclosed <tr> elements, at least one un-opened <tr>, your form tags don't work out given your if/else statement structure, and you don't actually have an opening <table> tag or an opening <div> tag at the top of your code while you have both at the end. The div that you are getting above your loop that you expect to occur IN your loop is probably the result of your browser trying to interpret the broken page structure.
As far as the form tags I mentioned, make sure that if you use an if statement to open a form, you must also have a condition that will open any required forms if the if statement evaluates to false. I think you have a form element inside an if, then form inputs as part of the next else statement.
I've simplified your posted code and included comments to try and illustrate this:
<tbody id="cart_contents">
<?php if(){?>
<tir><!--what's a 'tir'?, did you mean 'tr'?-->
<td colspan='8'>
<div class='warning_message' style='padding:7px;'>
</div>
</tr>
</tr>
<?php }else{
echo "</tr><tir>";//here you are closing a row that was never opened, and another 'tir'.
foreach($cart as $line=>$item){?>
<td></td>
<?php if (){ //here you call a form input before the form is created...?>
<td><?php echo form_input();?></td>
<?php }else{?>
<td></td>
<?php echo form_hidden();
//this form isn't in a table element, which might act weird?>
<?php }?>
<td><?php if() {
echo form_hidden();
}else{
echo form_input());
//here you have a form input outside of a form if
//the previous if statement evaluates to false.
}?>
</td>
<td></td>
<?php if(){ }
else {
if(){}
else{}
}?>
</td><!--this td was never opened-->
<td> </td>
<td></td>
<td></td>
</tr><!--this tr was never opened-->
<tr><td></td></tr>
</form><!--I don't believe you can count on your conditional statements to garantee that a form was opened-->
<?php }
} ?>
</tbody>
</table> <!--you haven't opened your table in this code-->
</div><!--you havent' opened a div in this code-->

Need help simplifying my php table

I am relatively new to php and have a feeling that I am going the long way round when displaying data from mysql.
I have a table a I want to show a few fields from my database.
How would I achieve this without having to echo every bit of the table???
Here is the code:
<?php
$query1 = mysql_send("SELECT firstname, lastname, email, user, country FROM customers WHERE id='".$_COOKIE['custid']."'");
while ($row = mysql_fetch_array($query1))
{
echo ' <table id="account_table" style="width:550px; border:none; ">
<tr>
<td width="155">Contact Name</td>';
echo '<td width="335">';
echo $row['firstname'] ;
echo ' ';
echo $row['lastname'];
echo '</td>
</tr>
<tr>
<td>Email Address</td>
<td>';
echo $row['email'];
echo ' </td>
</tr>
<tr>
<td>Username</td>
<td>' ;
echo $row['user'];
echo '</td>
</tr>
<tr>
<td>Country</td>
<td>';
echo $row['country'];
echo '</td>
</tr>
<tr>
<td>Time Zone</td>
<td>GMT+1</td>
</tr>
<tr>
<td>Activated</td>
<td>16 Dec 2009</td>
</tr>
</table>';
}
?>
I would suggest to look at some templating engine like Smarty, that would allow you to separate presentation from php code.
You can fetch all data into an array first and then iterate over that array. There is no need to echo all that HTML with PHP.
At the top of your file, you should do all the processing (i.e. getting, validating data) and in the remainder you just write plain HTML, only printing the values with PHP.
This already gives you a certain degree of separation. Others mention template engines (Smarty, etc.). I don't think that you really need that, because PHP itself is a template engine.
Just don't get tempted to do sophisticated stuff in your presentation ;)
Also the alternative syntax for control structures is very useful for using in combination with the presentation as it is imho much more readable.
I changed the table structure a bit, because you were not generation valid HTML (you create a lot tables with the same ID in your original code).
This just generates one table, with a row for each customer.
<?php
$customers = array();
$query1 = mysql_send("SELECT firstname, lastname, email, user, country FROM customers WHERE id='".$_COOKIE['custid']."'");
while ($row = mysql_fetch_array($query1)) {
$cusomters[] = $row;
}
?>
<table id="account_table" style="width:550px; border:none;">
<tr>
<th width="155">Contact Name</th>
<th>Email Address</th>
<th>Username</th>
<th>Country</th>
<th>Time Zone</th>
<th>Activated</th>
</tr>
<?php foreach($customers as $customer): ?>
<tr>
<td width="335">
<?php echo $row['firstname'] ?>
<?php echo $row['lastname'] ?>
</td>
<td><?php echo $row['email'] ?> </td>
<td><?php echo $row['user'] ?></td>
<td><?php echo $row['country'] ?></td>
<td>GMT+1</td>
<td>16 Dec 2009</td>
</tr>
<?php endforeach; ?>
</table>
The basics seem right, although you will need to move the <table> tag out of the while loop, now you are creating a table for every entry and my guess is that that´s not what you want.
You also need to prepare your output for output to the browser with something like htmlspecialchars($row[...]). That way you avoid potential problems if the output contains html tags (javascript, etc.).
First some advices, keep a window/tab open to the php manual. (ie, mysql_send() function doesn't exist).
Indent your code, and try to find a consistent convention to keep your code readable.
You're inserting your table markup into your while loop which is wrong. Your table should wrap your loop.
Using $_COOKIE as is to select from your database is really bad. Filter and sanitize your input before to use it in any query.
To avoid mixing data presentation and business logic, you can take a look to template engine.
Look at 19 Promising PHP Template Engines to find one, or take a look at the wikipedia list.

Categories