dynamically divs creation on the basis of table records - php

I have a page in which i have to display a list of job boards. I have a table named as job_board in which i all the record of 10 to 12 may be more job boards is saved. I want to display a page in which there will be a div as container and inside that div i want to display these job boards, each in a separate div(side by side). At the moment i am trying this loop:
foreach($this->test as $value)
{
$variable=null;
echo $variable .='<div class="testing"></div><div class="head"></div>';
$variable .=$value["job_board_id"] . '</br>';
$variable .=$value["name"] . '</br>';
$variable .=$value["description"] . '</br>';
$variable .=$value["price"]. '</br>';
$variable .= $value["enabled"]. '</br>';
echo $variable;
}
The columns in my table are id,name,description,price,url)
I want to display it in the small divs which are inside the main div "container"

If you want show divs side by side, please try float. The code may goes like this:
foreach($this->test as $value)
{
$variable=null;
$variable .='<div class="cell">';
$variable .=$value["job_board_id"] . '</br>';
$variable .=$value["name"] . '</br>';
$variable .=$value["description"] . '</br>';
$variable .=$value["price"]. '</br>';
$variable .= $value["enabled"]. '</br>';
$variable .='</div>';
echo $variable;
}
And, the class 'cell' will be defined in your CSS file like below:
<style type="text/css">
.cell{
width:150px;
float:left;
}
#container:after { /*clear the float*/
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
</style>

if you wish to print each line in one div with span you can try with this
echo $variable .='<div class="testing"></div><div class="head"></div>';
$variable .= '<div><span>'.$value["job_board_id"] . '</span>';
$variable .= '<span>'.$value["name"] . '</span>';
$variable .= '<span>'.$value["description"] . '</span>';
$variable .= '<span>'.$value["price"]. '</span>';
$variable .= '<span>'.$value["enabled"]. '</span></div>';
echo $variable;
And for second loop after print $variable please assign with blank like $variable = '';
Also try to make more attractive with css.
let me know if i can help you further.

Related

Create php $_SESSION from count variable

