I'm trying to update a one value when a user clicks on a link.
<?php
$data = mysql_query("SELECT * FROM comments a LEFT JOIN pins b ON a.pin_id = b.id INNER JOIN board c on b.board_id = c.id WHERE a.to_id = '$myid' AND a.status = 'unviewed'")
or die(mysql_error()); while($info = mysql_fetch_array( $data ))
{
Print "<li>";
Print "<a href='/board/pins/".$info['board_id']."/".$info['pin_id']."'>";
Print "<img src='".$info['pin_url']."' width='50' align='left'>";
Print "<font size='1'>comment received on ".$info['date']."</font></a>";
Print "Collection: ".$info['board_name']."</li>";
}
?>
The link is the one above.
how can I edit the above code to include an update query "UPDATE comments SET status='viewed' WHERE to_id = '$myid' AND id='$postid'" when the link is clicked?
EDIT:
this is my mark_viewed.php:
<?php
$con=mysqli_connect("XXX","XXX","XXX","XXX");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// get values sent from address bar
$myid=$_GET['myid'];
$postid=$_GET['postid'];
mysqli_query($con,"UPDATE comments SET status='viewed' WHERE to_id ='$myid' AND id='$postid'");
mysqli_close($con);
?>
And my the send page:
<?php // display of the notifications dropdown menu
$query_select = "SELECT * FROM comments a LEFT JOIN pins b ON a.pin_id = b.id LEFT JOIN board c on b.board_id = c.id WHERE a.to_id = '$myid' AND a.status = 'unviewed' ORDER BY a.date DESC";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
$rows[] = $row;
foreach($rows as $row){
$myid = $row['user_id']; // my id
$name = $row['board_name']; // collection name
$boardid = $row['board_id']; // collection id
$postid = $row['pin_id']; // post id
$url = $row['pin_url']; // image url
echo "<li><a href='/board/pins/$boardid/$postid' data-myid='$myid' data- postid='$postid' class='markviewed'>";
echo "<img src='$url' height='50' width='50'>";
echo "New comment in $name.";
echo "</a></li>";
}
?>
I have the JS in the head of the same page but it isn't working. The varibles are fine on this page $myid and $postid but they aren't being sent/received on mark_viewed.php
Try this code (AJAX as suggested in comments). It assumes What it basically does is:
Print relevant ids into html as attributes.
Binds a listener to click event on those links
After pinging http://domain.com/mark_viewed.php (file that does the query updating comments as viewed) it redirects the browser to the desired location (/board/pins/...)
//html part
<?php
$myid = 1234;
$postid = 333;
//echo prepared link with ids in it's data-attributes
echo '<a href="/board/pins/"'.$info['board_id'].'/'.$info['pin_id'].'"
data-myid="' . $myid . '"
data-postid="' . $postid . '"
class="markviewed">mark ids as viewed and go to /board/pins/...</a>';
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//bind a listener to "click" event on links with class "markviewed"
$('a.markviewed').click(function(event) {
//prevent default behavior just in case
event.preventDefault();
//get ids from clicked <a>
var myid = $(this).attr('data-myid');
var postid = $(this).attr('data-postid');
//ping the address to mark clicked link as viewed
$.ajax('http://domain.com/mark_viewed.php?myid=' + myid + '&postid=' + postid);
//redirect to the link in the href attribute
window.location.href = $(this).attr('href');
});
});
</script>
Related
I'm trying to make a website for people to post their cars for sale. I've done posting data into database. Everything works fine, but when they go to Member's page, it should show them added cars with photo, and edit button.
Here's my function to display added cars:
function get_user_auto($username) {
//extract from the database all the URLs this user has stored
$conn = db_connect();
$result = $conn->query("
SELECT
images.filename,
car_make.make,
car_model.model,
car_generation.name,
cars.year,
cars.price,
cars.car_id
FROM cars
LEFT JOIN car_make ON cars.make = car_make.make_id
LEFT JOIN car_model ON cars.model = car_model.model_id
LEFT JOIN car_generation ON cars.generation = car_generation.generation_id
LEFT JOIN images ON cars.car_id = images.car_id
WHERE cars.username = '$username';");
if (!$result) {
return false;
}
//create an array of the URLs
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$make = $row["make"];
$model = $row["model"];
$generation = $row["name"];
$year = $row["year"];
$price = $row["price"];
$filename = $row["filename"];
$imageURL = 'uploads/'.$filename;
?>
<img src="<?php echo $imageURL; ?>" alt="" width="100"/>
</div>
<div>
<?php echo "" . $make ." " . $model ." - " . $year ." " . $price ." USD";?>
Edit
</div>
</div>
<?php
}
} else {
echo "You did not add car for sale yet.";
}
}
So, i.e. I have added one car with 3 photos attached to it by car_id, when I retrieve data and echo it, it shows the same car 3 times with 3 different photos.
If you want only one row per car then you can add GROUP BY to query like this
GROUP BY car_id. This will allow only one row per car_id regardless of how many images car have (but it might not select image you like).
// PAGE ONE
This is the index page, Here I am printing out rows from a list of
movie´s with some basic info, title , year.
I am also adding edit and delete links to the movies,
these work by passing the row id's of that movie.
$sql = "SELECT c.* , d.* FROM category c , movies d WHERE c.ID=d.ID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='floatbox collection'><table><tr><th>Titel</th><th>regissör</th><th>År</th><th>Genre</th><th>Ändra</th><th>Ta bort</th>";
while($row = $result->fetch_assoc()) {
echo
"<tr><td>".$row["title"]."</td><td>".$row["director"]."</td><td>"
.$row["year"]."</td><td>".$row["category"]."</td>
<td><a href='edit.php?row=".$row["ID"]."'>justera</a></td>
// delete link to send ID to next page
<td><a href='delete.php?delete=".$row["ID"]."'>stryk</a></td>";
}
echo "</table></div>";
} else {
echo "0 results";
}
// PAGE TWO
Here I have my $row[ID] trough $_get by the link on the previous page,
I have checked the value by "dumping" so I know that the row ID is in that
variable: The thing is, How do I call that $ID in my sql statement?
I'm trying to delete by calling that ID on the table row.
// Variable with correct ID value
if(isset($_GET["ID"]))
if($_GET["ID"]) = $ID; // This doesn't work, Do I need to convert
the $get_ID to a variable with the ID that can be called in the statement?
or is my syntax wrong?
// Delete join
$sql = "SELECT * FROM movies, category
INNER JOIN category ON movies.ID = category.ID
DELETE WHERE movies.ID = '$ID'"; // No syntax works here
// Any help appreciated.
// konfirmering
if ($conn->query($sql) === TRUE) {
echo "Register struket <br>
<a href='panel.php'>Gå tillbaka</a>";
} else {
echo "Fel vid anslutning : " . $conn->error;
}
As per your code your delete.php would be like this:
// Variable with correct ID value
if (isset($_GET["delete"])) {
$ID = $_GET["delete"];
// Delete join
$sql = "DELETE FROM movies, category INNER JOIN category ON movies.ID = category.ID WHERE movies.ID = '$ID'";
// konfirmering
if ($conn->query($sql) === TRUE) {
echo "Register struket <br><a href='panel.php'>Gå tillbaka</a>";
} else {
echo "Fel vid anslutning : " . $conn->error;
}
}
I'm tired of searching for the solution my news comment system.
What i have.
I have 2 different mysql tables item (id, title, category_id, details) and comments (id, item_id, comment)
If i have single news then counting is fine like here in picture:
Single news
Code:
if (!empty($comments)) {
$comm = count($comments);
} else {
$comm = 0;
}
But if i use same code category view, result is:
Category view
If i use code:
$sqls = mysql_query("SELECT c.item_id,
COUNT(c.comment)
FROM comments c
RIGHT JOIN items i
ON c.item_id = i.id
GROUP BY c.item_id");
$comm = mysql_num_rows($sqls);
$smarty->assign('comm',$comm);
Result is :Some number of comments
How to make possible to see the Category View the correct number of comments?
TRY this example. The result is the same as the screenshot below but with some background colour to distinguish the difference. Of course you should change to your own connection and layout.
<?php
$db = new PDO('sqlite:news.db');//change to your own
$sql = $db->prepare("
SELECT item.id, item.title, item.details, comments.comment, COUNT(comments.id) AS NumberOfComment
FROM item LEFT JOIN comments ON item.id = comments.item_id
GROUP BY item.id ORDER BY item.id");
$sql->execute();
$row = $sql->fetchAll();
//get comment
$comment = $db->prepare("SELECT comment FROM comments WHERE item_id = ?");
foreach ($row as $rows){
echo "<br>";
echo "Title: ".$rows['title'];
echo "<br>";
echo "Details: ".$rows['details'];
echo "<br>";
echo "<i>".$rows['NumberOfComment']." comments </i>";
echo "<br>";
$comment->execute(array($rows['id']));
$comments = $comment->fetchAll();
echo '<div style="background-color:pink;">';
foreach ($comments as $showcomment){
echo $showcomment['comment'];
echo "<br>";
}
echo "</div>";
echo "<br>";
}
?>
example item table
example comment table
and the result is...
Taking a deep breath, really don't know how to combine 2 tables from my MySQL,
I will show you the tables which I've and the rows which needed to be combinated.
Table called post:
As you see cat means Category, which category it is (see below category table nameID is same as cat here)
For example my page www.site.com/category.php?nameid=NAMEID(table category)&id=ID(table post) Need to be combined so if I go to ?nameid=1&id8 the page should be blanc or giving an error since id=8 is category 2 and not 1.
// BEGIN OF SHOWING CONTENT PAGE
if (isset($_GET['id'])){
$naamID = mysql_real_escape_string($_GET['nameID']);
$id = mysql_real_escape_string($_GET['id']);
$idnext = $id + 1;
$gn = (" SELECT * FROM category WHERE nameID='".$naamID."'") or die(mysql_error());
$go = (" SELECT * FROM post WHERE id='".$id."'") or die(mysql_error());
$gnn = mysql_query($gn) or die(mysql_error());
$goo = mysql_query($go) or die(mysql_error());
$gnnn = mysql_fetch_array($gnn);
$gooo = mysql_fetch_array($goo);
if(empty($gooo['youtube'])){
} else {
?> <h2> <?php echo htmlspecialchars($gooo["title"]); ?> </h2><br />
<?php
echo '<iframe width="560" height="315" src="//www.youtube.com/embed/'.$gooo["youtube"].'" frameborder="0" allowfullscreen></iframe><br />';
}
if(empty($gooo['pic'])){
} else {
?> <h2> <?php echo htmlspecialchars($gooo["title"]); ?> </h2><br />
<?php
echo '<img src="'.$gooo["pic"].'"/>';
}
}
?>
SELECT table1.keyid FROM table1
UNION
SELECT table2.keyid FROM table2
i wish this example help you ,try to understand how to combine 2 tables
I think i don't understand need of passing categid, as post id itself looks like primary key, so you must able to fetch particular post record, and can retrieve name of that category which is linked with requested post using something like(you just need to pass post id in parameter)
SELECT youtube,title,c.name,pic FROM post p
INNER JOIN categories c
ON c.nameid=p.cat
WHERE p.id=2
If you are trying to get requested post record along with all posts from requested category than you can write query like
SELECT youtube,title,c.name,pic
FROM post
INNER JOIN categories c
ON c.nameid=p.cat
WHERE (p.id=8 or cat=2)
Hope this will help!
Thanks
Suresh
Update:
Based on what I understood, following code snippet may solve your problem
$row = mysql_query("SELECT p.cat, c.nameID FROM post p INNER JOIN category c ON p.cat = c.nameID WHERE p.cat = '".$id."' AND c.nameID = '".$naamID."' LIMIT 1");
if(mysql_num_rows($row)==0)
{
echo("This post doesn't exist on this category")
}
Update 2:
<?if (isset($_GET['id']))
{
$naamID = mysql_real_escape_string($_GET['nameID']);
$id = mysql_real_escape_string($_GET['id']);
$row1 = mysql_query("SELECT p.cat, c.nameID FROM post p INNER JOIN category c ON p.cat = c.nameID WHERE p.cat = '".$id."' AND c.nameID = '".$naamID."' LIMIT 1");
if(mysql_num_rows($row1)==0)
{
echo("This post doesn't exist on this category");
}
else
{
$idnext = $id + 1;
$gn = (" SELECT * FROM category WHERE nameID='".$naamID."'") or die(mysql_error());
$go = (" SELECT * FROM post WHERE id='".$id."'") or die(mysql_error());
$gnn = mysql_query($gn) or die(mysql_error());
$goo = mysql_query($go) or die(mysql_error());
$gnnn = mysql_fetch_array($gnn);
$gooo = mysql_fetch_array($goo);
/*--------------your other display code when data is available-------------*/
}
}
?>
First time for me here.
I am using PHP, MySQL, JavaScript and running JQUERY and AJAX functions.
I have an anchor link that runs a function.
The function emptys a DIV tag and then fills/displays (SELECT query) a table of rows in the DIV with a is null where clause. Each row has a select box where the NULL data column would go. The data in the select box comes from a different table.
When the select box changes it immediately runs the ajax to UPDATE the table row with the new data in the select box.
When you click the link to run the function again (empty, select query and display based on null column) the row that was just updated to the DB shows up again based on the is null clause. Checking the DB table at this point shows that it is in fact not null and was UPDATEd properly the first go around.
The page is never refreshed during this process and never has to be. If I do refresh it shows the proper data without the BUG.
All your thoughts are greatly appreciated.
matt
function closeItemsBtn() { // called by a click function of a standard link/button
$('#CloseItems').empty(); // remove all html from the DIV
var newAppend = '';
<?
//[... connect to db ...]
// select info from 2 different tables so it can be used in different locations if necessary
// where the row has not been reviewed and therefore is null
$query = "select * from nearmiss where reviewedId is null order by submitDate desc";
$result = $db->query($query) or die($db->error);
$query2 = "select * from hazardid where reviewedId is null order by submitDate desc";
$result2 = $db->query($query2) or die($db->error);
$num_rows = $result->num_rows;
$num_rows2 = $result2->num_rows;
// create html for the DIV tag. Creates a table in a DIV that collapses by clicking aCloseList.
// each row is in tbody so it can be striped by a all purpose striping function
// this part is the table header and opening div tags and link
$newAppend = "<p id=\"closeList\">Show/Hide {$num_rows} Near Misses requiring attention.</p><div id=\"closenearmiss\" style=\"display:none;\"><table class=\"closenearmisstable\"><tbody><tr><td>Date Submitted</td><td>Submitted By</td><td>Location</td><td>Reviewed By</td></tr><tr><td rowspan=\"2\">Type</td><td colspan=\"3\">Description / Observation</td></tr><tr><td colspan=\"3\">Action / Reinforcement</td></tr></tbody>";
// update various foreign key information from other tables
for ($i=0;$i<$num_rows;$i++) {
$row = $result->fetch_assoc();
$query3 = "select location from locations where locationId='{$row['locationId']}'";
$result3 = $db->query($query3);
$location = $result3->fetch_assoc();
$query3 = "select name from employees where employeeId='{$row['employeeId']}'";
$result3 = $db->query($query3);
$name = $result3->fetch_assoc();
// here is the table itself with the select tag in the null column name=reviewed
$newAppend .= "<tbody><tr><td>{$row['submitDate']}</td><td>{$name['name']}</td><td>{$location['location']}</td><td><form name=\"nearmissreview\" action=\"\" method=\"\"><input type=\"hidden\" name=\"docId\" value=\"{$row['nearmissId']}\"><input type=\"hidden\" name=\"type\" value=\"nearmiss\"><select name=\"reviewed\"><option>Choose name to sign off</option></select></form></td></tr><tr><td rowspan=\"2\">Near Miss</td><td colspan=\"3\">{$row['description']}</td></tr><tr><td colspan=\"3\">{$row['action']}</td></tr></tbody>";
}
$newAppend .= "</table></div>";
// this is the beginning of the second table same structure as first with collapsing but
// different data
$newAppend .= "<p id=\"closeList\">Show/Hide {$num_rows2} Hazard IDs requiring attention.</p><div id=\"closehazardid\" style=\"display:none;\"><table class=\"closehazardidtable\"><tbody><tr><td>Date Submitted</td><td>Submitted By</td><td>Location</td><td>Reviewed By</td></tr><tr><td rowspan=\"2\">Type</td><td colspan=\"3\">Description / Observation</td></tr><tr><td colspan=\"3\">Action / Reinforcement</td></tr></tbody>";
for ($i=0;$i<$num_rows2;$i++) {
$row = $result2->fetch_assoc();
$query3 = "select location from locations where locationId='{$row['locationId']}'";
$result3 = $db->query($query3);
$location = $result3->fetch_assoc();
$query3 = "select name from employees where employeeId='{$row['employeeId']}'";
$result3 = $db->query($query3);
$name = $result3->fetch_assoc();
$newAppend .= "<tbody><tr><td>{$row['submitDate']}</td><td>{$name['name']}</td><td>{$location['location']}</td><td><form name=\"hazardidreview\" action=\"\" method=\"\"><input type=\"hidden\" name=\"docId\" value=\"{$row['hazardidId']}\"><input type=\"hidden\" name=\"type\" value=\"hazardid\"><select name=\"reviewed\"><option>Choose name to sign off</option></select></form></td></tr><tr><td rowspan=\"2\">Hazard ID</td><td colspan=\"3\">{$row['description']}</td></tr><tr><td colspan=\"3\">{$row['action']}</td></tr></tbody>";
}
$newAppend .= "</table></div>";
echo "newAppend='{$newAppend}';";
$result->free();
$result2->free();
$result3->free();
$db->close();
?>
// put HTML of $newAppend php in the DIV
$('#CloseItems').append(newAppend);
// fill the select box with a variable set somewhere else in the code not displayed here
$('#CloseItems select[name=reviewed]').append(newAppendE);
stripePointsTable('.closenearmisstable tbody');
stripePointsTable('.closehazardidtable tbody');
// close list click options
$('#closeList > a').each(function() {
$(this).click(function() {
if ($(this).parent().next().css('display')=='none') {
$(this).parent().next().slideDown('slow');
} else {
$(this).parent().next().slideUp('fast');
}
});
});
// select tag change function that calls ajax and displays a message in a DIV called header
$('#closenearmiss select').change(function() {
function processDataClose(data, success) {
if (success) {
$('#header').prepend(data+"<br />");
closeItemsBtn();
} else {
$('#header').prepend(data+"<br />");
}
}
var formData = $(this).parent().serialize();
$.post('processreviewsign.php',formData,processDataClose);
});
jQuery caches your ajax calls. This is likely why you see the correct result when you refresh the page, but not in subsequent calls via ajax.
Try setting cache: false in your ajax call