I have a nice page including system here is the code for it
if(isset($HTTP_GET_VARS['mod']))
{
$page = $HTTP_GET_VARS['mod'];
}
else
{
$page = 'home';
}
switch($page)
{
case 'home':
require('home.php');
break;
default:
echo('Error: There is no file on this server with that name');
}
}
I am trying to get the case, require from a DB called pages there are 2 fields Name, Link i am trying to get all of the results from the table so it will display the pages
It's not particularly clear from your question, but my reading of it is that you want a way to check any value of $page against a link value in a db table (pages?), without having to write all possible values in to your switch statement,
If my understanding is correct, then the below is a quick-and-dirty function which should let you do this. In a live, heavily-trafficed environment you'd obviously need to build in caching so every page load doesn't hit the db, and strong input validation, neither of which are in the demo below, but this should at least give you an idea of where to go next.
Common library file:
/**
* Given a page name, see if we have an associated
* link in the db.
* If so, return the link value, else false
*/
function getTemplate($page)
{
// Check db to see if we have a link for this page
// On heavy-traffic sites, this should be cached out
$query = sprintf("SELECT link FROM pages WHERE name = '%s'",
mysql_real_escape_string($page));
$result = mysql_query($query, $db_cnx);
// Have we any results?
if (mysql_num_rows($result) > 0)
{
// Assumption: 'name' is unique in the db
$row = mysql_fetch_assoc($result);
return $row['link'];
}
else
{
return false;
}
}
Header.php:
include('common.lib.php');
if(isset($HTTP_GET_VARS['mod']))
{
$page = $HTTP_GET_VARS['mod'];
}
else
{
$page = 'home';
}
// Check whether our page has a link in the db
$template = get_template($page);
if($template)
{
require( $template );
}
else
{
// Got false back from get_template, no link found
echo('Error: There is no file on this server with that name');
}
$server_db = "YOUR_SERVER_DB";
$user_db = "YOUR_USER_DB";
$password_db = "YOUR_PASSWORD_DB";
$db_name = "YOUR_DB_NAME";
$table = "YOUR_TABLE_NAME";
$link = mysql_connect($server_db,$user_db,$password_db);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name);
$sql = sprintf("select Name, Link from %s",$table);
$rs = mysql_query($sql,$link);
while($row = mysql_fetch_assoc($rs)) {
echo "<a href='".$row['Link']."'>".$row['Name']."</a>";
}
mysql_free_result($rs);
mysql_close($link);
Related
I'm trying to count page views on page load, although anytime I load the page 'UPDATE SET views = views + 1' is actually adding 2. I've got my code below, if any one has any suggestions that'd be awesome.
// Create database connection
$db = new mysqli($db[host], $db[user], $db[pass], $db[data]);
// Display database connection error (if applicable)
if (mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
}
// Define Visitor Variables
$visitor[ip] = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
// Checks database to see if ip exists in logs
$check[ip] = $db->query("SELECT ip FROM admin_views WHERE ip = '$visitor[ip]'");
// If ip is found in database, update page views counter if it's not found, create a record for it
if ($check[ip]->num_rows == 1){
$db->query("UPDATE admin_views SET views = views +1 WHERE ip = '$visitor[ip]'");
} else {
$db->query("INSERT INTO admin_views VALUES('NULL', '$visitor[ip]')");
echo "not found";
}
// Count the number of views
$count_views = "SELECT SUM(views) AS countViews FROM admin_views";
if ($result = $db->query($count_views)) {
while ($row = $result->fetch_assoc()) {
$views = $row['countViews'];
}
$result->free();
}
// Count unique page views
$count_unique_views = "SELECT id FROM admin_views ORDER BY id DESC LIMIT 1";
if ($result = $db->query($count_unique_views)) {
while ($row = $result->fetch_assoc()) {
$unique_views = $row['id'];
}
$result->free();
}
// Close database connection
$db->close();
I'm trying to $_get part of URL in a href. What I want to happen is when you click the link you a redirected to that specific link. If that makes sense.
I have 2 functions:
First function, The list of links:
function showPosts() {
$sql = ("SELECT * FROM blog");
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$listId = $row["blog_id"];
$showTitle = $row["title"];
$showContent = $row["content"];
$showTimestamp = $row["timestamp"];
echo'
<div>
<h3>'.$showTitle.'</h3>
<div>'.$showContent.'</div>
<p>'.$showTimestamp.'</p>
</div>
';
}
}
Second function, redirect to link:
function viewPost() {
if(empty($_GET['id']) ) {
$listId = '';
} else {
$listId = $_GET['id'];
}
$sql = ("SELECT title, content, timestamp FROM blog WHERE blog_id='.$listId.'");
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$showTitle = $row["title"];
$showContent = $row["content"];
$showTimestamp = $row["timestamp"];
echo'
<div>
<h2>'.$showTitle.'</h2>
<p>'.$showTimestamp.'</p>
<div>'.$showContent.'</div>
</div>
';
}
}
As you can see i'm using $_get['id'] here and I read that $_get can be used to retrieve passed url parameters.
The way i have set up the URL is defined by a set of variables in a switch.
if(empty($_GET['task']) ) {
$task = 'show';
} else {
$task = $_GET['task'];
}
switch ($task){
case "create":
createPost();
die();
break;
case "save":
savePost();
die();
break;
case "show":
showPosts();
die();
break;
case "view":
viewPost();
die();
break;
default: echo'Something went wrong!';
}
Currently when I click a link, it redirects but all of the content related to that id is not there.
You are misusing the die() command in the switch. Die command is used to handle errors, it stops immediately the script execution and returns the error message set as argument. Try removing it.
I have a page which only admins can access once they click a link. If the logged in user is a standard user then they should not be able to access the page. However, when a standard user tries to access the admin page they have access to the page.
I would appreciate a pair of second eyes to see if they can spot anything wrong with the code which would make the functionality work as intended.
Thanks
<?php
if(check_login() && isAdmin()) {
echo 'welcome administrator';
} else {
header('Location: login.php');
exit;
}
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID ='" . $_SESSION['sess_uid'] . "'";
$mainaccess = $conn->query($sql);
print_r($mainaccess);
if(!$mainaccess){
echo $conn->error;
}
if ($mainaccess -> userLevel == 0) {
return true;
} else {
return false;
}
}
function check_login () {
if(isset($_SESSION['sess_uid']) && $_SESSION['sess_uid'] != '') {
return true;
} else {
false;
return;
}
}
?>
The issue is that you are selecting from the database users where they have admin access already ie
SELECT `userID` FROM `usertable` WHERE `userLevel` = 0
So you are always showing anyone as an admin. The query needs to be changed to check specifically if the logged in user is an admin. So changing the query to something like so
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
Where $_SESSION['sess_uid'] is the userID
We have to remove both the userLevel check, as this is irrelevant when selecting the user, we also have to change from SELECT userID, to SELECT *, as if you only select the userID, you will not have the userLevel in your array and the line
$mainaccess -> 'userLevel' == 0
Will not work. By selecting everything you ensure all attributes can be accessed, ie
$mainaccess -> 'userLevel'
$mainaccess -> 'userID'
Update
The correct way to access the table data will be using either
Object (this is the method you will use)
$mainaccess -> 'userLevel'// Incorrect
$mainaccess->userLevel //correct
Array
$mainaccess -> 'userLevel'// Incorrect
$mainaccess['userLevel'] //correct
Please change this line
You query is also incorrect please use this block of code as your sql query is not pulling in the right info.
function isAdmin()
{
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
if($result = $mainaccess = $conn->query($sql))
{
while($obj = $result->fetch_object())
{
$user = $obj;
}
}
if ($user->userLevel == 0)
{
return true;
}
else
{
return false;
}
}
You really need something like:
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT `userID` FROM `usertable` WHERE `userLevel` = 0 AND userID ='" . $_SESSION['sess_uid'] . "'";
As I said in the comments, you are looking for ANYONE with admin access, but you really want to know whether THIS user has admin access, therefore you have to validate what user you are trying to figure out has access. I just put the code together above, thinking you are storing the userID in the session (as per your later code) but you may need to change this
Your approach is wrong. The link should only be shown to logged in admins.
Try something like this test code.
<?php
session_start();
$_SESSION['admin'] = 0;//set only by logging in
$html ="Test<br>";//page html
if ($_SESSION['admin']== 0) {
$html .="<a href=\"adminpage.php\" >Admin</a>";
}
echo $html;
?>
Modify to suit your requirements.
I need a little help of my brilliant friends.
Actually i m new to development so that i have no much idea how can i show my page in words like www.testsite.com/index.php?pname=**Home** except of www.testsite.com/index.php?pid=**1**
i have the following code for showing page in number
if (!$_GET['pid']) {
$pid = '1';
} else {
$pid = ereg_replace("[^0-9]", "", $_GET['pid']); }
and the sql code
$sqlCommand = "SELECT id, link FROM main_page WHERE showing='1' ORDER BY id ASC";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$menu='';
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$link = $row["link"];
if ($linklabel){
$menu .=''. $link .'';
}}
i want to show and href name of page not id how can i do that.
help plz
Your example will fail if I enter *1*2*3*
you should be searching for the contents of
**(contents)**
and nothing else.
That will get you the name and the number.
Here is my example
$string = "**123naasdme456**";
preg_match("/[^\*+](?P<val>\w+)[^\*+]/",$string,$matches);
echo $matches[0];
will echo 123naasdme456
and here it is implemented into your code
function getReal($urlVar)
{
if(preg_match("/[^\*+](?P<val>\w+)[^\*+]/",$urlVar,$matches))
{
return $matches[0];
}
return false; // or default value
}
$pid = getReal($_GET['pid']);
$name = getReal($_GET['pname']);
You should add an extra field in your database (table main_page) with the name name or something similar. Then you could:
if (!$_GET['pname']) {
$pid = 'home';
} else {
$pid = mysql_real_escape_string($pid);
$sql = mysql_query("SELECT name FROM main_page WHERE name = '$pid'");
if (mysql_num_rows($sql) == 1))
{
echo "Content";
} else {
echo "404 error. Couldn't find the page you were looking for.";
}
}
URL Rewriting. http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/
Firstly, Thaks for taking a look at my question.
I have a function that works perfectly for me, and I want to call another function from within that function however I'm getting all kinds of issues.
Here are the functions then I'll explain what I'm needing and what I'm running into.
They are probably very messy, but I'm learning and thought I'd try get fancy then clean it up.
function GetStation($id){
$x_db_host1="localhost"; // Host name
$x_db_username1="xxxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
// SQL Query Setup for Station Name
$sql="SELECT * FROM stations WHERE ID = $id LIMIT 1";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$retnm = $rows['CallSign'];
}
mysql_close();
echo $retnm;
} // Closes Function
// List Delegates Function!!!!!!!!!!!!!!!!!!!
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_st_name = GetStation($StatNm);
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}
So I output ListDelegates() in a page and it displays a nice table etc.
Within ListDelegates() i use the GetStation() function.
This is because the table ListDelegates() uses contains the station ID number not name so I want GetStation($id) to output the station name
The problem I'm having is it seems GetStation() is outputting all names in the first call of the function so the first row in the table and is not breaking it down into each row and just one at a time :S
Here's what I think (I'm probably wrong) ListDelegates() is not calling GetStation() for each row it's doing it once even though it's in the loop. ??
I have no idea if this should even work at all... I'm just learning researching then trying things.
Please help me so that I can output station name
At the end of GetStation, you need to change
echo $retnm;
to
return $retnm;
You are printing out the name from inside the function GetStation, when you are intending to store it in a variable. What ends up happening, is that the result of GetStation is effectively echo'ed on the screen outside of any table row. Content that is inside a table but not inside a table cell gets collected to the top of a table in a browser. If you want to see what I mean, just view source from your browser after loading the page.
You don't need to connect to the database in each and every function. Usually you do the database connection at the top of your code and use the handle (in PHP the handle is usually optional) throughout your code. I think your problem is because when you call the function each time it makes a new connection and loses the previous data in the query.
My dear first of all you should place your code of connection with local host and database globally. It should be defined only once. you are defining it in both function.
something like this, and as suggested, you should have connection to database established somewhere else
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
//$d_st_name = GetStation($StatNm);
$sql="SELECT * FROM stations WHERE ID = $StatNm LIMIT 1";
while($rows=mysql_fetch_array($result)){
$d_st_name = $rows['CallSign'];
}
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}