Im busy with an school command, and i need to play display and text on a page when you have fill in 2 forms on 2 different pages.
First page is kies_merk.html where you have to choose the merk (brand)
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8" />
<title>Kies merk</title>
</head>
<body>
<h3>Auto selectie (Deel 1 van 3)</h3>
<p>Kies een automerk...</p>
<form name="form" action="kies_type.php" method="get">
<select name="merk">
<option value="Volvo">Volvo</option>
<option value="Peugeot">Peugeot</option>
<option value="Volkswagen">Volkswagen</option>
<option value="Opel">Opel</option>
</select>
<input type="submit" value="ok"/>
</form>
</body>
</html>
Second page is where you have to choose the type of the car:
<?php
$formulier = '<p>Welk type wil je bekijken?</p><form name="form2" action="type_informatie.php" method="get"><select name="type"><option value="S40">S40</option><option value="S60">S60</option><option value="C70">C70</option><option value="S80">S80</option></select><input type="hidden" name="Merk" value="Volvo"><input type="submit" value="ok"/></form>'
?>
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8" />
<title>Kies merk</title>
</head>
<body>
<h3>Auto selectie (Deel 2 van 3)</h3>
<p>Kies een type...</p>
<?php
$merk = ($_GET['merk']);
if ($merk === Volvo) {
echo $formulier;
} else {
echo "<p>Dit merk zit helaas nog niet in het 'systeem'...</p><a href='kies_merk.html'>Maak een andere keuze a.u.b</a>";
}
?>
</body>
</html>
On the third page is the output, but there it goes wrong. It doesnt show the image, it only takes the first number out of the array. If i go to my browser to the image URL, it says for e.g. /S (not even .png extension). I think it goes wrong at the $type = $_GET['type'] part, but i dont know for sure. I hope someone can help me.
type_informatie.php:
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8" />
<title>Kies merk</title>
<style>
img {
height: 200px;
width: auto;
}
</style>
</head>
<body>
<h3>Auto selectie (Deel 3 van 3)</h3>
<p>Je koos de volgende auto: <?php echo ($_GET['Merk']) . " " . ($_GET['type']) ?> </p>
<?php
$S40 = array('/S40.png', 'De S40: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut malesuada tincidunt est ut faucibus.');
$S60 = array('/S60.png', 'De S60: Fusce eget quam in purus interdum tincidunt ultricies sit amet velit. Nulla pulvinar cursus malesuada.');
$C70 = array('/C70.png', 'De C70: Aenean aliquam varius eros. Nam dictum, lorem a maximus gravida, odio risus pretium mi, vel convallis neque dui eget nisl. Quisque vestibulum vel lacus id congue.');
$S80 = array('/S80.png', 'De S80: Nullam rutrum metus nec iaculis facilisis. Maecenas vitae hendrerit orci. Nulla sit amet dolor risus. Fusce accumsan augue nec leo congue, nec porta tellus semper.');
$type = $_GET['type'];
echo "<div>" . "<img src='$type[0]' alt='' />" . "</div>";
echo "<p>$type[1]</p>"
?>
</body>
</html>
$type = $_GET['type']; is going to hold the value of the selected option in your select named type
<select name="type"><option value="S40">
$type[0] is an array reference in <img src='$type[0]' alt='' /> which is referencing the first character in the string, which happens to be S from S40
so you need to echo the whole thing, and probably add the .png extension since that's not in your form.
echo "<div>" . "<img src='$type.png' alt='' />" . "</div>";
if you look at your error logs, then you might also notice a notice
Notice: Use of undefined constant Volvo - assumed 'Volvo' in thispage.php on line 6,000,042
You should clean up that assumption by explicitly changing if ($merk === Volvo) which uses a constant, to if ($merk === 'Volvo') which uses a string.
Related
I'm new to php as you can tell and I'm having trouble with my session.Session is being lost upon refreshing page. I have a simple button that toggles between light and dark mode, it works and I store the value into a session value. I'm able to print the value and see that it is being stored, however upon a refresh or a revisit, the mode switches to the opposite mode and then upon refresh/revisit, the state is actually saved. I've tried to search for my issue but I cant find anything and I'm off to bed so I thought I may as well post in the meantime. I'm not sure what I'm missing, probably something obvious, but I appreciate the help. I can only use PHP for this by the way.
<?php
session_start();
//header('Refresh: 3000; url=index.php');
echo "" . $_SESSION['color'] . "";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
?>
<!DOCTYPE html>
<html lang = "en-US">
<head>
<link rel="stylesheet" href="index.css">
<title>
Web Technologies
</title>
</head>
<body>
<?php session_start();
include_once "templateFunctions.php";
if (isset($_POST['dark'])) {
if (!isset($_SESSION['color'])) {
//session_register('color');
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
} else {
if ($_SESSION['color'] == "rgb(54, 53, 53)") {
$_SESSION['color'] = "white";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
} else {
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
}
}
}
/*$color = "rgb(48, 48, 48)";
setcookie('color', $color, time() + 10, '/');
$_COOKIE['color'] = [$color];
echo "<p>'$cookie'</p>";
echo "<body style = 'background-color: $cookie;'>";
else {
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
}
*/
?>
<div class = "header">
<div class = "title" >
<h1>Jimbo Fimbo</h1><h2><u>Software Stuff</u></h2></th>
</div>
<div class = "img">
<img id = "img1" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTci5Mqm2mgMe_9KfJR0TqMEd-A_wtmqq69cru0wed7OEQF6jVAYycqCY_KzWV0o3hIVYs&usqp=CAU" alt="https://i.ytimg.com/vi/KEkrWRHCDQU/maxresdefault.jpg">
</div>
</div>
<hr style = "margin-bottom: 20px;">
<div class = "colgroup">
<div class="column1">
<h3 style = "text-align: center;">Menu</h3><hr style = "color:white;">
<ul style = "padding-left:20px; font-size: 25px;">
<li>GitHub<br></li>
<li>Courses<br></li>
<li>School<br></li>
</ul>
</div>
<div class="column2">
<h1>About Me</h1>
<img id = "img2"src="https://i.ytimg.com/vi/KEkrWRHCDQU/maxresdefault.jpg">
<p>
Heres some lorem ipsum! <br> Lorem ipsum dolor sit amet. Reprehenderit sunt est quia
necessitatibus est eius quis. Est dolor adipisci et dolor molestiae hic vitae expedita eum inventore quam aut mollitia natus. Qui quia
dolor aut totam Quis qui expedita repudiandae non quam magni et enim ipsa qui consequatur omnis. Ea incidunt debitis est nemo nesciunt
eum quia rerum eum recusandae sunt nam maiores saepe. Hic omnis dolores ab deserunt vero cum fugiat explicabo vel perferendis numquam.
Sed unde voluptatibus quo aliquid iure rem accusamus voluptatum aut maxime adipisci id molestiae voluptatem? In quia necessitatibus et
provident id nobis eius ea enim voluptatem in aliquam voluptas ut similique facilis. Et porro ipsam eos excepturi voluptatem non ullam sint.
</p>
<p>Stuff goes here </p>
</div>
<div class="column3">
<p style = "text-align: center;">Enrolled Courses</p>
<hr style = "color:white;">
<ol style = "padding-left: 20px; font-size: 25px;">
<li>CS-3753</li>
<li>CS-4393</li>
<li>CS-4413</li>
<li>CS-4423</li>
<li>CS-4843</li>
</ol>
<form action="index.php" method = "post" accept-charset=utf-8 >
<input type="submit" name = "dark" id ="submit" value = "Dark Mode">
</form>
</div>
</div>
<footer class="foot">
Copyright 2022, Jimbo Fimbo
</footer>
</body>
</html>
I'm expecting what I mentioned above.
I've looked over the code to no avail, I've tried using another session variable to save the color change, I tried saving the session to a path using said method, and I've looked on the internet for similar problems but I guess I suck at googling since this seems like it would be straightforward.
If you want to get rid of the problem that the session variable will be "toggled" on page refresh, One of the ways is to separate the change color part from your display part, so the form submission target can be set to "changecolor.php", which will trigger a page redirection to index.php upon changing the session variable :
index.php
<?php
session_start();
/// initalize the color to be white if no color session variable
if (!isset($_SESSION['color'])) {
$_SESSION['color'] = "white";
}
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
?>
/// other HTML code
<form action="changecolor.php" method = "post" accept-charset=utf-8 >
<input type="submit" name = "dark" id ="submit" value = "Change Color Mode">
</form>
changecolor.php
<?php session_start();
if (isset($_POST['dark'])) {
if (!isset($_SESSION['color'])) {
$_SESSION['color'] = "rgb(54, 53, 53)";
} else {
if ($_SESSION['color'] == "rgb(54, 53, 53)") {
$_SESSION['color'] = "white";
} else {
$_SESSION['color'] = "rgb(54, 53, 53)";
}
}
header("Location: index.php");
}
?>
Hey i want to display some html/css depending on how many rows there are in database basically. Is there a way to do this without echo? Because i'm lost when i have to use many ' '. Here is code sample
<?php foreach ($result as $row) {
}?>
<div id="abox">
<div class="abox-top">
Order x
</div>
<div class="abox-panel">
<p>lorem ipsum</p>
</div>
<br>
<div class="abox-top">
lorem</div>
<div class="abox-panel">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ac convallis diam, vitae rhoncus enim. Proin eu turpis at ligula posuere condimentum nec eu massa. Donec porta tellus ante, non semper risus sagittis at. Pellentesque sollicitudin sodales fringilla. Ut efficitur urna eget arcu luctus lobortis. Proin ut tellus non lacus dapibus vehicula non sit amet ante. Ut nibh justo, posuere sit amet fringilla eget, aliquam mattis urna.</p>
</div>
There's nothing complicated about it:
Simple/ugly:
<?php while($row = fetch()) { ?>
<div>
<?php echo $row['somefield'] ?>
</div>
<? } ?>
Alternative:
<?php
while ($row = fetch()) {
echo <<<EOL
<div>
{$row['somefield']}
</div>
EOL;
}
and then of course there's any number of templating systems, which claim to separate logic from display, and then litter the display with their OWN logic system anyways.
you can simply use <?= short opening tag introduced in php 5.3 before PHP 5.4.0 came out you had to enable short_open_tag ini but after 5.4.0 tag
here is an example
<?php $var='hello, world'; ?>
<?=$var ?> // outputs world
hope it helps.
Templates engines makes your life a pie
Take Smarty for example, it's pretty good template library. What template engine does is fetch variables to pre defined templates.
Your code in simple php:
<?php
echo 'My name is '. $name. ', that's why I'm awesome <br>';
foreach ($data as $value) {
echo $value['name'].' is awesome to!';
}
?>
Code in smarty:
My name is {$name}, that's why I'm awesome <br>
{foreach $data as $value}
{$value} is awesome to!
{/foreach}
Template engines pros:
Templates are held in separate custom named files. (i.e users.tpl, registration.tpl etc)
Smarty Caches your views (templates).
Simple to use i.e {$views + ($viewsToday/$ratio)}.
A lot of helpers.
You can create custom plugins/functions.
Easy to use and debug.
Most importantly: It separates your php code from html!
Template engines cons:
Sometimes hard to grip the concept of working for beginner.
Don't know any more actually
When I dont want to use a template engine (I like Twig, btw), I do something like this:
1) Write a separate file with the html code and some custom tags where data should be presented:
file "row_template.html":
<div class="abox-top">{{ TOP }}</div>
<div class="abox-panel"><p>{{ PANEL }}</p></div>
2) And then, read that file and do the replacements in the loop:
$row_template = file_get_contents('row_template.html');
foreach ($result as $row) {
$replaces = array(
'{{ TOP }}' => $row['top'],
'{{ PANEL }}' => $row['panel']
);
print str_replace(
array_keys($replaces),
array_values($replaces),
$row_template
);
}
In addition, you can change the content of "row_template.html" without touching the php code.
Clean and nice to the eye!
I have a really small webpage written in php (approx. 5 pages + blog entries). All pages are located in php files on the server side (no database is used). So far I managed to search inside my 'blog entries' - because these are just plain textfiles with HTML markup (I strip the tags & performing a search operation):
$file_name=array();
$search_string="";
if(isSet($_GET["query"])){
$search_string=$_GET["query"];
}
$search_result="";
$files="";
$phpfilename="";
$i=0;
if (!$search_string){
echo 'No query entered<br />';
}else{
if ($handle = opendir('content/')) {
while (false !== ($file = readdir($handle))){
if(strrchr($file, '.') === ".txt"){
$filename[]= $file;
}
}
closedir($handle);
}
foreach($filename as $value){
$files="content/$value";
$fp = strip_tags(file_get_contents($files));
if(stripos($fp, $search_string)) {
$search_result.=preg_replace('/<[^>]*>[^<]*<[^>]*>/', '', substr($fp,0,255)); // append a preview to search results
}
if($search_result!=""){
echo $search_result;
}else{
echo "No Results<br />";
}
}
}
Of course that works just because the files are plain text. But I've got also pages that are real 'php' files and want to perform a search operation on them too. But I don't want to search inside the 'php code' of course. I figured out, that I would need the preparsed files that the browser gets from the webserver - I thought about using file_get_contents() with http requests to all my pages (ok, 'just' about 5 pages but still)...
I've read here on SO that it's considered bad practice to do so and it feels like I'm taking the wrong approach.
Any ideas & suggestions would be highly appreciated.
Edit: A example for a regular page that I want to be able to search in
index.php
<?php ob_start(); require_once("./include/common.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $lang['WEBSITE_TITLE']; ?></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="keywords" content="keyword, keyword, keyword" />
<link href="css/main.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="page">
<!-- Header Area -->
<?php include("./include/header.php"); ?>
<?php include("./include/banner.php"); ?>
<div id="content">
<?php
$page = '';
if(isSet($_GET["page"])){
$page=$_GET["page"];
}
switch($page){
case 'category_1':
include("./include/category_1.php");
break;
case 'about':
include("./include/category_2.php");
break;
case 'contact':
include("./include/contact.php");
break;
default:
include("./include/home.php");
}
?>
<!-- /content --></div>
<!-- /page --></div>
<br />
<br /><br /><br />
<!-- Footer Area -->
<?php include("./include/footer.php"); ob_end_flush(); ?>
</body>
</html>
/include/category_1.php
<?php echo '<h2>'.$lang['NAVI_CAT_1'].'</h2>'; ?>
<div id="entry">
<br/>
<?php echo $lang['CAT_1_TEXT']; ?>
</div>
language file
<?php
$lang = array();
$lang['NAVI_CAT_1'] = 'Category 1';
$lang['CAT_1_TEXT'] = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.';
?>
Why not include into a buffer and then search the buffer's contents?
ob_start();
include ('index.php');
$contents = ob_get_clean();
//the $contents now includes whatever the php file outputs
I actually use this method in production code for all kinds of things, but mainly previewing site-generated emails before users send them. The nice thing is, you can use this on all the files, not just the php files.
this is failed by design.
consider not using plain mixed html sides. try to use xml files or wathever.
the alternative is crawling your own side. take a look at http://symfony.com/doc/current/components/dom_crawler.html
I create a simple backed area for my client to post new job openings and was wanting to give them the ability to format the text a little by adding line breaks in the job description text that will be visible on the front end.
The job openings are stored in a MySQL database.
Example of what I'm talking about:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat.
I've would like the breaks to happen when my client hits enter / return on the keyboard.
Any help on this matter would be appreciated.
------------UPDATE------------
okay so after much trial and error I got it somewhat working.
I added this line in my upload / action code.
$description = nl2br(htmlspecialchars($_POST['description']));
Full upload code is:
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$date = mysql_real_escape_string($_POST["date"]);
$title = mysql_real_escape_string($_POST["title"]);
$description = mysql_real_escape_string($_POST["description"]);
$description = nl2br(htmlspecialchars($_POST['description']));
// Insert record into database by executing the following query:
$sql="INSERT INTO hire (title, description, date) "."VALUES('$title','$description','$date')";
$retval = mysql_query($sql);
echo "The position was added to employment page.<br />
<a href='employment.php'>Post another position.</a><br />";
?>
Then on my form I added this to the textarea, but I get an error.
FYI that is line 80 the error is refering to.
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />","",$description); ?></textarea>
</div>
Here is what the error looks like.
Here is my results page code:
<?php
$images = mysql_query("SELECT * FROM hire ORDER BY ID DESC LIMIT 10");
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>">
<div class="box white-bg">
<h2 class="red3-tx"><?=$image["title"] ?> <span class="date-posted blue2-tx"><?=$image["date"] ?></span></h2>
<div class="dotline"></div>
<article class="blue3-tx"><?=$image["description"] ?><br />
<br />
For more information please call ###-###-####.</article>
</div>
</li>
<?php
}
?>
If I delete all that error copy and write out a real position with line breaks it works.
I have no idea how to fix the error though.
Again any help would be appreciated.
Thanks!
you can use str_replace
$statement = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat."
$statement = str_replace(chr(13),"<br/>", $statement);
query example : INSERT INTO table (statement) VALUES ('$statement');
hope this can help you
EDIT :
if you want display the result at textarea from database u can using this code
$des = $row['description'] //my assumption that your feild name at table inside mySQL is description
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />",chr(13),$des); ?></textarea>
</div>
hope this edit can help your second problem
I would start by answering a couple of questions first
Do I want my database to store html-formatted user input?
Is the data going to be editable afterwards?
Since you seem to want only nl2br, a simple approach would be to save the content as is in the database, then use nl2br() on the output side as Marcin Orlowski suggested.
I am working with html document generated from Micrsoft Word 2007/2010. Besides generating incredibly dirty html, word also has the tendency of using both block and inline style. I am looking for a php library would merge block into already existing inline style element.
Edit
The goal is to construct a html block preserve the original formatting and editable in WYSIWYG editor like tinyMCE
Example
If the original html is:
<html>
<head>
<style>
.normaltext {color:black;font-weight:normal;font-size:10pt}
.important {color:red;font-weight:bold;font-size:11pt}
</style>
<body>
<p class="normaltext" style="font-family:arial">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In ut erat id dui mollis faucibus. Mauris eu neque et eros tempus placerat.
<span class="important">Nam in purus nisi</span>, vitae dictum ligula.
Morbi mattis eros eget diam vulputate imperdiet.
<span class="important" style="color:green">Integer</span> a metus eros.
Sed iaculis porta imperdiet.
</p>
</body>
</html>
Should become:
<html>
<head>
<body>
<p style="font-family:arial;color:black;font-weight:normal;font-size:10pt">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In ut erat id dui mollis faucibus. Mauris eu neque et eros tempus placerat.
<span style="color:red;font-weight:bold;font-size:11pt">Nam in purus nisi</span>, vitae dictum ligula.
Morbi mattis eros eget diam vulputate imperdiet.
<span style="color:green;font-weight:bold;font-size:11pt">Integer</span> a metus eros.
Sed iaculis porta imperdiet.
</p>
</body>
</html>
Check out:
http://inlinestyler.torchboxapps.com/
http://premailer.dialect.ca/
http://www.pelagodesign.com/sidecar/emogrifier/
http://blog.verkoyen.eu/blog/p/detail/convert-css-to-inline-styles-with-php
http://beaker.mailchimp.com/inline-css
http://burrowscode.wordpress.com/2011/02/19/emailify-internal-stylesheets-to-inline-styles/
https://github.com/crcn/emailify
https://github.com/peterbe/premailer
Porting code from either of the sources to PHP, or using any of the available APIs should do the trick of getting your CSS styling inline.
See the CssToInlineStyles project which does exactly what you want.
No, but try this instead, copying and pasting from word into http://ckeditor.com/ or tinymce, etc does clean it up A LOT, thought it's still not perfect it will get you much closer.
I finally managed to get it to work. The code is based off of
http://blog.verkoyen.eu/blog/p/detail/convert-css-to-inline-styles-with-php
with once simple change:
Moving the line
// add new properties into the list
foreach($rule['properties'] as $key => $value) $properties[$key] = $value;
up to the begining of the loop, right after where $properties is declared.
To make this work for WordPress however, one additional change is needed. DomDocument replace &nbps; from the document with blanks, which breaks WordPress update statement and lead to cotent being cut off. Please refer to my other question for the solution:
DOMDocument->saveHTML() converting to space
This problem is detailed in https://wordpress.stackexchange.com/questions/48692/post-content-getting-cut-off-on-blank-space-on-wpdb-update. If you know why this is happening for WordPress, please post your answer there as I would very much like to find out why it is happening.