I working on a simple project, and basically what I am doing is that I am creating a simple page from admin panel and then displays it in another page using iframe...
So in the process of displaying the page names, I managed to display all the page names that I have in the database. However, when I try to give them a link so when the user click on them, it redirects them to the specific page. So if there is a page named: new york and he clicks on it, it goes to: /pages/newYork.php ...
The problem: When I give them a link, only 1 page link is given for all the pages. Example: If I had cities named: New York, Bangkok and Amsterdam, the link for all of those pages is only for New york.
Here is my code:
<?php
require_once '../connect.php';
session_start();
if(isset($_SESSION['loggedinAdmin'])){
}else{
header("Location: index.php");
}
// To display content:
$realDisplay = '';
$sql = mysql_query("SELECT * FROM cities");
while($row = mysql_fetch_assoc($sql)){
$displayName = $row['name'];
$realDisplay .= $displayName.'<br/>';
}
echo "<u align='center'>Page names:";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display Pages</title>
<style>
a{
text-decoration:none;
font-size:30px;
color:skyblue;
}
</style>
</head>
<body>
<div style="color:red;">
<a href="<?php echo 'pages/'.$displayName.'.php'?>">
<?php echo $realDisplay;?>
</a>
</div>
</body>
</html>
Any thoughts of how to solve this? Also, if there is a better way to do it then it would be great.
Thanks in advance for everybody :)
First, move your loop to the page where you are actually going to display the data.
Second, keep your code clean and readable by putting things where they actually belong. ie. <u align='center'>Page names: doesn't belong where you put it. It goes in the body.
Third, don't forget to properly close your tags. <u align='center'>Page names: has no closing tag.
Finally, don't over-complicate it. You don't need two different vars for the same data row.
<?php
require_once '../connect.php';
session_start();
if(isset($_SESSION['loggedinAdmin'])){
}else{
header("Location: index.php");
}
// To display content:
//$realDisplay = '';
$sql = mysql_query("SELECT * FROM cities");
//while($row = mysql_fetch_assoc($sql)){
//$displayName = $row['name'];
//$realDisplay .= $displayName.'<br/>';
//}
//echo "<u align='center'>Page names:";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display Pages</title>
<style>
a{
text-decoration:none;
font-size:30px;
color:skyblue;
}
</style>
</head>
<body>
<div align="center"><u>Page names:</u></div>
<div style="color:red;">
<?php while($row = mysql_fetch_assoc($sql)){
$displayName =$row['name']
?>
<?php echo $displayName;?><br>
<?php } ?>
</div>
</body>
</html>
Related
I'm new to php and backend, I tried making a login and I wanted to buttons to change the background colour. Instead of using javascript, I use php to program it, to create sessions.
Below is the code. The buttons work in the url bar, but nothing is happening.
What am I missing or overseeing?
<?php
// Initialize the session
session_start();
require_once "config.php";
session_start();
require_once "config.php";
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$sql = "SELECT background FROM users ORDER BY id DESC";
$backgroundColour = [];
$colour = [];
$result = $link->query($sql);
$data = [];
while ($row = $result -> fetch_object()) {
$data[] = $row;
}
$backgroundColour['backgroundColour'] = $data;
$_SESSION['colour'] = $colour;
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
$_SESSION['colour'] = $colour;
}
$colour_session = $_SESSION['colour'];
$sql = "INSERT INTO users (background) VALUES ('$colour_session')";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>Choose background color</h1>
Hvid
Sort
</div>
<title>Welcome</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<h1 class="my-5">Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
<p>
Reset Your Password
Sign Out of Your Account
</p>
</body>
</html>
At least you need to tell the client side (the browser) that the background color is set as $_SESSION["color"] (e.g. black)
So, one of the ways is to add the following line to the end of your script (your script already has <body></body>) :
<?php
echo '<script>document.body.style.backgroundColor = "'. $_SESSION['colour'] . '";</script>';
?>
So, omitting the db part, the code (tested, fully working) will be
<?php
session_start();
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
$_SESSION['colour'] = $colour;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>Choose background color</h1>
Hvid
Sort
</div>
</body>
<?php
echo '<script>document.body.style.backgroundColor = "'. $_SESSION['colour'] . '";</script>';
?>
For the db part:
You may need to re-write the part on the db queries. For example, apart from the need to use parameterized prepared statement in your query (to avoid SQL injection attacks). Consider using "update user set background=? where id=?" instead of an insert query, For a multi-user system, it will be something like:
$sql = "UPDATE users SET background=? WHERE id=?";
$stmt= $link->prepare($sql);
$stmt->bind_param("si", $_SESSION['colour'], $_SESSION["id"]);
$stmt->execute();
It is because each user should have only a single record in the db table (so logically it is an update instead of an insert).
I'm fetching some data from a MySQL database onto a WebPage. I came up with a simple PHP page that queries the database and shows the query in the form of a table and it works just fine.
However, when I try to add bootstrap to the page and style it, the entire page stops working.
Here's my index.php
<!DOCTYPE html>
<html>
<head>
<title>MakersBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<center>
<h1>Sensor Testing Dashboard</h1>
<div class="container">
<?php
echo "<table class='table table-hover' align=center>";
echo "<thead><tr><th>Sensor Id</th><th>Temperature</th><th>Light</th><th>Last Updated</th></tr></thead>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "paanikiboond";
$dbname = "testbox1";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM sensor ORDER BY LastUpdate DESC LIMIT 1");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
</div>
$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>
</body>
</html>
Any idea what I may be doing wrong here?
First, I think you must separte properly your HTML, and your PHP.
In your code, mixte HTML tag + HTML tag from PHP code in your HTML body is... not too regulatory. And very difficult to maintain.
You can, create an architecture like that :
<?php
// Create connexion, and get your results.
$connexion = new PDO();
$results = [];
?>
<!DOCTYPE html>
<html>
<head>
<!-- Your link and scripts-->
</head>
<body>
<h1></h1>
<div>
<?php if (!empty($results){ ?>
<table class='table table-hover'>
<!-- Show your results. -->
<? foreach($results as $result)
{
}
?>
</table>
<?php }else{
echo 'no results found';
}
?>
</div>
</body>
</html>
Also, Boostrap is a Javascript library, It doesn't work directly on PHP, but it read the HTML structure, with your elements and their classes. If your javascript is loaded, and your structure is well done, that work! You have samples and documentation of Boostrtap here;
In your code you forgotten to close your <head></head> element and you've a problem in this lines :
echo "</table>"; // that is PHP, but PHP is not close with `?>`
</div> <!-- That is HTML but in PHP code witouth `echo ''` -->
If PHP and HTML has well separted, you will have fewer problems of forgetting :D You have many links in Internet for understand this good practise
PS : don't forgot to code with proper line indentions: it's much more readable:
<html>
<head> <!-- Very difficult to see we havn't a </head> close tag -->
<body>
<div>
My content
</div>
</body>
</html>
<html>
<head> <!-- Very easy to see we havn't a </head> close tag -->
<body>
<div>
My content
</div>
</body>
</html>
Hope I help you.
for one thing you arent closing your <head>, so your code should be
<!DOCTYPE html>
<html>
<head>
<title>MakersBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
...
EDIT: close to the bottom your code should look like
...
echo "</table>";
echo "</div>";
$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>
</body>
</html>
</center><!--that where you forgot to add this as it needs to be closed off-->
</body>
</html>
Also, you might be better off put Javascript on the bottom of the pages, Not sure if it will work.
Second things you need use Web developer tools to diagnosed this issues. it will help a lot. also, you might need to test out different browser if it's same issues or not.
I tried your code. I only find these three mistakes:
You must use echo for build HTML code from PHP and then close your
div container
$conn = null;
echo "</table>";
//wrong way expecting statement
</div>
//correct way for use HTML inside PHP tags
echo "</div>";
The line where you add a header "refresh" generate a warning because
"Cannot modify header information - headers already sent"
$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
You use <center> tag that it's deprecated so you should use CSS instead and you not close this tag
Problem :
User is already logged in
so when I type
local.test_php.com/form/
It takes me to Login page. local.test_php.com/form/index.php
But i want it to take it to my home page instead.(http://local.test_php.com/form/home.php)
what i want is like what facebook does when we type facebook.com (already logged in before) we r redirected to the news feed ... but in my case i get redirected to Login page(even if i'm already logged in) so i have to login again or type the url to get to the home page
I don't know how to customize sessions to always redirect to home page whenever user is logged in. It should not take me to login page in any condition.
Home page looks like this:
<!DOCTYPE html>
<html>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<head>
<title>My first PHP Website</title>
</head>
<body>
<h2 align="center">Home Page</h2>
<?php
session_start();
if(isset($_SESSION['user'])){
}else{
header("location: index.php");
}
$user = $_SESSION['user'];
echo "<br>";
echo "WELCOME ".$user." ";
echo "<br>";
echo "Do you want to ";
print 'logout';
echo " ?";
echo "<br>";
?>
</body>
</html>
I rewrote your code a littlebit, so it's more readable now.
First of all, when you want to use header function on your page, or start a session, you should do it before anyhing in the output buffer.
As you see, I removed the echo things, if you use an IDE as an editor, syntax highlighting help you to read the code, and be sure, it is valid.
The second thing, if you want to "remember" for user, when user closes all the browsers what stored the session variables, then you need to give a shot for cookies. But first, fix the code.
<?php
session_start();
if (!isset($_SESSION['user'])) {
header("location: index.php");
}
?><!DOCTYPE html>
<html>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<head>
<title>My first PHP Website</title>
</head>
<body>
<h2 align="center">Home Page</h2>
<?php
if (!empty($_SESSION['user'])) {
?>
<p>WELCOME <?php echo $_SESSION['user']; ?></p>
<p>Do you want to logout?</p>
<?php
}
?>
</body>
</html>
try this:
<?php
session_start();
if(isset($_SESSION['user'])){
}else{
header("location: index.php");
}
$user = $_SESSION['user'];
echo "<br>";
echo "WELCOME ".$user." ";
echo "<br>";
echo "Do you want to ";
print 'logout';
echo " ?";
echo "<br>";
?>
<html>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<head>
<title>My first PHP Website</title>
</head>
<body>
<h2 align="center">Home Page</h2>
the problem with your code is that you want the header function after html output
So here's an example code I use to show all the categories that are linked to a certain postID.
For example post 1 has the categories: Apple, Green and Yellow linked to it.
But I can't seem to fetch the data correctly since it has already been fetched once at the top i can't do a proper while loop at the Categories: part of my code where I try to do a while loop. The while loop works and fetches all the categories except the First one and also when I place the while loop the
$row['postTitle']
and
$row['postCont']
won't appear anymore because it's being skipped. How would I fix something like this? Thanks.
<?php require('includes/config.php');
$stmt = $db->prepare(" SELECT *
FROM blog_posts
LEFT JOIN blog_posts_categories ON blog_posts.postID=blog_posts_categories.postID
INNER JOIN blog_categories ON blog_posts_categories.catID=blog_categories.catID
WHERE blog_posts.postID = :postID");
$stmt->execute(array(':postID' => $_GET['id']));
$row = $stmt->fetch();
//if post does not exists redirect user to homepage.
if($row['postID'] == ''){
header('Location: ./');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $row['postTitle'];?> | Website</title>
<link rel="stylesheet" href="style/normalize.css">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div id="wrapper">
<h1>Single Post Page</h1>
<hr />
<p>Home |
Categories:
<?php while($row = $stmt->fetch())
{
//the first category is being skipped? How to fix?
echo $row['catName'];
} ?>
</p>
<div>
<?php
//these won't appear because of the while loop. It's being skipped.
echo '<h1>'.$row['postTitle'].'</h1>';
echo '<p>'.$row['postCont'].'</p>';
?>
</div>
</div>
</body>
</html>
Replace:
while($row = $stmt->fetch())
{
echo $row['catName'];
}
With:
do {
echo $row['catName'];
} while($row = $stmt->fetch());
As for the other items - put them inside the loop obviously instead of afterwards.
Greetings,
I am a newbie who just started with jQuery. I am building a basic PHP app for our team that displays a list of open helpdesk tickets.
To avoid cluttering the screen, I only want to display the title of the ticket and if clicked, its description.
Here's my code
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Animate my Div</title>
<style type="text/css" media="screen">
a { text-decoration: none; }
#expand { background-color: #fff; }
#mydiv { display: none; }
</style>
<script src="jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript"> $(document).ready(function(){
$("a").click(function(){ $("div").slideToggle(1000); });
}); </script>
</head>
<body>
<?php
$con = mysql_connect("korg", "joe", "bob");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("wfr11", $con);
$result = mysql_query(" select title, description from webcases");
while ($row = mysql_fetch_array($result)) {
?>
<p><?php echo $row['title']; ?></p>
<div id="mydiv"><?php echo $row['description']; ?></div>
<?php
} mysql_close($con); ?>
</body>
</html>
Right now, my code works but unfolds all the divs for all open tickets, regardless of what ticket name I clicked.
Ideally, I'd like to show the description of for the ticket name I clicked. Not all of them. Is it possible?
Thanks for your help.
Entirely possible, yes.
First issue you have is that you are repeating an ID in the loop, HTML IDs must be unique. I would suggest using a class there. Wrap the two components together in a DIV to make them in to a combined item that can be dealt with individually as well
<?php
while ($row = mysql_fetch_array($result)) {
?>
<div class="entry">
<p><?php echo $row['title']; ?></p>
<div class="description"><?php echo $row['description']; ?></div>
</div>
<?php
}
?>
Then, you need to make your jQuery select just the adjacent description DIV.
$(document).ready(function(){
$(".entry a").click(function() {
$(this).parents('.entry').find('.description').slideToggle(1000);
});
});
Remember to use htmlentities() on your echo's from the database if they are not already in proper HTML form.
Yep, you're after a toggle. Maybe use an id to select the divs you want rather than just the plain div.
$(".link_class").click(function(){ $("#my_div").slideToggle(1000); });
Target particular divs by assigning a class to the link.