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.
Related
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.
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.
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.
I made this code where I define an array, fliepath, in which I store the locations of some files.
include 'last_file.php'; // Include the function last_file
$last_file = last_file(); // assign to the function a variable and call the function last_file
// Connect to the database
include('connect_thesis.php');
// Defining an array, which has the three paths to the three different gps receivers
$file_path[0] = "/Applications/MAMP/htdocs/php_test/check/".$last_file[0];
//echo $file_path[0]; echo "<br>";
$file_path[1] = "/Applications/MAMP/htdocs/php_test/check2/".$last_file[1];
//echo $file_path[1]; echo "<br>";
$file_path[2] = "/Applications/MAMP/htdocs/php_test/check3/".$last_file[2];
//echo $file_path[2]; echo "<br>";
Then I made a function called insert() which I want to take as input the $file_path[0]:
function insert($file_path){
$fh = fopen($file_path,'r') or die ("Could not open:".mysql_error()).......;
I call the function from the main script as:
insert($file_path[0]);
I am new in programming and I am sure somewhere I am missing something basic!
The problem is that the function doesn't run!!!
Can you help me?
Thanx
D.
I THINK I DONT PASS CORRECTLY THE VALUE TO THE FUNCTION. CAUSE I GET NOTHING AS AN ERROR!
A few points to note:
You are calling insert using only the index 0, consider using a foreach and call the function on each items in your array.
insert() -> we are missing part of the implementation, but if the file exists, you should not get an error. Keep in mind that you need to close files that you open.
or die -> it looks like you copy pasted code from elsewhere... mysql_error() will not help you much as you're dealing with files at the moment. Consider changing it to
$fh = fopen($file_path,'r') or die ("Could not open:".$file_path)
You should probably handle graciously the error instead of using "die"
I think you need this:
function insert($file_path) {
foreach ($file_path as $file) {
//Your code here
}
}
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.
here is the code for adding to database:
<?php
/*Config*/
Sounds like something that should be able to be easily accomplished using a PHP session variable.
Just use sessions and set a session variable (call it posted or something) and if that variable is set, don't allow the user to post (hide the submit button or use a PHP if-statement in your javascript to only perform the action when that variable is not set).
The session will be cleared when the user closes the browser.
As a possible example, in your PHP code for adding to the database, just put this at the beginning:
session_start();
if (isset($_SESSION['posted']))
die("posted");
$_SESSION['posted'] = true;
EDIT :
You just need to add another else if statement. It will look something like this:
if(response == "knownudid"){
document.getElementById('udid_message').innerHTML = '<br><i><font color="red">This UDID has already been inserted and it is valid.</font></i>' ;
}else if(response == "noudid"){
document.getElementById('udid_message').innerHTML = '<br><i><font color="orange">Please, enter your UDID.</font></i>' ;
}else if(response == "errudid"){
document.getElementById('udid_message').innerHTML = '<br><i><font color="red">It seems this UDID is not correct. Please check for typo.</font></i>' ;
}else if(response == "validatedudid"){
document.getElementById('udid_message').innerHTML = '<br><i><font color="green">This UDID has been found as an invalid one. Now it is valid.</font></i>' ;
}else if(response == "posted"){ // Here is the new one
document.getElementById('udid_message').innerHTML = '<br><i><font color="red">You have already posted a UDID for this session.</font></i>' ;
}else{
document.getElementById('udid_message').innerHTML = '<br><i><font color="green">UDID <b>'+response+'</b> successfully inserted.</font></i>';
}
With some nice jQuery or js you could hide the form after the user submit.
Having the javascript within the HTML elements is bad, move it into the <script> tags or even better, a separate .js file.
For HTML5 browsers, placeholder is a much more elegant way of providing instructions for text fields.
If you're using AJAX to submit the form, within your function insert_udid() add:
.
document.getElementById('your_button_or_form').disabled = true;
// or document.getElementById('your_form').style.visibility = 'hidden';
...otherwise, you'll need for the php code to disable or omit the form from the response HTML.
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, often, I check my accounts for different numbers. For example, my affiliate accounts: I check for cash increase.
I want to program a script where it can login to all these websites and then grab the money value for me and display it on one page. How can I program this?
you should take a look into curl.
You should be able to generate a script that retrieve some webpage easily.
Also take a look into simplexml and dom, it would help you to extract information from (X)HTML files.
Also Zend_Http could be a good alternative to curl.
Cheers
Well, sort of a vague question... I'd suggest the following steps:
send the login credentials via POST
grab and parse the response
do this for all relevant accounts / sites you wanna check
if you face specific problems feel free to comment on this answer
EDIT: I'd agree to RageZ in his technical approach. curl would be the 'weapon of choice' for me too... ^^
hth
K
First of all, check if the services where you want to log in have APIs.
It's be much easier as that's a format specifically made for the purpose of getting the datas and exploiting them in an other application.
If there is an API, you can look at it's documentation to see how to retrieve and use the datas.
If there isn't any, you need to scrap the HTML pages.
You can start by taking a look at Curl : http://php.net/curl
The idea is to simulate your own visit of the website by sending the loggin post request and getting the given datas.
After retrieving the page's datas, you can parse them with tools like dom.
http://php.net/dom
Use TestPlan, it was designed as a web automation system and makes such tasks very simple.
I would really have a look into Snoopy if i were you, its more user friendly than curl to use in your PHP scripts. Here is some sample code.
<?php
/*
You need the snoopy.class.php from
http://snoopy.sourceforge.net/
*/
include("snoopy.class.php");
$snoopy = new Snoopy;
// need an proxy?:
//$snoopy->proxy_host = "my.proxy.host";
//$snoopy->proxy_port = "8080";
// set browser and referer:
$snoopy->agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
$snoopy->referer = "http://www.jonasjohn.de/";
// set some cookies:
$snoopy->cookies["SessionID"] = '238472834723489';
$snoopy->cookies["favoriteColor"] = "blue";
// set an raw-header:
$snoopy->rawheaders["Pragma"] = "no-cache";
// set some internal variables:
$snoopy->maxredirs = 2;
$snoopy->offsiteok = false;
$snoopy->expandlinks = false;
// set username and password (optional)
//$snoopy->user = "joe";
//$snoopy->pass = "bloe";
// fetch the text of the website www.google.com:
if($snoopy->fetchtext("http://www.google.com")){
// other methods: fetch, fetchform, fetchlinks, submittext and submitlinks
// response code:
print "response code: ".$snoopy->response_code."<br/>\n";
// print the headers:
print "<b>Headers:</b><br/>";
while(list($key,$val) = each($snoopy->headers)){
print $key.": ".$val."<br/>\n";
}
print "<br/>\n";
// print the texts of the website:
print "<pre>".htmlspecialchars($snoopy->results)."</pre>\n";
}
else {
print "Snoopy: error while fetching document: ".$snoopy->error."\n";
}
?>
Use VietSpider Web Data Extractor.
VietSpider Web Data Extractor: Software crawls the data from the websites (Data Scraper), format to XML standard (Text, CDATA) then store in the relational database.Product supports the various of RDBMs such as Oracle, MySQL, SQL Server, H2, HSQL, Apache Derby, Postgres ...VietSpider Crawler supports Session (login, query by form input), multi downloading, JavaScript handling, Proxy (and multi proxy by auto scan the proxies from website),...
Download from http://binhgiang.sourceforge.net