PHP/MySQL OnClick Update MySQL - php

Need to update a hitcount field in a MySQL table when a user clicks on a banner ad. Have the random ad display script working but can't figure out how to update the table when they click..assuming will have to pass the ID to Ajax but no idea how to approach it? Code is below:
include 'connection.php';
$query = "select * from ads where adtype = 'small' and status = 'yes' ORDER BY RAND() LIMIT 3";
$result = mysql_query($query) or die(mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results !="0")
{
for($i=0;$i<$num_results;$i++)
{
$row = mysql_fetch_array($result);
$client = htmlspecialchars(stripslashes($row['client']));
$link = htmlspecialchars(stripslashes($row['link']));
$filename = htmlspecialchars(stripslashes($row['filename']));
$id = $row['id'];
echo "<tr>";
echo "<td>";
echo '<a href="';
echo $link;
echo '"><img src="thimg/';
echo $filename;
echo '" alt="';
echo $client;
echo '"></a>';
echo "</td>";
echo "</tr>";
}
}

Make the link point to a page which takes the ID of the ad as a parameter, something like click.php?id=the_id. Then that page can update the database, look up the link, and then you can use a header redirect to forward them on to the link. Make sure you don't output anything on that forwarding page though, or the redirect won't work.
This should get you what you need, without the need for javascript or ajax.

Related

How to make a variable to show the same row as it is currently showing in PHP?

I really don't know how to explain this question. But, I'm trying to make a product page that shows the same row as it is currently showing (so example "go onto a tech product page and at the bottom it shows all other tech related products").
Here is what I've tried:
<?php
$pType = $row['typeP'];
$sql = "SELECT * FROM products WHERE type=$pType";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while ($row = mysqli_fetch_array($result)){
echo "<a href='products.php?id={$row['productID']}'>";
echo "<img src='uploads/{$row['displayIMG']}'>";
echo "</a>";
}
?>
Your error would be in the $typeP declaration. I am guessing $row is not defined before that. therefor it is empty. Maybe you were trying to use a GET?
<?php
$pType = $_GET['typeP']; //This would get the type id from the querystring
$sql = "SELECT * FROM products WHERE type='".$pType."'";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while ($row = mysqli_fetch_array($result)){
echo "<a href='products.php?id=".$row['productID']."'>";
echo "<img src='uploads/".$row['displayIMG']."'>";
echo "</a>";
}
?>
I should also mention that your code is subject to SQL injection. Please clean your inputs before running them through you database. Otherwise you are asking for trouble.
http://www.wikihow.com/Prevent-SQL-Injection-in-PHP

Using Foreach for website. I want a hit counter using PHP & MSQL

