Delete from two tables - 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.

Related

Use session variable or copy PHP code from second page to third page of a website

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';
?>**

PHP old data still showing after POST

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 :)

Delete between with a button and $_GET

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");
}

not retrieving id from browser url when clicking on back button

I found a problem in my code, when I want to remove a user from database, it has to remove him, the code for removing works perfect, but afterwards, the if condition shows that the user has been removed and I have a Back button there, I click on it and it should redirect me back to the classroom with the rest of the users in it. Classroom is identified by ID of course, but when I click on Back, it shows me classroom without an ID of a class...so its not getting ID...
// get value of id that sent from address bar
$id_student=$_GET['id_student'];
$id_trieda = $_GET['id_triedy'];
// Delete data in mysql from row that has this id
$zmaz='DELETE FROM $tbl_name WHERE id_student="'.$id_student.'" AND id_triedy="'.$id_trieda.'"';
mysqli_real_escape_string($prip, $zmaz);
$row = mysqli_query($prip,$zmaz);
// if successfully deleted
if($row){
echo "Študent bol úspešne vymazaný.";
echo "</br>";
echo "<a href='./trieda.php?id_triedy=".$_GET['id_triedy']."'>Späť do triedy<a/>";
}
else {
echo "Chyba";
}
?>
EDIT:
// get value of id that sent from address bar
$id_student=$_GET['id_student'];
// Delete data in mysql from row that has this id
$zmaz="DELETE FROM $tbl_name WHERE id_student='$id_student'";
$result=mysql_query($zmaz);
// if successfully deleted
if($result){
$id_trieda = $_GET['id_triedy'];
echo "Študent bol úspešne vymazaný.";
echo "</br>";
echo "<a href='./trieda.php?id_triedy=".$id_trieda."'>Späť do triedy<a/>";
}
else {
echo "Chyba";
}
here is edited code which is similar to one that is working when I add a student into the class and then there is a Back button again, but it works....so problem will be in deleting the student, it cant find the ID of class he was in..i think..but I have no idea how to get the ID of the class before he is removed..
Looking at the page you linked to in your comment, I see the problem - you aren't passing id_triedy in your zmazat link. It reads:
http://www.xxx.xx/project/zmazat_studenta.php?id_student=15
Where it should read:
http://www.xxxx.xx/project/zmazat_studenta.php?id_student=15&id_triedy=18
(or whatever the relevant id_triedy is).
Then the $_GET['id_triedy'] in your question code actually has something to get.
You should really build in a check for this kind of thing:
if(isset($_GET['id_triedy'])){
$id_trieda = $_GET['id_triedy'];
} else {
echo 'No trieda ID';
}
This will check the URL for id_triedy and tell you if it's not there.
Is the trieda.php the file that contains the Classroom? If so, this line should be amended:
echo "<a href=\"./trieda.php?id_triedy=".$_GET['id_triedy']."&id_student=".$_GET['id_student']."\">Späť do triedy<a/>";
It looks like you left out the id_student in the URL

How to count banner impressions and Clicks

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 :)

Categories