I have almost created a fully working dynamic page using PHP OOP. I have successfully created a working menu - that is when a menu item is clicked, relevant text is displayed on the page. However, what I want is to have the home page text displayed by default and not solely clicking the Home link.
Here is the code I am using:
<?php
include_once('includes/connection.php');
include_once('includes/Article.php');
//instanstiating the article class and ssigning it to a variable
$article = new Article;
//assigning the contents of the method called fetch_all to the variable $articles
//this fetch_all method is inside the Articles class which is assigned to the above variable $article
$articles = $article->fetch_all();
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple PDO CMS</title>
<link rel="stylesheet" type="text/css" href="assets/styles.css">
</head>
<body>
<div class="container">
<table class="topMenu">
<tr>
<td>
<h1 class="siteName">site name</h1>
</td>
<!--Displaying the articles using a foreach loop-->
<?php foreach ($articles as $article){ ?>
<td class="navItem">
<?php echo $article['menuheader']; ?>
</td>
<?php } ;?>
</tr>
</table>
</div>
<p> this is where the time line will go</p>
<?php
//instanstiating the article class and ssigning it to a variable
$newArticle = new Article;
//checking if the user clicked the menu link
if (isset($_GET['id'])) {
//the display the article content
$id=$_GET['id'];
$data=$newArticle->fetch_data($id);
?>
<p><?php echo $data['bodytext']; ?></p>
<?php
} else {
}
?>
<p>This is where the footer will go</p>
</body>
</html>
So far I have tried: $id = 1; and using a redirect to index.php. Neither worked, the later due to 'to many redirects'.
I would like to keep the code I have used so far rather than redoing it again, so if you can help, please give me advice on this code.
Thanks
All you need to do is to set the id to 1 (or what ever your home page is) if there aren't any id passed in the url. No need for the if-statement.
Here's how it can be done using the null coalescing operator:
$newArticle = new Article;
// Sets the id to what $_GET['id'] is set to if it exists, otherwise, set it to 1
$id = $_GET['id'] ?? 1;
$data = $newArticle->fetch_data($id);
?>
<p><?php echo $data['bodytext'] ?? 'Page not found'; ?></p>
I also added in how you can show "Page not found" if $newArticle->fetch_data($id) didn't return anything.
Related
I have a mysql database named "drinks", in that database I have one table named "persons" and in "persons" I have two people, Bryan(fname) Fajardo(lname) 21(age) and Andross H Age:20.
In my index.php I have links set up from all of the people in table persons.
I am trying to get my links to work so that when I click on either name, the information relevant from that person is outputted into my other page (where the link goes to) which is: insert.php.
I have been trying for hours to run some test by clicking on the Bryan link and outputting only his last name etc. etc. My objective: is to be able to link the people from "persons" table and then upon click go to insert.php and output that person's information there.
Here is my current code from Index.php.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
//Connect to the database
$con = mysqli_connect("localhost","username","password","drinks");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo '<span style = "background: red ;">MSQL Connected.</span>' ;
}
$result = mysqli_query($con,"SELECT * FROM persons");
while($row = mysqli_fetch_array($result)) {
Print '<dd><a href=insert.php?
fname="'.$row['fname'].'">'.$row['fname'].'</a></dd>';
}
mysql_close();
?>
</body>
</html>
and here is my Insert .php where I want the relevant information to be printed.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class = "full-header">
<div class = "mid-header span12 center">
</div>
</div>
<div class = "main-content-container full_w">
<div class = "span12 main-content center">
<?php
$cont = mysqli_connect("localhost","username","password","drinks");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo '<span style = "background: red ;">yay</span>' ;
}
$fname = $_GET['fname'];
$sel = ($cont,"SELECT * FROM persons WHERE fname ='%$fname%'");
while($rower = mysqli_fetch_array($sel)) {
Print $rower['lname'];
//why is this not printing Bryan's last name?
}
?>
</div>
</div>
</body>
</html>
Thank you in advance, I appreciate the help, I have just recently gotten into php and database building/summoning.
EDIT: I also have been reading that this is becoming deprecated and PDO is going to be used now, if you have a solution that involves PDO, I would appreciate that as well, but I am very new to PDO.
EDIT 2: Changed "table" to "persons" in insert.php query.Still did not fix.
I can understand how it is when first starting out. Once you wrap your mind around the basic parts of it the rest will flow.
Since you asked for a better way I am going to suggest a class I personally use in all my projects.
https://github.com/joshcam/PHP-MySQLi-Database-Class
Of course don't forget to download the simple MYSQLI class from the link above and include it just like I do below in your project. Otherwise none of this will work.
Here us the first page which contains the table with all the users from your persons Db table. We list them in a table with a simple edit/view button.
PAGE 1
<?php
require_once('Mysqlidb.php');
//After that, create a new instance of the class.
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
//a simple select statement to get all users in the DB table persons
$users = $db->get('persons'); //contains an Array of all users
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<th>
First Name
</th>
<th>
Last Name
</th>
<th> </th>
<?php
//loops through each user in the persons DB table
//the id in the third <td> assumes you use id as the primary field of this DB table persons
foreach ($users as $user){ ?>
<tr>
<td>
<?php echo $user['fname'];?>
</td>
<td>
<?php echo $user['lname'];?>
</td>
<td>
<a href="insert.php?id=<?php echo $user['id']; ?>"/>Edit/View</a>
</td>
</tr>
<?php } ?>
</table>
</body>
</html>
So that ends your first page. Now you need to include this code on your second page which we are assuming is called insert.php.
PAGE 2
<!--add this to your insert page-->
<?php
require_once('Mysqlidb.php');
//After that, create a new instance of the class.
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
//a simple select statement to get all the user where the GET
//variable equals their ID in the persons table
//(the GET is the ?id=xxxx in the url link clicked)
$db->where ("id", $_GET['id']);
$user = $db->getOne('persons'); //contains an Array of the user
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>user ID</th>
<tr>
<td>
<?php echo $user['fname'];?>
</td>
<td>
<?php echo $user['lname'];?>
</td>
<td>
<?php echo $user['id']; ?>
</td>
</tr>
</body>
</html>
You have two main errors. On index.php you are wrapping your query string values in quotes
Print '<dd><a href=insert.php?
fname="'.$row['fname'].'">'.$row['fname'].'</a></dd>';
This should really be
Print '<dd><a href="insert.php?
fname='.$row['fname'].'">'.$row['fname'].'</a></dd>';
Next, on your second page, you need to use LIKE on your query.
$sel = ($cont,"SELECT * FROM persons WHERE fname LIKE '%$fname%'");
That said, you really should use parameters because the current method is going to open your script up to SQL Injection, and you should consider using a primary key in your querystring instead of passing the person's name.
Print '<dd><a href="insert.php?
id='.$row['id'].'">'.$row['fname'].'</a></dd>';
And your query
$id = intval($_GET['id']);
$sel = ($cont,"SELECT * FROM persons WHERE id = $id");
One final note, on your index page, you are using mysql_close instead of mysqli_close to close your database connection.
I am trying to make a website and it's almost completed but I want to add a view counter so when someone visit the page it count the view and save it into the database.
My script is working fine but the problem is that it continue view count even visitor is viewing anyother page
My pages url show like this
pictures.php?ID=13
I have added this PHP code in *count.php*
<?php
session_start();
if (isset($_SESSION['views'])){
$_SESSION['views']++;
} else {
$_SESSION['views'] =0;
}
//echo $_SESSION['views'];
?>
Page *views.php*
<?php
session_start();
if (isset($_SESSION['$post_id'])){
$_SESSION['$post_id']++;
} else {
$_SESSION['$post_id'] =0;
}
//echo $_SESSION['views'];
?>
<?php
echo "<hr><div align=\"center\">";
echo $_SESSION['$post_id'];
?>
<?php
$save = $_SESSION['$post_id'];
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE save_data SET Views='$save' WHERE ID='$page_id'");
mysqli_close($con);
?>
And added this line in Pictures.php where I want to show and count visits
<?php include("views.php"); ?>
Problem:
When someone visits page pictures.php?ID=8 it will show him page view 1 and save this view in database where ID=8, when he visit page pictures.php?ID=12 it will show him view 2 and save this 2 in database where ID=12. My point is that it is continuously counting instead of each page view.
Thanks in advance
Here is Pictures.php
<?php
include("connection.php");
if(isset($_GET['ID'])){
$page_id = $_GET['ID'];
$select_query = "select * from save_data where ID='$page_id'";
$run_query = mysql_query($select_query);
while($row=mysql_fetch_array($run_query)){
$post_id = $row['ID'];
$post_title = $row['Title'];
$post_image = $row['Name'];
?>
<h3>
<a href="pictures.php?ID=<?php echo $post_id; ?>">
<?php echo $post_title; ?>
</a>
</h3><center>
<form id="search-form" action="javascript:void(0);">
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Resize" Onclick ="splitString()"/></form>
<div id="sizet">
Type size like 200*300 in box
</div></center>
<div id="img"><img id="myImage" src="uploads/<?php echo $post_image; ?>" /></div>
<?php } }?>
<center>
<div id="postdetails">
<?php include("posted_by.php"); ?></center>
</div>
<?php include("views.php"); ?>
<html>
<link href="css/Pictures.css" rel="stylesheet" type="text/css">
<body>
<head>
<script type="text/javascript">
function splitString()
{
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");
document.getElementById("myImage").width=splitDimen[0];
document.getElementById("myImage").height=splitDimen[1];
}
</script>
</head>
</body>
Variables inside of single quotes are not evaluated, so regardless of whether $post_id is 8 or 12, $_SESSION['$post_id'] is setting the key named literally $post_id, rather than the key named 12 or 8. Variables are evaluated inside double quotes, so $_SESSION["$post_id"] would work, but the simplest and best way is to use $_SESSION[$post_id] instead.
Additionally, using $_SESSION here is probably not what you want to do. $_SESSION will be different for every user who visits the site, so when a new visitor comes to the site, it will start over with a count of 1. What you probably want to do is load the views value from the database, add one to it, and then save it back to the database. $_SESSION is for keeping data that is specific to a certain user.
Try to use structure like this
$_SESSION['view'][{resource_name}_{resource_id}]
E.g. for picture with id 8 it will be
$_SESSION['views']['picutures_8']++
I'm creating a web site directory for my mobile site (FOUND HERE)
I have figured out how to display listings from my mysql table to my home page from my tables promo_cat list.
The thing im having trouble with is this:
once clicking on one of the catagories it leads me to my list.php page.
How do I get this page to display results related to the category clicked and not others?
For example:when clicking on "FREE" brings up this page: http://www.xclo.mobi/xclo2/list.php?id=FREE. Which displays all results. it should only display results that have a promo_cat field as "FREE" and should not display any other results as it does currently.
My list.php code:
<?php
include_once('include/connection.php');
include_once('include/article.php');
$article = new article;
$articles = $article->fetch_all();
?>
<html>
<head>
<title>xclo mobi</title>
<link rel="stylesheet" href="other.css" />
</head>
<body>
<?php include_once('header.html'); ?>
<div class="container">
Category = ???
<ol>
<?php foreach ($articles as $article) { ?>
<div class="border">
<a href="single.php?id=<?php echo $article['promo_title']; ?>" style="text-decoration: none">
<img src="<?php echo $article['promo_image']; ?>" border="0" class="img" align="left"><br />
<img alt="" title="" src="GO.png" height="50" width="50" align="right" />
<font class="title"><em><center><?php echo $article['promo_title']; ?></center></em></font>
<br /><br />
<font class="content"><em><center><?php echo $article['promo_content']; ?></center></em></font>
</div><br/><br />
</a>
<?php } ?>
</ol>
</div>
</body>
</html>
/include/article.php
<?php
class article {
public function fetch_all(){
global $pdo;
$query = $pdo->prepare("SELECT * FROM mobi");
$query->execute();
return $query->fetchAll();
}
public function fetch_data($promo_title) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM mobi WHERE promo_title = ?");
$query->bindValue(1, $promo_title);
$query->execute();
return $query->fetch();
}
}
?>
You need to make changes to the code for list.php based on the input it gets through GET parameter. something like:
if ($_GET['id'] == 'FREE'){
// do something like display FREE items
}
elseif($_GET['id'] == 'GIFT') {
// display GIFT items
}
else {
// perform some default action
}
This is to make it even more database driven (helpful when there are many categories):
$sql = "select * from categories where id = '".$_GET['id']."'";
if (mysql_results($sql)){
// do something
}
else {
// show error
}
Note that this is for demo only and in your code you should use PDO/MySQLI and prepared statements and not mysql_results function.
In light of more information provided by OP:
Change this
$articles = $article->fetch_all();
to
$articles = $article->fetch_data($_GET['id']);
in list.php and see if you get correct results.
Based on the code you provided, try this:
<?php foreach ($articles as $article) {
if ($article['promo_cat'] === 'FREE') { ?>
// Keep the rest of the code
//instead of <?php } ?> - put...
<?php } } ?>
Keep in mind, this is messy. But the foreach statement (I imagine) is being used to print out all posts. So, before printing out a post, you just check to see if the promo_title is FREE, GIFT, etc. If it's not, then it doesn't print that item.
You can make this more dynamic by passing in a $_GET variable (which you apparently are doing, but the code is never using this variable) with the current promo title and altering the conditional line to say
if ($article['promo_cat'] === $_GET['id'])
Hope that helps!
I am currently creating a CMS.
Currently I have.
* Saved my images in mysql as app_image
* Saved the images as a URL to where the images are located
But creating MY INDEX PAGE only displays my link as a broken URL.
my code for this page:
<?php
include_once('include/connection.php');
include_once('include/article.php');
$article = new article;
$articles = $article->fetch_all();
?>
<html>
<head>
<title>testing</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
CMS
<ol>
<?php foreach ($articles as $article) { ?>
<li>
<a href="article.php?id=<?php echo $article['app_id']; ?>">
<img src="<?php echo $article['app_image']; ?>" height"100" width"100">
<?php echo $article['app_title']; ?>
</a> -
<small>
Posted: <?php echo date('l jS', $article['article_timestamp'] ); ?>
</small></li>
<?php } ?>
</ol>
<br><small>admin</small>
</div>
</body>
</html>
Can anyone see how I have gone wrong?
Thanks.
OK, I have done simalar thing and it is working just fine.
The code looks similar, and looks fine by me, now, maybe the link indeed is broken (maybe you didn't input the right upload link in DB)
I would go step by step and check that link (check if it is the right link). (with /path/name.ext)
If it is some help here is my case:
I put in DB post_id,post_title,post_contents, post_link
than i get that info with:
$query = $db->prepare ("SELECT bla bla FROM bla bla ORDER BY id DESC")
$query->execute();
$query->bind_result(everything that is selected seperated with ",");
(including $link)
<?php
while($query->fetch()):
?>
<a href="single-post.html" title="">
<img src="../images/<?php echo $link; ?>">
</a>
<?php
}
?>
NOW, the trick I did (to avoid problem is that i put inside DB only the name of file, the upload path is stored directly in HTML ("../images/")
Your code looks similar, and I think it should work, I think the problem is with link.
Var dump can come to the rescue here. Try this to see what the array key values should be set to for each of the elements in $article.
<?php foreach ($articles as $article) { ?>
echo '<pre>'; //just makes it a bit easier to read
var_dump($article); exit;
I am sure this is a fairly simple question to answer, but I am new to PHP, so I was hoping someone could help me solve this problem.
I have a dynamic navigation menu that works really well, but I want to remove the link from the current page in the menu.
Here is my code:
<div id="navigation_menu">
<?
foreach($pagedata->menu as $menuitem){
$class = ($menuitem->uri == $requesteduri) ? 'navigation selection' : 'navigation page_select';
?>
<div id="<?=$menuitem->uri?>" class="<?=$class?>">
<img class="nav_icon" src="<?=PROTOCOL?>//<?=DOMAIN?>/img/<?=$menuitem->uri?>.png">
<h1><?=$menuitem->title?></h1>
<h2><?=$menuitem->description?></h2>
<img class="go" src="<?=PROTOCOL?>//<?=DOMAIN?>/img/go.png">
</div>
<?
}
?>
</div>
Any help would be greatly appreciated. Thanks!
UPDATED CODE: (this is what works for me now)
<div id="navigation_menu">
<?
foreach($pagedata->menu as $menuitem){
$class = ($menuitem->uri == $requesteduri) ? 'navigation selection' : 'navigation page_select';
?>
<div id="<?=$menuitem->uri?>" class="<?=$class?>">
<img class="nav_icon" src="<?=PROTOCOL?>//<?=DOMAIN?>/img/<?=$menuitem->uri?>.png">
<h1>
<?php if ($menuitem->uri == $requesteduri):?>
<?=$menuitem->title;?>
<?php else: ?>
<?=$menuitem->title?>
<?php endif;?>
</h1>
<h2><?=$menuitem->description?></h2>
<img class="go" src="<?=PROTOCOL?>//<?=DOMAIN?>/img/go.png">
</div>
<?
}
?>
</div>
I don't know what your loop is outputting, but you want to match your page name with the menuitem->uri. So you'd get your page name like.. (Put this outside the loop)
<?php echo base_name($_SERVER['REQUEST_URI']); ?>
find out what your loop is outputting (Put this in the loop):
<?php echo $menuitem->uri; ?>
Then you'd create an if statement to compare the current menuitem in the loop and the page request, this is just an example:
<h1>
<?php if (base_name($_SERVER['REQUEST_URI']) == $menuitem->uri):?>
<?=$menuitem->title?>
<?php else: ?>
<?=$menuitem->title;?>
<?php endif;?>
</h1>
Put a conditional around the anchor text to see if $menuitem->uri is equal to the current page URL, accessible from `$_SERVER['REQUEST_URI'] before outputting the anchor tags.