So I'm creating a piano library website for my younger cousin.
Currently I use the foreach function to display all the data from my database. Now, this works great and I managed to get a few features working, but one I'm having trouble with is a "counter".
Super easy concept, except the fact that I'd like a counter for every single entry.
By "counter" I mean that after clicking a link, it would add a +1 to the count. So that each link would have "Visited 100 times" or "Visited 34 times", etc.
I have tried the following:
if($mysqli){
$result = mysqli_query($mysqli,"SELECT * FROM testtable ".$orderbyfilter);
$rows = $result->fetch_all(MYSQLI_ASSOC);
foreach($rows as $row) {
echo "<tr id='entry'><td>";
echo ucwords($row['name']);
echo "</td><td align='center'>";
echo 'url';
echo "add hit:";
echo "<a href='?action=callfunction'>Click</a>";
//current counter script
if(isset($_GET['action']) && $_GET['action'] == 'callfunction'){
$hitcount = $row['hitcount'] + 1;
$id = $row['id'];
// why doesn't this work?
$sql="UPDATE testtable SET hitcount='$hitcount' WHERE id='".$id."'";
$result=mysqli_query($con,$sql);
}
echo "</td><td align='center'>";
echo $row['level'];
echo "</td><td align='center'>";
echo $row['hitcount'];
echo "</td></tr>";
}
mysqli_close($mysqli);
} else {
echo "table did not correctly display!";
}
Obviously the method:
$sql="UPDATE testtable SET hitcount='$hitcount' WHERE id='".$id."'";
Doesn't work, as when I click the link, it updates all entries with the same hit count. However when I change it to:
$sql="UPDATE testtable SET hitcount='$hitcount' WHERE id='2'";
It works perfectly, where it only modifies hitcount for the row with id=2.
Obviously the problem has to do with the "foreach" and setting $row[id] as a variable, but honestly I could use some help.
Does it have something to do with variable of variables? I have no clue. Any help is appreciated.
Here's what worked for me. You can modify it as per required.
What needed to be done was to pass an additional GET parameter for the related "id" in the URL, then pass that variable for it in the WHERE clause.
A header was also added in order to automatically redirect once a related URL to the given row has been clicked and show the results and to prevent the following warning:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in...
Sidenote: Read the comments left in the code below for additional information.
<?php
ob_start(); // keep this, it's for the header
$DB_HOST = 'xxx'; // Replace
$DB_USER = 'xxx'; // with
$DB_PASS = 'xxx'; // your
$DB_NAME = 'xxx'; // own
$Link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($Link->connect_errno > 0) {
die('Connection failed [' . $Link->connect_error . ']');
}
// Your original query. You can replace it if needed.
// $result = mysqli_query($Link,"SELECT * FROM testtable ".$orderbyfilter);
$result = mysqli_query($Link,"SELECT * FROM testtable");
while ($row = mysqli_fetch_array($result)) {
echo "<tr id='entry'><td>";
echo "ID: " . $row['id'];
$var = $row['id']; // used for the URL
echo "<br>";
echo $row['hitcount'];
echo ucwords($row['name']);
echo "</td><td align='center'>";
echo 'url';
echo " Add hit: ";
echo "<a href='?action=callfunction&id=$var'>Click</a> ";
if(isset($_GET['action']) && $_GET['action'] == 'callfunction'){
// Used for the query and escape the URL
$var = mysqli_real_escape_string($Link, $_GET['id']);
$sql="UPDATE testtable SET hitcount = hitcount +1 WHERE id='".$var."'";
$result=mysqli_query($Link,$sql);
// Added a header, otherwise the old method will generate the following warning
// Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in...
header("Location: http://www.example.com/your_counter_file.php");
exit; // Keep this in order to stop further execution
// ^ Change the url in header above to reflect your Web site's address
} // Closing brace for isset
echo "</td><td align='center'>";
echo $row['level'];
echo "</td><td align='center'>";
echo $row['hitcount'];
echo "</td></tr>";
} // Closing brace for while loop
mysqli_close($Link);
Just change your query like this to update the counter
$sql="UPDATE testtable SET `hitcount`=hitcount+1 WHERE id=".$id;
Don't use single quotes around value of counter since its a integer

record deleted when link is clicked

I have a link/page 'myfiles.php' which shows the details of the file that a certain user uploaded. But after clicking again/entering the 'myfiles.php' into the address bar, the records are gone in the page. What's supposed to be the solution? Please help. Thanks. Here's my code:
while ($row=mysql_fetch_array($query)) {
$row1 = $row['name'];
$row2 = $row['size'];
$row3 = $row['type'];
$delfile = "<a href='deletefile.php?file=$row1'>Delete file</a>";
$dlfile = "<a href='download.php?file=$row1'>Download</a> ";
echo "<p>";
echo $row1;
echo "<br>";
echo $row2;
echo "<br>";
echo $row3;
echo "<br>";
echo $dlfile;
echo $delfile;
}
Are you using some sort of browsing accelerator and donĀ“t you have a deletion confirmation?
It seems your browser is requesting all links on your page and deleting your records.
If you want to delete, insert, update, etc. records in a database, it is a very good idea to use POST instead of GET (like a clickable link), so you would have to add a form around every entry that posts the data to the server. You can of course skip this, but then you definitely need a POST based deletion confirmation.
I am assuming that $usersess is not changing? If this is dependent on a session or cookie - you should check that it is not expiring or being destroyed.
$query = mysql_query("SELECT * FROM uploadedfiles WHERE username='$usersess' ");
while ($row = mysql_fetch_array($query)) {
$delfile = "Delete file";
$dlfile = "Download ";
echo "<p>{$row['name']}<br>
{$row['size']}<br>
{$row['type']}<br>
{$dlfile}{$delfile}</p>";
}

