The code below works, in that, it updates the database correctly. However, after the post is completed the data on the page is old i.e. $reader_busy[0] is not updated even though it is driven by a SELECT query.
To force $reader_busy[0] to update properly on the users screen a refresh is required. This means the pages reloads after the post and then refreshes.
How do I get the page to display the correct data from the mysql without having to load the page twice?
Simplified version of my PHP code:
<?php
$reader_key = 'jm2';
$reader_busy_query = "SELECT `BusyWithClient` " .
"FROM {$wpdb->prefix}assistant " .
"WHERE `Key`='" . $reader_key . "'";
$reader_busy = $wpdb->get_col( $wpdb->prepare( $reader_busy_query ) );
$busy_with_client = $reader_busy[0];
if(isset($_POST['toggle'])){
$result = $wpdb->update(
$wpdb->prefix . 'assistant',
array('BusyWithClient' => $busy_with_client),
array('Key' => $reader_key)
);
// I want to remove / replace this line, and still see updated data.
echo "<meta http-equiv='refresh' content='0; url=" . curPageURL() . "#instructions" . "'>";
}
?>
<h1>
<?php print_r('busy: ' . $reader_busy[0]); ?>
<h1>
<form method="post" action="<?php echo curPageURL() . '#instructions'; ?>">
<input type="submit" name="toggle" value="toggle" >
</form>
Just flip the order of how you do things. Instead retrieving then updating, update before you retrieve.
<?php
if (isset($_POST['toggle'])) {
$result = $wpdb->update(
$wpdb->prefix . 'assistant',
array('BusyWithClient' => $busy_with_client),
array('Key' => $reader_key)
);
}
$reader_busy_query = "SELECT `BusyWithClient` " .
"FROM {$wpdb->prefix}assistant " .
"WHERE `Key`='" . $reader_key . "'";
$reader_busy = $wpdb->get_col($wpdb->prepare($reader_busy_query));
?>
I see what you are trying to accomplish and that's looks impossible. Instead of refreshing page you can (should) make ajax request and update your page by refreshing only the page data that you need.
EDIT:
Because, you are trying to post to a page with ANCHOR, and browsers by there nature will try to find information on the page without refreshing it. Browser still sends information to post, so it updates in background, but not refreshes the page.
You should make post over ajax request and return data to field, or post it to another php file (without #hashtag).
PS - You will not get more answerers if you will downgrade every answers that didn't work for you :)
Related
I have three pages in the website. The first is login page,second is profile page and third is main page.
<?php
session_start();
$servername="blah blah blah";
$connectioninfo=array('Database'=>'mbr');
$conn=sqlsrv_connect($servername,$connectioninfo);
if($conn)
{
echo 'connection established';
}
else
{
echo 'connection failure';
die(print_r(sqlsrv_errors(),TRUE));
}
$q1="SELECT * FROM EmployeeTable WHERE EmployeeID = '" . $_SESSION['id'] . "' ";
$stmt=sqlsrv_query($conn,$q1);
if($stmt==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
$row=sqlsrv_fetch_array($stmt);
echo $row['EmployeeName'];
$q2="SELECT * FROM pointsBadgeTable WHERE EmployeeID = '" . $_SESSION['id'] . "' ";
$stmt1=sqlsrv_query($conn,$q2);
if($stmt1==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
$pbrow=sqlsrv_fetch_array($stmt1);
?>
The above is the php used in the second page of the website. Here I am using two queries $q1 and $q2 to retrieve information from two different tables (EmployeeTable and pointsBadgeTable) after connection to the database "mbr" here.
I then echo the desired Info in my html after retrieving info from the tables.
For instance,
<?php echo "". $row['goldTotal'] .""?>>
Here 'goldtotal' is a column in the pointsBadgeTable in the above php. Also please note that I am using " . $_SESSION['id'] ." here to show info only about the person who logs in the first page of the website.
The issue here is that I want to echo the same value in the third page as in second page. Will I have to write the same php code in third page as I wrote in second page or I need to store it in some session variable. How to use a session variable here?
Also, is it correct to rewrite the same code in third page also as in second page and use the same queries $q1 and $q2? I will copy and paste the same PHP to the third page also.
You Can include the second page in third page , you will get the value .
Example : file3.php
**<?php
include 'file2.php';
?>**
I'm trying to setup a button that will delete all the rows we loaded on this run but it's not working.
PHP:
if(isset( $_GET['startID'], $_GET['endID']))
{
$sql_query = "DELETE FROM users WHERE id BETWEEN " .$_GET['startID'] . " AND " . $_GET['endID'] . ";";
mysql_query($sql_query);
header("Location: index.php");
}
Button:
<a onClick="javascript: return confirm('Are you sure?');" href='index.php?startID=<?php echo $firstID; ?>&endID=<?php echo $lastID; ?>'>Delete</a>
Button redirects to: index.php?startID=11111&endID=22222
The button is passing the values but they're not getting deleted from the database. Can anyone point me to the mistake?
For this kind of problem you need to start Debugging yourself. What you really need to do is-
Check the database connection is established or not.
Checkout the Condition is correct or not that is applied, You can use a simple echo for this.
echo the query string and run into the phpMyAdmin and see is there anything miss use or others.
These are the suggestion for all the OP who ask this type of
questions. We are always here to help you where you get stuck.
Try for instead:
if(isset( $_GET['startID'], $_GET['endID']))
{
for($i=$_GET['startID'];$i<=$_GET['endID'];$i++){
$sql_query="DELETE * FROM users WHERE id=" .$i. ";";
mysql_query($sql_query);
}
header("Location: index.php");
}
I am trying to delete a series of rows from a database using a delete button, but data is split across two tables, joined by one common field. I have created the following, but the delete isn't working right.
$watchlist_id = $_GET['id'];
// Delete Watchlist
if ($submit == 'Delete Watchlist') {
require_once("db_connect.php");
$deleteWatchlist_bad_message = '';
if ($db_server) {
$purge_watchlist_query = "DELETE FROM watchlist_films WHERE watchlist_id = '$watchlist_id'";
mysql_query($purge_watchlist_query) or die("Delete failed. " . mysql_error() . "<br />" . $purge_watchlist_query);
$delete_watchlist_query = "DELETE FROM watchlists WHERE watchlist_id = '$watchlist_id'";
mysql_query($delete_watchlist_query) or die("Delete failed. " . mysql_error() . "<br />" . $delete_watchlist_query);
} else {
$deleteWatchlist_bad_message = '<div class="alert alert-error">Error: could not connect to the database.</div>';
}
require_once("db_close.php");?>
<script type="text/javascript">
window.location = "profile.php"
</script><?php
}
Basically, I want it to delete all the films in the Watchlist in the watchlist_films table ($purge_watchlist_query), then delete the Watchlist itself from the watchlists tables ($delete_watchlist_query), before redirecting the user back to their profile page.
Apologies for not being clear enough - when I say 'the delete isn't working right', what's actually happening when clicking the delete button is that I am being successfully redirected back to profile.php, however the Watchlist I was attempting to delete is still showing and, when I click through to it, the film it contains is also still there. I aren't getting any errors or anything being spat back out to me, it's just not deleting the records. Hope this clarifies!
OK, so I've figured out the problem.
Basically, my original element was submitting to watchlist.php, rather than watchlist.php?id=$watchlist_id. Once I'd amended that, the delete worked fine.
We have a small php script, that displays random adverts on our site . The banners are served from any location we designate.
What I really would like to know, or be pointed in the right direction is, can we somehow collate the number of impressions each banner gets and possibly the click count on that banner.
I am sure this can be done in php, and stored in a db. Just havent got a clue. I searched on Google, and seemingly everything I could find harks back to 2002 and 2003 lol.
Here is our script:
<?php
$Img1 = "path to image folder/banner.png";
$Alt1 = "alt text for banner";
$Url1 = "http://www.externaldomain.com";
$Img2 ="path to image folder/banner.png";
$Alt2 = "alt text for banner";
$Url2 = "http://www.externaldomain.com";
$Img3 ="path to image folder/banner.png";
$Alt3 = "alt text for banner";
$Url3 = "http://www.externaldomain.com";
$Img4 ="path to image folder/banner.png";
$Alt4 = "alt text for banner";
$Url4 = "http://www.externaldomain.com";
$Img5 ="path to image folder/banner.png";
$Alt5 = "alt text for banner";
$Url5 = "http://www.externaldomain.com";
$num = rand (1,5);
$Image = ${'Img'.$num};
$Alt = ${'Alt' .$num};
$URL = ${'Url'.$num};
Print "<img src=\"".$Image."\" alt=\"".$Alt."\" /"; ?>
To initiate the above code ( we fire an include request )
<?php include ("../adserver/thescriptabove.php"); ?>
I see that you already selected an answer, so I'm not sure if you figured it all out, but I was writing out a little tutorial for you. Finally got it done, hope it still helps you out.
Your method seems to be working fine for serving banners, but if you're going to get into databases and tracking clicks/impressions, I would suggest that you go all in. So store your banner properties in the database as well. I'm going to get ahead and assume that your server/web host allows for a few free MySql databases.
What you need to do is create a database, as well as a User/Admin for the database. Then you're going to access the database with a MySql manager, most web hosts provide phpMyAdmin. Once you're inside the database, you need to set up a table to record your data.
Here's how I want you to set it up:
|Table Name: Banners |
|-------------------------|
|Field: | Type: |
|-------------------------|
|ID | int(5) | The Primary Key and Autoincrement attributes should be set on the ID field as well
|Image | varchar(100) |
|Url | varchar(100) |
|Caption | varchar(100) |
|Views | int(10) |
|Clicks | int(10) |
Now that you've got the database done, here comes the hard part, the PHP. I've pretty much done it for you, but it's untested, so I'm sure there will be bugs, that you will have to work out. But it should point you in the right direction, and help you learn.
<?PHP
// First of all, we need to connect to the MySql server
// For more info, check out: http://php.net/manual/en/function.mysql-select-db.php
$conn = mysql_connect("localhost", "username", "password");
if(!$conn){
die('Could not connect to the MySql Server ' . mysql_error());
}
// Now that we've connected to the MySql sever, we need to select the database
// More info can be found on the same link as above
$db_selected = mysql_select_db('my_database', $conn);
if(!$db_selected) {
die ('Could not select the MySql Database: ' . mysql_error());
}
// Now we need to check the URL parameters to see, if we came to this page normally or because a banner was clicked
// If normally, we serve a random banner and increment the Views field in the database
// Otherwise, we increment the Clicks field and direct the user to the banner's URL
if(!isset($_GET['Clicked'])){
// if the Clicked parameter is not set, we came to the page normally
// Let's select a random banner from the database
$result = mysql_query("SELECT * FROM banners ORDER BY RAND() LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array(result);
// Now let's increment the Views field for the banner we selected
mysql_query("UPDATE banners SET Views = Views + 1 WHERE ID = '" . $row['ID'] . "'") or die(mysql_error());
// let's set the URL to this same page but with the Clicked parameter set
$url = "banner_server.php?Clicked=" . $row['ID'];
// Last but not least, we have to output the banner HTML
// Notice, I set the caption on both the 'alt' and 'title' attributes of the 'img' tag,
// that's because IE shows the value of the 'alt' tag when an image is hovered,
// whereas Firefox shows the value of the 'title' tag, just thought you might want that!
echo "<img src=\"" . $row['Image'] . "\" alt=\"" . $row['Caption'] . "\" title=\"" . $row['Caption'] . "\" />";
}else{
// Otherwise, increment the Clicks field and redirect
// First, let's get the ID of the banner that was clicked from the Clicked parameter
$id = (int)$_GET['Clicked'];
// now let's increment the Clicks field for the banner
mysql_query("UPDATE banners SET Clicks = Clicks + 1 WHERE ID = '" . $id . "'") or die(mysql_error());
// now let's select the banner from the database so we can redirect to the URL that's associated with it
$result = mysql_query("SELECT * FROM banners WHERE ID = '" . $id . "'") or die(mysql_error());
$row = mysql_fetch_array(result);
// redirect to the URL
header("location: " . $row['Url']);
}
// Close the MySql connection
mysql_close($conn);
?>
Good luck
why dont you just let google analytics do it for you? Fire off an event when the link is clicked and let google capture it?
onclick="_gaq.push(['_trackEvent', 'Event Name', 'click', 'Button title/name']);"
You can store the $num in the database pretty easy to get your impression count. Clicks require client side action. The easiest way is to call a javascript function that counts when the banner is clicked via AJAX:
print "<img src=\"".$Image."\" alt=\"".$Alt."\" /";
Then have your javascript function (countClick()) execute the AJAX that will tell the server the banner has been clicked.
Another way is to have a passthru page: mysite.com/linkout.php?q=www.google.com and then have linkout.php count that link and update the database, and then redirect them to the variable passed in the URL.
Here are my 2 cents, assuming you have analytics on our site:
Use the following code when outputting a link:
<a class="ad" href="http://thecatisginger.com/" target="_blank" onclick="ga('send', 'event', 'Block-3-Ads', 'Click', 'The-Cat-Is-Ginger-Ad');"><img src="http://citybymouth.com/wp-content/uploads/2015/02/TCIG-Advert.jpg" onload="ga('send', 'event', 'Block-3-Ads', 'Impression', 'The-Cat-Is-Ginger-Ad', {'nonInteraction': 1});" /></a>
To explain:
<a class="ad" href="http://thecatisginger.com/" target="_blank"
Classic link a href link with class 'ad', links to a site, target opens in new tab. Easy.
onclick="ga('send', 'event', 'Block-3-Ads', 'Click', 'The-Cat-Is-Ginger-Ad');">
This is the newer 'analytics.js' google event tracking, onclick event code, that bascially says, hey, you've clicked this link, so 'send' this 'event' to my analytics 'Events' (which can be checked under "Realtime > Events" or "Behaviour > Events"). "Block-3-Ads" is the area on my website I personally know as the area I put ads, specifically its a right hand sidebar area, but it can be anything you want, so make yours a broad category type thing, like a box, inside which you will have different links you want to track. "Click" is simply the type of event you want to track, can be anything. "The-Cat-Is-Ginger-Ad" is this specific ad I want to track and have the information about.
<img src="http://citybymouth.com/wp-content/uploads/2015/02/TCIG-Advert.jpg"
Then you have an img with a src. Easy.
onload="ga('send', 'event', 'Block-3-Ads', 'Impression', 'The-Cat-Is-Ginger-Ad', {'nonInteraction': 1});" />
Then you have an onload event that fires when the image is loaded, it says, 'send' this 'event', categorise it as a 'Block-3-Ads' event, basically the image loading is counted as an 'Impression', before it was click, but not since this little 'onload' is called when it loads, its not a click, but a load / impression, and again, specifically, the ad loaded is 'The-Cat-Is-Ginger-Ad', and finally, there is passing the 'nonInteraction' parameter as 1, which is just telling google you are tracking a non interaction event.
Its pretty self explanatory, tho I may have typed too much.
WARNING: This is not perfect in that the page may load, and the ad may be below the viewport, out of sight of the user, and still get an impression, which is not accurate, so next I'll be working on firing the impression code just once when the user actually scrolls to the ad itself, and views it, instead of firing it every time a page loads that image.
Thanks to #Saad Imran for the code and also big thanks to the question poster
Bellow the update of the code in php 7 if someone else need it for later use
Note : The same Database table and then store this code in banner.php file
<?php
// to only count views
// select a random banner from the database to show
$rows = $db->QueryFetchArrayAll("SELECT * FROM banners ORDER BY RAND() LIMIT 1");
foreach ($rows as $row) {
// Now let's increment the Views field for the banner we selected
$url = "/banner.php?clicked=" . $row['ID'];
echo "<img src=\"" . $row['Image'] . "\" alt=\"" . $row['Caption'] . "\" title=\"" . $row['Caption'] . "\" />";
}
$db->Query("UPDATE banners SET Views = '".round($row['Views'] + 1)."' WHERE id = '" . $row['ID'] . "'");
// to count clicks need an if statement
if(isset($_GET['clicked'])){
$db->Query("UPDATE banners SET Clicks = '".round($row['Clicks'] + 1)."' WHERE id = '" . $row['ID'] . "'");
header("location: " . $row['Url']);
}
?>
Good luck everyone :)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a form that submits and displays text. Entering http://www.twitter.com for example displays in clear text. How can i get it to automatically display as a clickable link?
I am working with MySQL and PHP.
If the data is a URL, you can just wrap it in a tag:
printf('%1$s', htmlspecialchars($your_link, ENT_QUOTES));
Things get trickier if you need to convert the URL in the text. Most users won't bother with escaping the links correctly, and post example.com/Some Thing - [Me] instead of http://example.com/Some%20Thing%20-%20%5BMe%5D. Find a regular expression that fit your needs and use:
echo preg_replace('#expression that matches a URL#', '$1',
htmlspecialchars($your_data, ENT_QUOTES));
You propably want your script to automatically detect links...I did that a few weeks ago on a script that pulls tweets from an RSS Feed...this is the code. You can replace $_POST['inputfield'] with the appropriate variable!
if (preg_match('/www./',$_POST['inputfield'])) //checks if there's www. in the field. alternatively use http: instead of www.
{
$link_start_pos = strpos($_POST['inputfield'],'www.'); //returns the link-start-pos, alternatively use http: instead of www.
// find the end of the link
if($link_end_pos = strpos($_POST['inputfield'], ' ', $link_start_pos) === false)
{ //if theres no space after the link, it's propably on the end of the text
$link_end_pos = strlen($_POST['inputfield']);
}
// form a string with the actual link in it
$link = substr($_POST['inputfield'],$link_start_pos,$link_end_pos);
// and make it clickable
$link_insert = ''.$link.'';
}
Hope that helps
This works for me...
using a DB table with columns "id" "href" "title", as mentioned above by #DarkDevine
<div id="buttons">
<ul id="list">
<?php
$connect = mysql_connect("host","user","password");
if(!$connect){
die("Failed to connect: " . mysql_error());
}
if(!mysql_select_db("YOUR DATABASE NAME")){
die("Failed to select DB:" . mysql_error());
}
$results = mysql_query("SELECT * FROM YOU TABLE NAME");
while($row = mysql_fetch_array($results)){
echo '<li>' . '' . $row['title'] . '' . '</li>' . '<br/>';
}
?>
</ul>
$result = mysql_query( 'SELECT * FROM `links`' );
if( mysql_num_rows( $result ) ) {
foreach( $row = mysql_fetch_object( $result ) ) {
echo "{$row->title}";
}
}
assuming your table looks like
id href title
1 http://google.de Go to gooogle!
2 http://twitter.de Go to twitteeeerr!
Okay this is just an example senario for you to give you an idea of what to do.
Okay lets say we have a form with 1 textbox with the name url and a submit button, we are also using the POST method.
<form method="post" action="pageurl.php">
<input type="text" name="url" value="" />
<input type="submit" value="Submit" />
</form>
In pageurl.php we would then have something like this:
<?php
//Get the value of $_POST['url'] and cleanse it.
$url = htmlentities(stripslashes(mysql_real_escape_string($_POST['url'])));
//Echo out the click-able link.
echo '' . $url . '';
?>
For example if we entered http://twitter.com into the form we would get a click-able link with the text http://twitter.com which would also link to twitter.com
On the processing page:
<?php
include('config.php');
$link = $_POST['link'];
$title = $_POST['title'];
$sql = "INSERT INTO table_name (link) VALUES ('<a href=\'$link\'>$title</a>')";
?>
And to retrieve the link:
<?php
include('config.php');
//code to select the table
$sql="SELECT * FROM table_name";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
echo "$rows['link']";
}
?>
I wrestled with this for some time before finding the solution that best worked for me. I'll post it as it might help someon else. I am just playing around with a simple URL/Comment PHP script that takes a URL/Comment and inserts to the DB. I then display the results. At first the URLs weren't clickable when displaying. So I set out to find a way to do that. Here's the snippet that worked for me:
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['url'] . "</td>";//this line is it
echo "<td>" . $row['description'] . "</td>";
echo "</tr>";
}
I have no problem with Making link after getting information out of a database. my logic is using <?php echo '$status'; ?> So if you say Click here The link will end up inside the echo function. Although if you do it different you might not get the same result.
There is a far easier way to do this.
With a row named "website"
Website: < a href="http://'.$website.'" target="_blank">'.$website.'
the form entry is "www.whateverthewebsiteis.com" and the output would be "http://www.whateverthewebsiteis.com"