I'm trying to create a "Like" button for some articles that I'm printing out from my database. But I'm stuck.
I get to the point where I have posted my vote from the jQuery and I get an empty VAR_DUMP.
And in my OOP class I'm not sure how to print out the votes when I got them to save in the database.
Here's my code
HTML
<?php
// IF theres is a id in adress field
//if(isset($_GET['id'])) {
$page = new CMS();
$gp = $page->getPage();
foreach ($gp as $sp) {
//var_dump($sp);
echo "<div class='pub'>";
echo "<h4 class='pub-headline'>" . $sp['title'] . "</h4>";
echo "<article class='pub_art'>" . $sp['content'] . "</article>";
echo "<p class='pub_created'>" . $sp['created'] . "</p>";
echo "<p class='pub_created_by'>". $sp['writer'] ."</p>";
echo "<button class='show'>Show</button>";
echo "<button class='noshow'>Hide</button>";
echo "<button class='btn-like'>Like</button>"; // Here is my button
echo "</div>";
}
?>
jQuery
/* --------------------Selecting article----------------------*/
// Calling for the method - likes
$(".btn-like").on("click", like);
function like(e) {
e.preventDefault();
// Declaring variables
var id=$(id).val();
var likes=$(".btn-like").val();
console.log('Click Click..');
$.post('classCalling4.php', {
id: id,
likes: likes },
function(data){
console.log(data);
});
}
PHP
var_dump($_POST); // ***** This VAR_DUMP is getting back to me empty
if(isset($_POST['id'])) {
//echo "rätt...";
$id = $_POST['id'];
$likes = $_POST['likes'];
$id = intval($id);
$likes = intval($likes);
$ul = new updateLikes();
if($ul->updateLikes($_POST['id'], $_POST['likes'])) {
echo "Created";
}
else {
} echo "noooo";
}
?>
And finally my OOP class, that is not complete because I'm stuck.
public function updateLikes($id, $likes) {
$stmt = $this->db->prepare('UPDATE pages SET likes = likes+1, WHERE id = $id');
$stmt->bind_param("ii", $likes, $id);
if($stmt->execute()) {
echo "win";
} else {
echo "lost";
}
}
At least your OOP class have some errors:
$stmt = $this->db->prepare('UPDATE pages SET likes = likes+1, WHERE id = $id');
$stmt->bind_param("ii", $likes, $id);
Should be:
$stmt = $this->db->prepare('UPDATE pages SET likes = likes + :likes, WHERE id = :id');
$stmt->bind_param(":likes", $likes);
$stmt->bind_param(":id", $id);
or if the meaning is to increase likes only by one, then:
$stmt = $this->db->prepare('UPDATE pages SET likes = likes + 1, WHERE id = :id');
$stmt->bind_param(":id", $id);
If var_dump doesn't return anything, then there might be error in the PHP code (causes error code 500 and depending on PHP settings PHP might return blank page)
Related
I have news_Category and news table, here every news comes under one category,so before deleting new_category I want to display user a msg that child news exists in this category so u are not allowed to delete, If there are no child news than a confirm alert to user that "do u really want to delete".If he confirms the news category gets deleted.
HTML STUFF
<?php echo "<a style='color:red;''
href='delete.php?delete=$values[category_id]&
img=$values[category_image]'><i class='fas fa-trash-alt'></i></a>"; ?>
if ($_GET['msgError']) {
echo "<script>alert('First Delete The News Than Category');</script>";
}
if ($_GET['msg']) {
?>
<?php
}
?>
DELETE.PHP
if (isset($_GET['delete'])) {
$id= $_GET['delete'];
$img=$_GET['img'];
$obj=new commands();
$obj->delete_category($id,$img);
}
Delete Function
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
I am not able to make to logic here, how can I check whether the child news exists so i can display error msg and if there is no child news how to show confirm alert to allow delte
You need to check to see if the result is empty.
Something like this:
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($result)) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
Edit due to extra details request
On the front end you just need to display the GET msgError like this:
<?php isset($_GET['msgError']) ? echo url_decode(base64_decode($_GET['msgError'])) : '' ?>
Where you want to show the message text.
I have the codes to search autocomplete from MySQL and the match query can be clicked and direct me to a new page. How can i have the result of the clicked queries to be displayed in the new page w/out using any URL from database because I need to avoid using lots of HTML files. Thank you.
<p id="searchresults">
<?php
// PHP5 Implementation - uses MySQLi.
// mysqli('localhost', 'yourUserbookTitle', 'yourPassword', 'yourDatabase');
$db = new mysqli('localhost', 'root', '', 'book');
if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT * FROM bookinfo WHERE bookTitle LIKE '%" . $queryString . "%'");
if($query) {
// While there are results loop through them - fetching an Object.
// Store the category id
$bookTitle = 0;
while ($result = $query ->fetch_object()) {
if($result->bookTitle != $bookTitle) { // check if the category changed
echo '<span class="category">'.$result->bookTitle.'</span>';
$bookTitle = $result->bookTitle;
}
echo '<a href="'.$result->url.'">';
echo '<img src="search_images/'.$result->bookimage.'" alt="" />';
$bookTitle = $result->bookTitle;
if(strlen($bookTitle) > 35) {
$bookTitle = substr($bookTitle, 0, 35) . "...";
}
echo '<span class="searchheading">'.$bookTitle.'</span>';
$author = $result->author;
if(strlen($author) > 80) {
$author = substr($author, 0, 80) . "...";
}
echo '<span>'.$author.'</span></a>';
}
echo '<span class="seperator">Nothing interesting here? Try the sitemap.</span><br class="break" />';
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
?>
</p>
I don't know if I get your problem right, but if you need to display a new page with the selected book data/review/comments, I would add :
echo '<span>'.$author.'</span></a>'; /* after this line */
echo '<span>Read more > click here</span>'; /* where $bookID id the ID column in your DB */
Then, on the new page, retrieve data from DB according to $bookID value and display it...
I have a problem here that Ive described in the unanswered question mysql query returning false even when values DO exist in table? Trying to find if not in table?
Basically, I am trying to echo a special image along with a link IF a username string is in an array that means a conversation has been started with them. This all happens when a search bar is entered in.
I have succeeded in storing the users who either SHOULD NOT BE PRINTED or PRINTED WITH A SPECIAL IMAGE here:
$convoArray = array();
echo '<form class="usersearchpm" method="post"><input class="searchbarpm" name="searchbarpm"></input></form>';
$con = mysqli_connect("localhost","username","password","sqlserver");
//$num = mysqli_query($con, "SELECT * FROM `pm_messages` WHERE user_from=".$account['id']."");
$numCon = mysqli_query($con, "SELECT * FROM `conversation` WHERE user_one=".$account['id']."");
$numrows = mysqli_num_rows($numCon);
while ($u = mysqli_fetch_assoc($numCon))
{
//get other users usernames to echo link
$getUserTwo = mysqli_query($con, "SELECT * FROM `accounts` WHERE id=".$u['user_two']."");
$s = mysqli_fetch_assoc($getUserTwo); //s[username] is a user that DOES have convo
array_push($convoArray, $s['username']);
//echo "<a href='message.php?id={$s['id']}'><li><img class = 'dmCircle' src = '../images/chatCircle.png'/>{$s['username']} </li></a>";
}
This works. Problem comes with the search - this code prints each user the the size of the convo array because the echo is called each time a for loop circles through -
if(isset($_POST['searchbarpm'])){
// foreach($convoArray as $name)
// {
// echo $name;
// }
//$sess->getUsers();
$dbh = mysqli_connect("localhost","username","password","sqlserver");
$query = $_POST['searchbarpm'];
$q = mysqli_query($dbh, "SELECT * FROM sqlserver.accounts WHERE username LIKE '%".$query."%'");
//display all the results
while($row = mysqli_fetch_assoc($q)){
// $checkConvo = mysqli_query($dbh, "SELECT * FROM sqlserver.conversation WHERE user_one=".$user_id." AND user_two=".$row['id']."");
if($row['id']!= $user_id) { //only output users they dont have convo going with because theyre already printed!!!
for($i=0;$i<sizeof($convoArray);$i++)
{
if($row['username']==$convoArray[$i])
{
echo 'match!!';
echo $row['username'];
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/chatCircle.png'/> {$row['username']}</li></a>";
}
else
{
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/noChatCircle.png'/> {$row['username']}</li></a>";
}
}
}
}
}//
This code does recognize when the user searched for is in the array and DOES print a special image, however again it does this multiple times.
I need help and cannot finish my project without this. Been struggling for a week here.
How can I print the users in the array with a special image? Or have the search not turn them up at all?
What am I doing wrong?
Use this [Assuming that $convoArray contains the usernames are their array values]
if(in_array($row['username'], $convoArray) {
echo 'match!!';
echo $row['username'];
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/chatCircle.png'/> {$row['username']}</li></a>";
}
else {
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/noChatCircle.png'/> {$row['username']}</li></a>";
}
Instead of the following code
for($i=0;$i<sizeof($convoArray);$i++)
{
if($row['username']==$convoArray[$i])
{
echo 'match!!';
echo $row['username'];
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/chatCircle.png'/> {$row['username']}</li></a>";
}
else
{
echo "<a href='message.php?id={$row['id']}'><li><img class = 'dmCircle' src = '../images/noChatCircle.png'/> {$row['username']}</li></a>";
}
}
I am going out of my mind as it is. I am trying to pass a variable from a page that shows all albums thumbnail image and name to a page that will display all the pictures in that gallery using that passed variable, but the variable is empty in the url on the target page. I have seen similar cases on the web and on this site and I've applied the suggestions but it's still the same. Here is the code that lists the thumbnail and passes the variable(id).
<?php
include ("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
$albums = mysqli_query($conn,"SELECT * FROM albums");
if (mysqli_num_rows($albums) == 0) {
echo "You have no album to display. Please upload an album using the form above to get started. ";
}
else{
echo "Albums created so far:<br><br>";
echo "<table rows = '4'><tr>";
while ($thumb = mysqli_fetch_array($albums)) {
echo '<td><a href ="view.php?id="'.$thumb['id'].'"/><img src = "'.$thumb['thumbnail'].'"/><br>'.$thumb['album_name'].'<br>'.$thumb['id'].'</a></td>';
}
echo "</tr></table>";
}
?>
The code for getting the passed variable is as follows:
<?php
include("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
$db = mysqli_select_db($conn,dbname);
if (isset($_GET['id'])) {
$album_id = $_GET['id'];
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn,$pic);
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
}
else{
echo "Pictures in the gallery:<br><br>";
while ($result = mysqli_fetch_assoc($picQuery)) {
echo "<img src='".$result['photo_path']."'/>";
}
}
}
?>
Please help as i have spent the last two days trying to get it right.
First, your's code is weak against sql injections:
$album_id = $_GET['id']; // here
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
Use either $album_id = intval($_GET['id']) or prepared statements functionality.
Second, add debug lines to your code, like:
<?php
include("config.php");
if (isset($_GET['id'])) {
$album_id = intval($_GET['id']);
var_dump($album_id); // should print actual passed id
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
var_dump($conn _id); // should print conn resource value
$db = mysqli_select_db($conn, dbname);
var_dump($db); // should print 'true' if db select is ok
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn, $pic);
var_dump($picQuery); // should print query resource value
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
} else {
echo "Pictures in the gallery:<br><br>";
while (($result = mysqli_fetch_assoc($picQuery)) !== false) {
var_dump($result ); // should print fetched assoc array
echo "<img src='".$result['photo_path']."'/>";
}
}
}
Notice $album_id = intval($_GET['id']) and while (($result = mysqli_fetch_assoc($picQuery)) !== false) parts
Then follow link view.php?id=<existing-album-id> and observe debug result. On which step debug output differs from expected - there problem is.
$stmt = $dbh->prepare("SELECT * FROM events ORDER by event_id DESC LIMIT 5") ;
$stmt->bindValue(1,$eventwhat);
$stmt->execute();
if ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)){
while($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)){
$_SESSION['id'] = $selected_row['event_id'];
$_SESSION['searchresultwhat'] = $selected_row['event_what'];
$_SESSION['searchresultwhere'] = $selected_row['event_where'];
$_SESSION['searchresultwhen'] = $selected_row['event_when'];
$_SESSION['searchresultwho'] = $selected_row['event_who'];
echo $_SESSION['id']."\r\n";
echo $_SESSION['searchresultwhat']."\r\n";
echo $_SESSION['searchresultwhere']."\r\n";
echo $_SESSION['searchresultwhen']."\r\n";
echo $_SESSION['searchresultwho']."\r\n";
echo "<br/>\n";
}
}
i have the code above to echo the last 5 entries in my database but the problem is it only show 4 it does not get the last 5 so when i have i entry only it does not show anything..what am i missing here why is the last entry not being retrieve?
remove if condition and do like below
$stmt = $dbh->prepare("SELECT * FROM events ORDER by event_id DESC LIMIT 5") ;
$stmt->bindValue(1,$eventwhat);
$stmt->execute();
while($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)){
$_SESSION['id'] = $selected_row['event_id'];
$_SESSION['searchresultwhat'] = $selected_row['event_what'];
$_SESSION['searchresultwhere'] = $selected_row['event_where'];
$_SESSION['searchresultwhen'] = $selected_row['event_when'];
$_SESSION['searchresultwho'] = $selected_row['event_who'];
echo $_SESSION['id']."\r\n";
echo $_SESSION['searchresultwhat']."\r\n";
echo $_SESSION['searchresultwhere']."\r\n";
echo $_SESSION['searchresultwhen']."\r\n";
echo $_SESSION['searchresultwho']."\r\n";
echo "<br/>\n";
}
Your if condition fetaches first row and so while will fetch remaining 4 rows
function makeGetRequest(e, key) {
if (!e) e = window.event;
if (!e.ctrlKey && !e.button == 1) { //this is to be able to open links by clicking the wheel button or ctrl+click
http.open('GET', key, true);
//assign a handler for the response
http.onreadystatechange = processResponse;
//actually send the request to the server
http.send(null);
return false; //this is important, otherwise the href link will trigger and not the onclick
}
}