How could I show only selected row in PHP?

I'm working at this thing that takes information from a MySQL database that comes from a contact form and displays it all to the user. Well, I got that far without issues using:
$result = mysql_query("SELECT * FROM contact");
while($row = mysql_fetch_array($result))
{
echo $row['name'] . "<br/>" . " " . $row['email'] . "";
echo "<br/>";
echo $row['message'];
echo "<br />";
}
Now I would like to add a button next to each item that would single them out, basically taking me to a page where only the selected row shows up, not all of them, as happens on this page.
The thing is that i don't know how to do that. So, does anyone have any ideas?
Thanks!
Add a button that refreshes the page with a "GET" parameter, such as yourpage.php?uid=123; Then do
if ($_GET['uid'] !== null) {
$id = (int) $_GET['uid'];
$result = mysql_query('SELECT * FROM contact WHERE id='.$id);
...
}

How to give a unique url/id to a question posted by the user?

There's a form called discussion.php, in which a user will fill out his/her question/discussion and post it to savedisc.php. Some of the savedisc.php looks like this:
$message = $_POST['message'];
$title = $_POST['title'];
$represents = $_POST['represents'];
//connect to database
//save the content of discussion/question into the database for future use
$sql="INSERT INTO Discussion (Message, Title, Type)
VALUES
('$message','$title','$represents')";
//Display user's question/discussion again
echo $message . "<br />";
echo $title . "<br />";
echo $represents . "<br />";
It is not shown above, but I am saving the id field manually, i.e. via phpmyadmin as a auto increment and primary key of course. Therefore, all of the values in the table Discussion will have their own unique id. Once the question/discussion is saved, I want to be able to display $title of each question on wb.php as a link, which as of now looks like this(some code from wb.php):
$result = mysql_query("SELECT * FROM Discussion ORDER BY id DESC");
//When user clicks the question/discussion Title, he/she will be directed to wbcomm.php
while($row = mysql_fetch_array($result))
{
echo "<a href='wbcomm.php' >{$row['Title']}</a><br />";
}
Until here, everything is working smooth. However, from here on, what I'm trying to do is, when the user clicks the question/discussion title via above code, I want him/her to be directed to wbcomm.php?id=1, where id=1 represents the unique id of the question/discussion. Some of the code from wbcomm.php is below:
if (isset($_GET['id']))
{
//connect to db
$wbid = mysql_real_escape_string($_GET['id']);
$sql = "SELECT * FROM Discussion WHERE id = '$wbid' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows() > 0) {
$discussion = mysql_fetch_object($res);
//display member's question here:
echo $discussion['id'] . "<br />";
echo $discussion['Title'] . "<br />";
echo $discussion['Type'] . "<br />";
echo $discussion['Message'] . "<br />";
}
else {
// discussion does not exist with ID
}
}
However, for some reason, the result is blank. I.e. the question/discussion doesn't even show up. What am I doing wrong? Is my procedure even correct?
Thank you.
In your wb.php, you create a link to wbcomm.php but you are not passing the ID of the discussion, so your $wbid will be empty. You need to pass the ID along with the link, like this:
while($row = mysql_fetch_array($result))
{
echo "<a href='wbcomm.php?id={$row['id']}' >{$row['Title']}</a><br />";
}
Your ID column is an autoincrement int type so you do not need to put it in quotes or escape it. You should definitely test it to see if it's numeric, though.
Use this SQL mysql_num_rows($res) > 0

Categories