I am trying to create a $_SESSION from example code count($result). I have decalred the variable like thus:
$result = array();
$result[] = $boxdest;
This is working fine on the page where I run it but I need to pass the value to a page to use in php mail() function. I have tried
$_SESSION['result'] = $result;
But all I get is Resource id #40. How do I pass this variable to another page. Full code example here: http://sandbox.onlinephpfunctions.com/code/ba0a34774e30c93edfdf02f531bb199c681021e3 Many thanks
This is more of a critique of the code rather than a solution to the problem:
$_SESSION['result'] = []; //Clear it in case there's an old value here.
if (isset($_POST['boxdest']) && is_array($_POST['boxdest']) && !empty($_POST['boxdest'])) { //Merged condition
$destroydata = explode(',', $_POST['boxdest'][0]); //Split was deprecated
$result = array_filter($destroydata);
if (empty($result) {
$boxdesterror = '<span style="font-weight:bold;font-size:12px;color: #ff0000;">' . 'BOX DESTRUCTION ERROR! ' . '</span>' . '<span style="font-weight:normal;color: #000;background-color:#ffa;">' . 'You must enter a box for destruction' . '</span>';
echo "<script language=\"JavaScript\">\n";
echo 'alert("BOX DESTRUCTION ERROR:\nYou must enter a box for destruction.");';
echo "</script>";
echo $boxdesterror;
} else {
echo 'You wish to destroy ' . count($result) . ' box(es): ' . '<div style="word-wrap:break-word;white-space: pre-wrap;overflow:auto !important;height: 100px; width: 250px; border: 1px solid #666; background-color: #fff; padding: 4px;">' . '<span style="font-weight:bold;color: #000;">' . implode(', ', $boxdest) . '</span>' . '</div>' . '<p />';
$_SESSION['result'] = $result; //Did you really need both?
$flag = 1;
}
}
This should be the same results. I don't see why a resource would pop up from nowhere though.
U can't store any Resource in PHP session
https://stackoverflow.com/a/42389037/5361130
http://php.net/manual/en/function.serialize.php
EDIT
if your $result is result of function like mysqli_query or something like this, use mysqli_num_rows to get number of rows not count
http://php.net/manual/en/mysqli-result.num-rows.php
$result = mysqli_num_rows($boxdest)
or
$_SESSION['result'] = mysqli_num_rows($boxdest)

How do I style my text inside an echo?

Part of the code is
while ($row = mysqli_fetch_assoc($result))
{
echo "$row[firstname] $row[lastname]";
echo "<hr>";
echo "<strong>Date Referred:</strong>     $row[cf_831]";
echo "<br/>";
echo "<strong>Date Today:</strong>       $today";
echo "<br/>";
}
How do I style this part for example?
"$row[firstname] $row[lastname]"
You can try
echo '<p class="mystyle">' . $row['firstname'] . " " . $row['lastname'] . '</p>';
Then add CSS
.mystyle {
}
Addition to Sidsec9's answer: if you are afraid of stylesheets, you can also consider:
echo '<p style="color: red; font-size: 10pt;">' . $row['firstname'] . " " . $row['lastname'] . '</p>';
You could also use styles to get rid of  , for example using margin-right or padding-right properties.
echo '<p id="name"> '. $row[firstname] $row[lastname] .'</p>';
Css you only using for name alone use id else use class and use the single css for all values.
#name
{
color: red;
}
You can wrap it in a class, and fix it with a stylesheet. I also changed the echo, you're allowed to close the PHP tag, do some HTML and then open PHP again.
<?=$variable?> is short echo, it is the same as <?php echo $variable; ?>.
while ($row = mysqli_fetch_assoc($result)){
?>
<span class="Example"><?=$row[firstname].' '.$row[lastname]?></span>
<hr>
<strong>Date Referred:</strong>     <?=$row[cf_831]?>
<br/>
<strong>Date Today:</strong>       <?=$today?>
<br/>
<?php
}
A better method would be making and html file, say example.com, and place <!-- FIRSTNAME -->,<!-- LASTNAME --> AND <!-- TODAY --> instead of the variables. Then, using php:
$totalResult = "";
$template_one = file_get_contents("example.html");
while ($row = mysqli_fetch_assoc($result)){
$item = $template_one;
$item = str_replace("<!-- FIRSTNAME -->", $row['firstname'], $item);
$item = str_replace("<!-- LASTNAME -->", $row['lastname'], $item);
$totalResult.= $item; // add to totel result
)
// $today doesnt change in the loop, do it once after the loop is done:
$totalResult = str_replace("<!-- TODAY -->", $today, $totalResult);
echo $totalResult; // Now you have the result in a pretty variable

insert echo into the specific html element like div which has an id or class

I have this code.
<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM hi");
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
mysql_close($con);
?>
</body>
</html>
the above code works.
now, I want to insert this
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
into the specified div or other element in the html, example, i will insert this
echo '<img src="'.$row['name'].'" />';
into the html element .
I dont know how to do this, please help me. Thanks
Juliver
if yo want to place in an div like
i have same work and i do it like
<div id="content>
<?php
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
?>
</div>
The only things I can think of are
including files
replacing elements within files using preg_match_all
using assigned variables
I have recently been using str_replace and setting text in the HTML portion like so
{{TEXT_TO_REPLACE}}
using file_get_contents() you can grab html data and then organise it how you like.
here is a demo
myReplacementCodeFunction(){
$text = '<img src="'.$row['name'].'" />';
$text .= "<div>".$row['name']."</div>";
$text .= "<div>".$row['title']."</div>";
$text .= "<div>".$row['description']."</div>";
$text .= "<div>".$row['link']."</div>";
$text .= "<br />";
return $text;
}
$htmlContents = file_get_contents("myhtmlfile.html");
$htmlContents = str_replace("{{TEXT_TO_REPLACE}}", myReplacementCodeFunction(), $htmlContents);
echo $htmlContents;
and now a demo html file:
<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
{{TEXT_TO_REPLACE}}
</body>
</html>
You can write the php code in another file and include it in the proper place where you want it.
AJAX is also used to display HTML content that is formed by PHP into a specified HTML tag.
Using jQuery:
$.ajax({url: "test.php"}).done(function( html ) {
$("#results").append(html);
});
Above code will execute test.php and result will be displayed in the element with id results.
There is no way that you can do it in PHP when HTML is already generated. What you can do is to use JavaScript or jQuery:
document.getElementById('//ID//').innerHTML="HTML CODE";
If you have to do it when your URI changes you can get the URI and then split it and then insert the HTML in script dynamically:
var url = document.URL;
// to get url and then use split() to check the parameter
refer to the basic.
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
there is no way to specifically target an element with php, you can either embed the php code between a div tag or use jquery which would be longer.
You can repeat it by fetching again the data
while($row = mysql_fetch_assoc($result)){
//another html element
<div>$row['name']</div>
<div>$row['title']</div>
//and so on
}
or you need to put it on the variable and call display it again on other html element
$name = $row['name'];
$title = $row['title']
//and so on
then put it on the other element, but if you want to call all the data of each id, you need to do the first code
Have you tried this?:
$string = '';
while($row = mysql_fetch_array($result))
{
//this will combine all the results into one string
$string .= '<img src="'.$row['name'].'" />
<div>'.$row['name'].'</div>
<div>'.$row['title'].'</div>
<div>'.$row['description'].'</div>
<div>'.$row['link'].'</div><br />';
//or this will add the individual result in an array
/*
$yourHtml[] = $row;
*/
}
then you echo the $tring to the place you want it to be
<div id="place_here">
<?php echo $string; ?>
<?php
//or
/*
echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
*/
?>
</div>
Well from your code its clear that $row['name'] is the location of the image on the file, try including the div tag like this
echo '<div>' .$row['name']. '</div>' ;
and do the same for others, let me know if it works because you said that one snippet of your code is giving the desired result so try this and if the div has some class specifier then do this
echo '<div class="whatever_it_is">' . $row['name'] . '</div'> ;
You have to put div with single quotation around it. ' ' the Div must be in the middle of single quotation . i'm gonna clear it with one example :
<?php
echo '<div id="output">'."Identify".'<br>'.'<br>';
echo 'Welcome '."$name";
echo "<br>";
echo 'Web Mail: '."$email";
echo "<br>";
echo 'Department of '."$dep";
echo "<br>";
echo "$maj";
'</div>'
?>
hope be useful.
I use this or similar code to inject PHP messages into a fixed DIV positioned in front of other elements (z-index: 9999) just for convenience at the development stage.
Each PHP message passes into my 'custom_message()' function and is further conveyed into the innard of preformatted DIV created by echoed JS.
There can be as many as it gets, all put inside that fixed DIV, one under the other.
<style>
#php_messages {
position: fixed;
left: 0;
top: 0;
z-index: 9999;
}
.php_message {
background-color: #333;
border: red solid 1px;
color: white;
font-family: "Courier New", Courier, monospace;
margin: 1em;
padding: 1em;
}
</style>
<div id="php_messages"></div>
<?php
function custom_message($output) {
echo
'
<script>
var
el = document.createElement("DIV");
el.classList.add("php_message");
el.innerHTML = \''.$output.'\';
document.getElementById("php_messages").appendChild(el);
</script>
';
}
?>

