I'm a beginner so this may ba a stupid one.
I'm creating simple platform, which uses a database to manage my post stamps collection. I've managed to set up a database and gather new stamps from user. Now I want to create kind of "product page", which will use data from mySQL. You will be able to enter this page through a dynamically generated table, which will contain all stamps in the database.
The code,which generates a simple table is here:
//connect to database
$db = mysqli_connect(database login data);
if(mysqli_connect_errno()){
echo "Jest problem z podłączeniem się do bazy danych. Skontaktuj się z administratorem.";
die();
}
// loop through results of database query, displaying them in the table
$result = mysqli_query($db,"SELECT * FROM stamps");
?>
</head>
<body>
<?php include "navbar.php" ?>
<h1>Przeglądaj swoją kolekcję.</h1>
<?php
echo "<p><b>View All</b>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Nazwa</th> <th>Kraj</th> <th>Wartość nominalna</th> <th>Wartość rynkowa</th> <th>Klaser</th> <th>More info</th> <th>Edytuj</th> <th>Usuń</th></tr>";
while($row = mysqli_fetch_object($result)) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row->id . '</td>';
echo '<td>' . $row->name . '</td>';
echo '<td>' . $row->country . '</td>';
echo '<td>' . $row->price . '</td>';
echo '<td>' . $row->estimated . '</td>';
echo '<td>' . $row->album . '</td>';
echo "<td>More info.</td>";
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
Now, I'd like to post database values to another page, after clicking "More info" and just view it something like that:
<body>
<?php include "navbar.php" ?>
<div class="jumbotron">
<img class="photo" src="http://placehold.it/250x250">
<h1>Znaczek z XIX wieku</h1> <!-- database data goes here -->
<h3>Informacje:</h3> <!-- database data goes here -->
<h5>Numer katalogowy:</h5> <!-- database data goes here -->
<h5>Rok wydania:</h5> <!-- database data goes here -->
<h5>Kraj:</h5> <!-- database data goes here -->
<h5>Wartość nominalna:</h5> <!-- database data goes here -->
<h5>Wartość rynkowa:</h5> <!-- database data goes here -->
<h5>Klaser:</h5> <!-- database data goes here -->
<h3>Opis:</h3> <!-- database data goes here -->
<h5><div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa, aliquam, tenetur voluptatibus veritatis numquam expedita nesciunt quos repudiandae similique atque provident ipsam dolorem recusandae id possimus minus ea eum cupiditate!</div>
<div>Sint, debitis, saepe repellendus commodi recusandae error architecto voluptates soluta ipsa facere perferendis aspernatur quo atque fugiat consequatur! Assumenda necessitatibus dolorem esse distinctio incidunt pariatur praesentium veniam voluptate quae quaerat!</div>></h5>
<p><a class="btn btn-primary btn-lg" role="button">Edytuj</a></p>
</div>
<?php include "footer.php" ?>
</body>
The question is: what is the best way to do it ?
Thanks in advance !
For generating page dynamically you can use $_GET['id'] for getting the id of the table, from where you are gonna fetch the data. Now put a get query after the link you wanna use,
It should look like this
Index.php?id=2
It is gonna fetch all the data from the second row.
But if you are like making a admin board or anything that is gonna modify the database do not use this, use secure login with user password verification,
Be sure to sanitize the id as this is going to used for getting the data in the database.
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");
}
?>
I have json data that looks like this
{
"project_no":1693,
"project_name":"Theresa Project",
"description":"Nonumy euismod ornatus usu te, quodsi viderer accommodare sea cu, ut alterum officiis nec. At deleniti eloquentiam vis. Explicari definitionem ei sea. No nec erat fugit voluptaria, in his elit discere fastidii. Aperiri virtute no eos. Te per habemus vulputate, partem iuvaret intellegebat eam in.",
"project_cost":10000.00,
}
{
"project_no":1664,
"project_name":"School Supplies for Children",
"description":"Nonumy euismod ornatus usu te, quodsi viderer accommodare sea cu, ut alterum officiis nec. At deleniti eloquentiam vis. Explicari definitionem ei sea. No nec erat fugit voluptaria, in his elit discere fastidii. Aperiri virtute no eos. Te per habemus vulputate, partem iuvaret intellegebat eam in. ",
"project_cost":8000.00,
},
I have over 60 records, With php I want to show 10 records on each page and dynamically populate the page numbers based on how many records I have.
Heres how I'm displaying the data.
$json = file_get_contents('http://linktojsondata.com');
$obj = json_decode($json, true);
<?php
$i = 0;
foreach ($obj as $project_name => $project_info) { ?>
<a href="single-project-detail.php/<?php echo $project_info['project_no'];?>">
<img class="img-thumbnail" alt="" src="<?php echo $project_info['featured_image_url']; ?>">
</a>
<a href="single-project-detail.php/<?php echo $project_info['project_no'];?>">
<?php echo $project_info['project_name']; ?>
</a>
<p>
<?php $string = strip_tags($project_info['description']);?>
</p>
<?php if (++$i == 10) break; } ?>
Here is a start, you will split the json array into blocks of 10 using array_chunk, and then loop through this using the page number $_GET['p'] - 1 so your page url may look like page.php?p=2 which will select the second set of data.
$pages = array_chunk(json_decode($json, true), 10, true);
foreach ($pages[$_GET['p'] - 1] as $project_name => $project_info) {
// your code
}
Recently I've set it up so I can update my sites news via my administration panel and now I've been seeking across the web for a solution to print specific lines.
$query = "SELECT * FROM BananzaNews";
$result = mysql_query("SELECT * FROM BananzaNews", $con);
$num_rows = mysql_num_rows($result);
The above tells me how many rows I have and for my five most recent which will be shown on my home page, I want to fetch the data for $num_rows, $num_rows -1, $num_rows -2, $num_rows -3 and $num_rows -4.
The data to fetch;
title
newsDate
imagePath
content
websitePath
My current dummy filled code is the following dubplicated five times;
<div class="Feed">
<div class="Img"><img alt="" src="http://www.davidreneke.com/wp-content/uploads/2013/12/News-Briefs.png"></div>
<div class="Title">My Testing Title</div>
<div class="Date">
<div class="Day">22</div>
<div class="Month">Jan</div>
<div class="Year">2015</div>
</div>
<div class="Brief">Vivamus consectetur et sapien vel rhoncus. Maecenas gravida posuere hendrerit. Duis lobortis justo ac justo malesuada commodo. Proin iaculis, erat ac aliquet eleifend, neque felis tristique turpis, at dictum tellus lectus et lorem. Nunc turpis enim, auctor sed purus nec.</div>
<div class="More"></div>
<div class="Divider"></div>
</div>
My PHP
<?php
$query = 'SELECT title,newsDate,imagePath,content,websitePath FROM BananzaNews ORDER BY id Desc LIMIT 5';
$resultSe = mysql_query($query, $con);
if (mysql_num_rows($result) > 0) {
while($row = $resultSet->fetchRow ( DB_FETCHMODE_OBJECT )){
echo "<div class=\"Feed\">
<div class=\"Img\"><img alt=\"\" src=\"" $row->imagePath "\"></div>
<div class=\"Title\">" $row->title "</div>
<div class=\"Date\">
<div class=\"Day\">" $row->newsDate "</div>
<div class=\"Month\">" $row->newsDate "</div>
<div class=\"Year\">" $row->newsDate "</div>
</div>
<div class=\"Brief\">" $row->content "</div>
<div class=\"More\">" $row->websitePath "</div>
<div class=\"Divider\"></div>
</div>";
}
}
?>
Database View
You want to use MySQL's ORDER BY. You don't need to use num_rows to get the 5 latest posts. Simply order them by their id columns and then LIMIT it to 5. If they don't have id columns, they should have an id column that auto_increments and is a PRIMARY KEY. With that, this code will help you:
//Load your mysql_query into a variable SELECTing not *, but only the rows you need.
$query = mysql_query("SELECT title, newsDate, imagePath, content, websitePath FROM BananzaNews ORDER BY newsid DESC LIMIT 5") or die(mysql_error()); //<- Error handling.
//This loads up each row into an associative array into the variable $row
//So, $row['title'] will be equal to the 'title' column at that row in your database
while($row = mysql_fetch_array($query)){
//Output your repeating code
//Notice how I've used concat operators (dots) to stop the echo and start it again.
//I'd recommend looking those up if you haven't.
echo
'<div class="Feed">
<div class="Img"><img alt="" src="'.$row['imagePath'].'"></div>
<div class="Title">'.$row['title'].'</div>
<div class="Date">
<div class="Day">22</div>
<div class="Month">Jan</div>
<div class="Year">2015</div>
</div>
<div class="Brief">'.$row['content'].'</div>
<div class="More"></div>
<div class="Divider"></div>
</div>';
}
I would actually also use mysqli over mysql, mainly because it's well... mysql-improved. Do look into it, I highly recommend it. Even better, use PDO.
I hope this was helpful!
if you want to get the data to fetch run your query in while loop
$result=mysqli_query("select * from table_name order by id desc limit 0,5")
while($each=mysqli_fetch_array($result ))
{
//your code goes here
}
Use this query it will work for you
$query = 'SELECT title,newsDate,imagePath,content,websitePath FROM BananzaNews ORDER BY id Desc LIMIT 5';
$resultSet = mysql_query($query);
if (mysql_num_rows($query) > 0) {
while($row = mysql_fetch_array($resultSet)){
echo $row['title'];
echo $row['newsDate'];
}
}
You can loop your data like this.
Try this it will work :
1. use mysqli or pdo instead of mysql extension. It already depreciated and will be remove in future.
2. Loop your result set to get all the data from the table.
<?php
$result = mysqli_query($con,"SELECT * FROM BananzaNews LIMIT 0,5");
$rs = mysqli_fetch_array($result);
?>
<table>
<?php
do
{
?>
<tr>
<td><?php echo $rs['title']; ?></td>
<td><?php echo $rs['newsDate']; ?></td>
<td><?php echo $rs['imagePath']; ?></td>
<td><?php echo $rs['content']; ?></td>
<td><?php echo $rs['websitePath']; ?></td>
</tr>
<?php
}while($rs = mysqli_fetch_array($result));
?>
</table>
I'm trying to scrape product descriptions on a div based on its id. If the description is too long it shows a "show more". The div id's are short-description and long description.
My code works great on short-description but invisible to the DOM parser for long-description. How can I toggle the show more and then call the long-description ?
function my_function($str){
$url = $str;
// break apart ugly affiliate URL
list($chuck, $keep) = explode('=', $url);
// call simple DOM library
require_once 'libs/simple_html_dom.php';
// clean up unencoded URL
$keep = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($keep));
// Get HTML from clean URL
$html = file_get_html($keep);
//find div element
foreach($html->find('*/div[id="short-description"]') as $element){
echo $element;
}
}
Content I'm trying to get.
<div id='short-description'>
Eos inciderint interpretaris ea. Eam ut legere aperiri qualisque.
In propriae perfecto gubergren vix. Omnesque perpetua id duo,
no mel habeo appetere persecuti. Dico phaedrum qui ad, discere euripidis
delicatissimi vim cu.....
<a class='more'>Show More</a>
</div>
<div id='long-description' style='display: none;'>
Eos inciderint interpretaris ea. Eam ut legere aperiri
qualisque. In propriae perfecto gubergren vix. Omnesque
perpetua id duo, no mel habeo appetere persecuti. Dico phaedrum
qui ad, discere euripidis delicatissimi vim cu.Eos inciderint
interpretaris ea. Eam ut legere aperiri qualisque.
<a class='less'>Show Less</a>
</div>
</div>
Update: Solved
Code was working the entire time, didn't realize the raw output had the tags attached. It was including
style='display: none;
so I couldn't see my output result. I added
echo strip_tags($element);
and then I could see the output.
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.