It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
To begin with we're beginners to PHP, we're studying Multimedia Design and we have been assigned to make a website in plain HTML. Furthermore we also have to include some PHP (which must be object-oriented). Our idea is to call the URL from our Youtube videos in our database and each video should have a vote button attached.
We can easily call our videos to a specific page in a div box on our website. This is our video_class.php:
<?php class Video {
private $db;
public function insertVideo($videoId) {
$row = $this->db->query("SELECT url FROM video WHERE id = ".$videoId);
$ost = $this->db->loadRows($row);
echo '<iframe width="200" height="200" src="https://www.youtube.com/embed/' . $ost[0]['url'] . '" frameborder="0" allowfullscreen></iframe>';
}
public function setDatabaseConnection($db) {
$this->db = $db;
} } ?>
And the page we're loading it to:
<?php // Create database connection
// Load Database class file
require_once 'db_class.php';
//Creating new object instance from Database class
$db = new event();
// Run initiate function and provide credentials.
$db->initiate("localhost","root","","event");
$db->connect(); // Connect to MySQL database
// Load Video class file
require_once 'video_class.php';
$video = new Video;
$video->setDatabaseConnection($db);
$row=$db->query("SELECT url FROM video WHERE id = 1");
$ost=$db->loadRows($row);
//var_dump($ost);
$row1=$db->query("SELECT url FROM video WHERE id = 2");
$ost1=$db->loadRows($row1);
//var_dump($ost1);
$row2=$db->query("SELECT url FROM video WHERE id = 3");
$ost2=$db->loadRows($row2);
//var_dump($ost2); ?>
HTML:
<center><div class="video_clip">
<?php echo '<iframe width="200" height="200" src="https://www.youtube.com/embed/' . $ost[0]['url'] . '" frameborder="0" allowfullscreen></iframe>'; ?>
<img src="images/vote.png">
</div><!--video_clip end-->
But the real problem is next:
We have 3 videos you can vote on by clicking on the vote button, under each video. Each button must count the clicks and store it in our database. We have absolutely no clue how to make this possible. Our teacher told to link to a subpage (for example, "vote.php"). On that page we should use:
$_GET[id]
fetch id from $get
get current votes from video where id = 1/2/3
add+1
save votes in video where id=1
and finish with a redirect
Can someone help us? We have found a few possible solutions on the forums, but still no luck! Sorry for the long post and too much text :)
DATABASE STRUCTURE:
Table name:
users
Table comments: users
Column Type Null Default Comments MIME
id int(11) No
videoId int(11) No
Table name:
video
Table comments: video
Column Type Null Default Comments MIME
id int(11) No
url varchar(50) No
If you want to keep it simple, you might want to skip the part where the page doesn't reload. You can make a button do all sorts of javascript tricks (google jquery and ajax), but there's no need for this.
supposing your url is yourfile.php
Make a link called upvote beneath each video linking it to yourfile.php?voteid=xx
where xx is the id of the video
if you click the link, you get redirected to the same page, but now you have a get parameter
In your code, before you show the page, check if any votes are being cast
if(isset($_GET['voteid']){
//save vote!
}
Now you are on the same page, you retrieve the votes (one is higher then it was before), and you can just keep on going.
This is quite open-ended, so I'll add some clues to get you going.
Firstly, since your votes will affect the database, you should use post and not get (see here for more details)1. Once you've dealt with the operation, you can then do your redirect.
So, under your <iframe>, set up a <form> with a post method. In it, add three input tags each having a type of submit, and each having a different name attribute. For your action, you can aim it at a different page if you want to, but since it is simple I would point it at itself. Thus, use <?php echo $_SERVER[ 'PHP_SELF' ] ?> for the time being.
OK, so this will send the post data to the same page. Thus, in your page PHP, just after your database initialisation, catch the post op like so:
// Your existing code
$db->connect(); // Connect to MySQL database
// New code
if ($_POST) {
print_r($_POST);
exit();
// #todo Parse the result in your POST array
// #todo Save the result in the database
// #todo Redirect to self
}
// Load Video class file
require_once 'video_class.php';
What that will do is dump the post data on the screen, and then exit immediately. This is a good prototyping approach to see that you're on the right track.
Adding #todo notes is quite a good approach too - do these in order, and delete the comment when that piece is written and tested. Don't forget to add new comments explaining code, if appropriate.
1 If using the $_GET array is an essential component of the exercise, then you could use three post forms, each with their own button, and with the action containing a separate query string that will appear in the $_GET array. However I'd argue that's a bit convoluted, and probably not the best way to achieve this in practice.
Related
I have a database with just over 800 data.
product table
pid name p_page
1 money money.php
2 gold gold.php
3 .
. .
. .
800 .
I have 2 pages...
product_item.php
<div class="button">
View
</div>`
when you click view the product info is pass to product.php
in here i have
if (isset($_GET['pid'])) {
depending on what product the user clicked on the URL might look like something below but the 44 will change to whatever id
http://www.example.x10.mx/money.php?pid=44
the problem with this, is that money.php have a different layout to the other pages and if I change 44 to 68, the product info will show on the page but the layout will not look good.
My question
what is the best way for me to stop users from being able to change the url.
I want to encrypt all my pid in the url so it will look something like
http://www.example.x10.mx//money.php?sel=the product name here or 4 letters or anything
I just want to take away pid from the url.
Please help me. If you dont understand my question please ask in the comment and try and say what you think you understand.
Edited to show my fetch function
$php = "php/";
$apages = "account/";
$bpages = "booking/";
$gpages = "general/";
$ppages = "product/";
// Global functions
function fetchdir($dir)
{
$protocol = $GLOBALS['protocol'];
$host = $GLOBALS['host'];
($dir == $GLOBALS['apages'] || $dir == $GLOBALS['bpages'] || $dir == $GLOBALS['ppages'] || $dir == $GLOBALS['gpages'] ? $branch = $GLOBALS['pagebranch'] : $branch = $GLOBALS['branch']);
echo $protocol.$host.$branch.$dir;
}
Thanks
p.s. I dont know if this can be done in .htaccess but i think it can be done in php
Some clarification:
I have a url which looks like this
www.example.com/account/product.php?pid=1
the problem with this is that someone can change 1 or any number and if they is a pid in the database with that number it will get the items information and display on the page. Which I don't want to happen because not all product are meant to be display in some pages.
In the papge which i show all my available product. I simple uses a SELECT statement and then echo what I need in some div.
In that page I have a view button.
$stmt = $conn->prepare("SELECT * FROM Product WHERE Type = 'shoes'");
$stmt->execute();
$i = 0;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$id = ($row['pid']);
$product_page ($row['dir_page']);
<div class="button" >
<a href = "<?php fetchdir($apages) ?><?echo $product_page?ProdID=<?php echo $id>" > View</a >
</div >
}
Depending on the page that information is getting sent to when you click on view I use Get method
<?php
if (isset($_GET['pid'])) {
// Connect to the MySQL database
dbconnect();
$id = preg_replace('#[^0-9]#i', '', $_GET['pid']);
}
If you notice in my select statement used type to show only the product which type is shoes. I have other types as well, which as their other pages. Now the problem is if i change the pid to any page that doesn't have a type of shoes or if an in the other pages and enter a pid which type is shoes or anything, the information from that page will still render. Which I don't want to happen.
My question
how can i stop users from changing that pid and even if they change it. they will still be on the same page?
The problem isn't having the PID in the URL, it is having the template name in the URL.
Store the template name in the database (you are doing this already), and use that to determine what HTML to wrap the data in instead of putting it (money.php) in the URL.
Move your templates out of the web root (they shouldn't be hit by users directly), have a single index.php and then include() the template based on the data in the database.
You cannot prevent someone from changing the URL or from requesting arbitrary URLs. Your server (i.e. your app) has to decide how to respond to an invalid request. If you don't want to display certain things publicly, flag them as such in your database, test for that flag and simply refuse to output anything if that flag is hit.
Make the server respond negatively if something doesn't fit your conditions; don't expect the user to behave correctly.
Assuming that PID is a autoincrement value, you can still obfuscate it. Add another column in the table that contains a randomly-generated key (using uniqid or some derivative). Then use that key in your URL. You'll get something like: www.example.com/account/product.php?pid=II8GypI6H93Ij. This doesn't guarantee that someone won't find it, but it's good enough in most instances.
Check for allowance in the Database
Depending on your level of programming skills, in the database you could add a field or a relational table that relates the ID of the pages to allowed page templates (I'm guessing you're talking about templates.)
Then in the code you can make it so the page checks this database to see if the page contents are allowed to show. Something like:
$query1 = "SELECT * FROM Product WHERE Type = 'shoes' and allowedTemplate='1'";
This way you won't have to hardcode everything into the code itself. On the backend (if there is a CMS) then you could have checkboxes indicating the relationships to the templates and prefill them by default.
You'll need to make the site so something with that stuff though.
Your other option
You could use clean urls (which used to be better for SEO) to show real words instead of the IDs. Then you can use .htaccess tricks to convert the URIs to their ID counterparts with a dynamic RewriteMap.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to run PHP, specifically PHP I can't do it any other language, on click of a link with the class .URL
Specifically the PHP I need to run is this:
$list[4]+=10;
and the link that I need it to run on click of looks like this:
Some site's URL
I have heard about jQuery's ajax() function and its derivatives. But how can I do those to update the value of a PHP variable on click on .URL ?
First things first, most of your question is not possible in the way you want it done. Specifically incrementing a variable in PHP such that you have $list[4] += 10. I say this because when this script is run this won't exist anymore, you'd have to load it in from where ever you happen to be storing data (assuming a DB).
So, a short example of what you're trying to achieve you'll need a couple of files.
index.php - This is where your code happens that renders the page with the links on it.
link_clicked.php - This is called when a link is clicked.
You'll add need this basic Javascript in your code (it uses jQuery because you mentioned it in your question). I've broken this snippet into many pieces which is not how you'd normally write or see jQuery written to explain what is going on.
$(function() {
// Select all elements on the page that have 'URL' class.
var urls = $(".URL");
// Tell the elements to perform this action when they are clicked.
urls.click(function() {
// Wrap the current element with jQuery.
var $this = $(this);
// Fetch the 'href' attribute of the current link
var url = $this.attr("href");
// Make an AJAX POST request to the URL '/link_clicked.php' and we're passing
// the href of the clicked link back.
$.post("/link_clicked.php", {url: url}, function(response) {
if (!response.success)
alert("Failed to log link click.");
});
});
});
Now, what should our PHP look like to handle this?
<?php
// Tell the requesting client we're responding with JSON
header("Content-Type: application/json");
// If the URL was not passed back then fail.
if (!isset($_REQUEST["url"]))
die('{"success": false}');
$url = $_REQUEST["url"];
// Assume $dbHost, $dbUser, $dbPass, and $dbDefault is defined
// elsewhere. And open an connection to a MySQL database using mysqli
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbDefault);
// Escape url for security
$url = conn->real_escape_string($url);
// Try to update the click count in the database, if this returns a
// falsy value then we assume the query failed.
if ($conn->query("UPDATE `link_clicks` SET `clicks` = `clicks` + 1 WHERE url = '$url';"))
echo '{"success": true}';
else
echo '{"success": false}';
// Close the connection.
$conn->close();
// end link_clicked.php
This example is simplistic in nature and uses some unrecommended methods for performing tasks. I'll leave finding how to go about doing this properly per your requirements up to you.
I asked the same question earlier and it got down voted and I have no idea why. I'm building a class that outputs a news feed, but it's a very structured html that I'm going to use a lot on the site (hundreds of times), so I'm using a class method to display the feed html and everything. And I just echo the whole thing.
The method is set up this way:
private function feed ($var)
{
$Statement = $this->Database->prepare("SELECT * FROM feed WHERE col = ? ORDER BY timestamp DESC LIMIT 50");
$Statement->execute(array($var));
while ($row = $Statement->fetch(PDO::FETCH_ASSOC))
{
echo ' <div class="feed-box">
' . /*facebook name retrieved from the facebook */ . '
' . $row["post"] . '
<br/>
</div>';
}
} //end feed
The class is set up so that another method that has more of the html template calls this feed method. (I'm not trying to be too redundant here, but again the last time I asked this question it got down voted). So I'm pretty new to oop, and I'm looking to display the profile pictures of people who are logged in with facebook. This isn't necessarily a facebook question because I know how to do it normally, but I don't know how to get the facebook information within the class scope using just their id. Normally I;d get their picture by going linking to this url https://graph.facebook.com//picture. How do I do this within the class when I only sotre their facebook id in the database? I've been working on this problem for a couple days now, and I can't figure it out on my own. So I really appreciate your help.
It's getting to the point where I just want to statically type everything out because I know I could easily do that, but I'd really love to learn what the proper way is, especially since editing so many of these little boxes if I want to change something one day would be a real hassle. Thanks for your help. I really appreciate it. Let me know if anything is unclear I'll update the questino as soon as I can.
How do I do this within the class when I only sotre their facebook id in the database
echo '<img src="https://graph.facebook.com/' . $row['facebook_id'] . '/picture" />' ;
You say you only store the facebook id in your database. That is all you need to display the picture. Just append /picture to the user's FB graph link to get the picture.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So, there is this website where they have some statistics about that website, and it's updated daily. What I want to do is to scrap that website and retrieve those informations to my website and put them into a line chart. Something like these http://code.google.com/apis/ajax/playground/?type=visualization#line_chart
or these http://code.google.com/apis/ajax/playground/?type=visualization#image_line_chart
The only problem is that I don't know how to do it.
Get Permission
If you need to crawl a remote page, you should start by making sure you're not doing anything illegal. I'm in no way capable of counseling you about the legality of what you're looking to do, but I can say with assurance that some people don't like having their data scrapped - you really should check with the site administrators to see if they have any problem with this.
Got Permission? Good...
When you're cleared, consider using the DOMDocument class to create a representation of the DOM in a series of nested objects that you can interact with pretty trivially:
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents("http://foo.com/data/statistics"));
If you're at all familiar with DOM-traversal and selection methods in JavaScript, the DOMDocument interface will seem pretty familiar. In order to get a particular element by ID, you'd use the appropriate method:
$statistics = $doc->getElementById("statistics");
And to get all TD elements within that element:
$cells = $statistics->getElementsByTagName("td");
Without going into too much detail, you could continue to use the methods provided to you by the DOMDocument class to traverse and select data. When you get to the actual nodes you're seeking, you could easily save their values into an array, and then output that array as a string with some JavaScript to show the Google graph.
Be Nice!
It would be wise to cache the results of this operation so that you don't hit the remote server every time the script runs. Save the output to a local file with a timestamp, and check that timestamp for expiration - when it's expired, remove it, and create a new cached result in its place.
What This Might Look Like
Here is a very basic implementation of what your solution may resemble when it is complete. Note that we only hit the remote server at most once per day.
// Silence errors due to malformed HTML
libxml_use_internal_errors(true);
// This function builds out data out, when necessary
function build_output () {
// Create a DOMDocument, grab debt-clock HTML
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents("http://brillig.com/debt_clock/"));
// Find element representing total National Debt
$total = $doc->getElementsByTagName("img")->item(0);
// Grab value from the alt attribute
$total = $total->attributes->getNamedItem("alt")->nodeValue;
// Second paragraph has two more values of interest
$parag = $doc->getElementsByTagName("p")->item(1);
// Build out resulting array of data: Natl. Debt, Population, Ind. Debt
$data = Array(
"ntl" => str_replace(" ", "", $total),
"pop" => $parag->getElementsByTagName("b")->item(0)->nodeValue,
"pay" => $parag->getElementsByTagName("b")->item(1)->nodeValue
);
// Return a JSON string of this data
return json_encode($data);
}
// Most recent cache file (today)
$cache_name = date("Y-m-d");
if (!file_exists($cache_name)) {
// Today's cache doesn't exist, create it.
$output = build_output();
$message = "Fresh: " . $output;
file_put_contents($cache_name, $output);
} else {
// Today has already been cached, load it.
$message = "Cached: " . file_get_contents($cache_name);
}
// Show the user the output
echo $message;
When loading from cache, the output from the above script looks similar to this:
Cached: {
"ntl":"$16,293,644,693,599.87",
"pop":"313,929,808",
"pay":"$51,902.19"
}
You can load that JSON data into any service you like now to generate an image representing its data.
I've searched far and wide and every CMS tutorial out there either doesn't explain this at all or gives you a huge chunk of code without explaining how it works. Even on stack overflow I can't find anything close to the answer, though I'd be okay with eating my words if someone could point me to the answer.
I am using PHP and mysql for this project.
I am building a CMS. Its extremely simple and I understand every concept I think I'll need except how to dynamically generate pages and page links. The way I want to do it is by having a database table that stores the name of a page and the main content of the page. That's all. Then I'd just call a script to pull the main content of a page into whatever page I happen to call. No big deal, right? Wrong.
Here's the problem. If I were to do this then I'd have to create a file for every page I want to create that calls the script that pulls the content from the correct database row. So I could add all sorts of page names and contents into the table but I don't know how to call them without manually creating new files each time I want to link to a new page.
Ideally there'd be a script that creates links to pages based on the page name row of the DB table as the pages are created. But how do you get those links with the ?=pageName at the end? If I just knew how that worked then I could figure the rest out.
UPDATE
The second answer really confirmed everything I thought I had to do but there is one catch. My plan now is to split up all the code into a series of functions and either include or require them in different templates that will be used to format the way pages are displayed. I need one look for the home page and one other design for the rest of the pages. I'm thinking that I'll have a function that says if ID is 0 then call this page template.php else call this other template file.php. But how do I pass the required variables to these new files? Do I just include the index.PHP page in them?
Bill your actually on the right track. Almost all web software today does extensive URL processing. Traditionally you would have php pages on your web root and then utilize the query string in the URL to refine the page's output. You have already arrived at why this might not be desired. So the popular alternative is the Front Controller design pattern. Basically we funnel every request to your index.php page and then route the request to internal pages or apps outside the web root. This can get complicated fast and everybody seems to implement this pattern in unique ways.
We can utilize this pattern without the routing by simply putting our app in the index page. The script below shows an example of what your trying to do in the simplest of ways. We basically have one page with our script. We can request the virtual pages by changing the id query string in our url. For example www.demo.net/?id=0 can be utilized as an index to your site. This should be the same as www.demo.net without the 'id' query. Just keep solving those problems one by one even if you don't know what the problem is. Once you start looking at other peoples code, then you can start seeing how other people solved the same problems you have.
The solution below will get you started, but then what do you do when you want an admin page? How do you authenticate the user? Do you duplicate alot of the code for yet another page? If your serious about your CMS then your going to want to implement some kind of framework underneath it. A framework to process the url, route to your application, load configuration files, and probably manage your database connection. Yea it gets complicated, but not if you solve each problem one at a time. Utilize classes or functions to share code to start. At the very least include a common "bootstrap" file at the top of your page to initialize common functionality such as a database connection. Read Stack Overflow just to keep up with whats going on. You can learn alot of terminology and probably find some answers to questions you didn't even know you wanted to ask.
Below assume we have a table with the following fields:
page_id
page_name
page_title
page_body
<?php
//<--------Move outside of web root-------------->
define('DB_HOST', 'localhost');
define('DB_USER', 'cms');
define('DB_PASS', 'changeme');
define('DB_DB', 'cms');
define('DB_TABLE', 'cms_pages');
//<---------------------------------------------->
//Display errors for development testing
ini_set('display_errors','On');
//Get the requested page id
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
else
{
//Make page id '0' an index page to catch all
$id = 0;
}
//Establish a connection to MySQL
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
//Select the database we will be querying
mysql_select_db(DB_DB, $conn) or die(mysql_error());
//Lets just grab the whole table
$sql = "SELECT * FROM ".DB_TABLE;
$resultset = mysql_query($sql, $conn) or die(mysql_error());
//The Select Query succeeded, but returned 0 result.
if (mysql_num_rows($resultset)==0)
{
echo "<pre>Add some Pages to my CMS</pre>";
exit;
}
//This is our target array we need to fill with arrays of pages
$result = array();
//Convert result into an array of associative arrays
while($row = mysql_fetch_assoc($resultset))
{
$result[] = $row;
}
//We now have all the information needed to build our app
//Page name - Short name for buttons, etc.
$name = "";
//Page title - The page content title
$title = "";
//Page body - The content you have stored in a table
$body = "";
//Page navigation - Array of formatted links
$nav = array();
//Process all pages in one pass
foreach($result as $row)
{
//Logic to match the requested page id
if($row['page_id'] == $id)
{
//Requested Page
$name = $row['page_name'];
$title = $row['page_title'];
$body = $row['page_body'];
$page = "<b>$name</b>";
}
else
{
//Not the requested page
$page = $row['page_name'];
}
//Build the navigation array preformatted with list items
$url = "./?id=" . $row['page_id'];
$nav[] = "<li>$page</li>";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>SimpleCMS | <?php echo $title; ?></title>
</head>
<body>
<div>
<div id="navigation" style="float:left;">
<ul>
<?php
foreach($nav as $item)
{
echo $item;
}
?>
</ul>
</div>
<div id="content"><?php echo $body;?></div>
</div>
</body>
</html>
I think you need to read about $_GET.
I also recommend a decent PHP book. Forget online tutorials; they are (for the most part) utterly useless.