Display foreach array side-by-side with CSS

I am pretty sure that if I use something like this in css
#list {
float:left;
}
I can format the display of my array to look like
A B C
rather than
A
B
C
The problem is I am having problems formatting the php of the with the proper <div>'s to give me what I want.
foreach ( $model->address as $address ) {
if ($address->Address) echo $address->Address.'<br />';
if ($address->city->Name) echo $address->city->Name;
}
Can someone help me modify the foreach above to achieve the different layout. I also need to be able to format the Address differently then the Name
EDIT: For clarification...
A =
Address
City
B =
Address
City
C =
Address
City
You need to wrap each address in a div and use a class to float it:
PHP/HTML:
foreach ( $model->address as $address ) {
echo '<div class="address-item">';
if ($address->Address) echo $address->Address.'<br />';
if ($address->city->Name) echo $address->city->Name;
echo '</div>';
}
CSS:
.address-item {
float: left;
}
$out = "<ul>";
foreach($model->address as $address){
if(!isset($address->Address) && !isset($address->city->Name)) continue;
$out .= "<li>" . isset($address->Address) ? $address->Address : "" . " "
. isset($address->city->Name) ? $address->city->Name : "" . "</li>";
}
$out .= "</ul>";
print $out;
CSS
li {
float: left;
}
something like:
foreach ( $model->address as $address ) {
echo '<div class="list">';
if ($address->Address) echo $address->Address.'<br />';
if ($address->city->Name) echo $address->city->Name;
echo '</div>';
}
wherein, the CSS will be:
.list {float:left;}

PHP looping problem?

I'm trying to display the first row in one color and the second row in another color but my code displays the result twice in both colors for example lets say I have 5 results my code will double the results by displaying 10 results. How can I fix this problem?
Here is the php code.
while ($row = mysqli_fetch_assoc($dbc)) {
//first row
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
//second row
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
You need to change the class on each row:
$count = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
if( $count % 2 == 0 ) {
$classMod = '';
} else {
$classMod = '-2';
}
//first row
echo '<h3 class="title' . $classMod . '">' . $row['title'] .'</h3>';
echo '<div class="summary' . $classMod . '">' . substr($row['content'],0,255) . '</div>';
$count++;
}
your code should be like this
CSS
.odd { background: #CCC }
.event { background: #666 }
PHP
$c = true;
while ($row = mysqli_fetch_assoc($dbc)) {
$style = (($c = !$c)?' odd':' even');
echo '<h3 class="title '.$style.'">' . $row['title'] .'</h3>';
echo '<div class="summary '.$style.'">' .substr($row['content'],0,255) . '</div>';
}
Here's a solution with minimal repetition:
$count = 0;
while (($row = mysqli_fetch_assoc($dbc)) && ++$count) {
printf(
'<h3 class="title%1$s">%2$s</h3>'
. '<div class="summary%1$s">%3$s</div>'
, $count % 2 ? "" : "-2"
, $row['title'] // might want to use htmlentities() here...
, substr($row['content'], 0, 255) // and here...
);
}
$i = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
$color =$i % 2;
echo '<h3 class="title-' .$color . '">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
$i++;
}
Your code just displays every result twice. Use a conditional (e.g. an integer or a boolean) to switch between rows (like: if true, then green; if false, then red).
For a boolean you could change the current value like so:
bool = !bool;
Couple of extra points:
You don't (normally) need so many classes. If you have <div class="stripe"> as your container, you can target the items with e.g. .stripe h3 in CSS.
If you target the odd and even items in CSS with .stripe h3, you can then overwrite just the odd items.
In a perfect world, you should keep presentation in the CSS. All browsers but IE7 and below support div:odd to target any odd child of a parent. This may require changing the structure of your HTML slightly. For IE7 and below, I'd add classes with JavaScript instead of PHP. When IE7 is no more then you can just remove the JS.
By the way, you could do this code too:
while ($row = mysqli_fetch_assoc($dbc)) {
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
if($row = mysqli_fetch_assoc($dbc)){
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
}
IMO, there is no excuse for not delegating this kind of non-critical, presentation layer decoration to client side code.
Just use a library like jQuery and access the odd and even rows like so:
<script>
$(document).ready(function()
{
//for your table rows
$("tr:even").css("background-color", "#F4F4F0");
$("tr:odd").css("background-color", "#EFF1F2");
});
</script>
You'll have us generating font tags next.

Categories