i'm new to php and what im trying to do here is add rating +1 for specific id (1,10,30....) whenever i press arrow up button.
I need to add id value (echo $row['id'];) to mysqli_query() somehow.
Can someone help please? :)
<?php include("db.php")?>
<?php
$sql = "SELECT * FROM gifs";
$result = mysqli_query ($db,$sql);
?>
<?php
//Fetch data from database
if ($result -> num_rows >0){
while($row = mysqli_fetch_array($result)){
?>
<div><?php echo $row["name"];?></div>
<p id="<?php echo $row['id'];?>">
<?php echo $row['copygif'];?></p>
$add = $row['id']; //i know this dosnt work...
<i onClick="<?php mysqli_query($db,"UPDATE gifs SET rating = rating + 1 WHERE id= $add ");?>"></i>
How do i translate ($row['id'];) into mysqli_query( id = ?)
Thank You
Very quickly cobbled together to show how you might accomplish your goal. You cannot simply embed the sql query as you did - the PHP code runs when the page loads ( it being server side code ) so will execute before you see any content on the page. The event click is a clientside event so you need some mechanism to send the request from the client to the server - typically one might use ajax or, as here, a form submission. The code below was not tested so you might find little mistooks but the idea should help solve the issue - this though is only one method you could employ.
<?php
/* include db connection */
include('db.php');
/* Process form submission */
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['id'] ) ){
$id=$_POST['id'];
/* sql query for prepared statement */
$sql='update gifs set rating = rating + 1 where id=?;';
/* prepare the sql query */
$stmt=$db->prepare( $sql );
if( $stmt ){
/* bind the placeholder to the id & execute */
$stmt->bind_param('i',$id);
$result=$stmt->execute();
} else {
exit( 'error: failed to prepare sql' );
}
}
/* select recordset for display */
$sql = "select * from `gifs`;";
$result = $db->query( $sql );
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>gifs</title>
<script>
/* assign event listeners to `i` elements */
document.addEventListener('DOMContentLoaded',function(){
var form=document.forms['gifs'];
var id=form.querySelector('input[type="hidden"][name="id"]');
var col=Array.prototype.slice.call( form.querySelectorAll('i.vote') );
col.forEach(function(node){
node.onclick=function(e){
/* set the value of the hidden field to the data-id value of current `i` */
id.value=this.dataset.id;
form.submit();
}.bind( node );
});
},false );
</script>
</head>
<body>
<!-- add a basic form, using POST -->
<form name='gifs' method='post'>
<!-- hidden field for ID value -->
<input type='hidden' name='id' />
<?php
/* display recordset and create `i` elements that will register vote click */
if( $result->num_rows > 0 ){
while( $row = $result->fetch_object() ){
echo "
<div>{$row->name}</div>
<p id='{$row->id}'>{$row->copygif}</p>
<i class='vote' data-id='{$row->id}'>vote</i>";
}
}
?>
</form>
</body>
</html>
yes as #RamRaider mentioned in the comment above you may need to bind a function on up arrow button and pass the $row['id'] in i, and onclick on the button you can send this id via ajax to server and do what you to. Example may look like,
<?php while($row = mysqli_fetch_array($result)){
?>
<div><?php echo $row["name"];?></div>
<p id="<?php echo $row['id'];?>">
<?php echo $row['copygif'];?></p>
$add = $row['id'];
<i onClick="upButtonClick($row['id'])"></i>
<?php } ?>
Related
I am working on creating a like counter for quotes. I am trying to increment the like counter when the user clicks on the like button and display the number of likes.
Problems I encountered:
Like counter gets incremented when I refresh the page (Not because I am actually hit the like button).
I tried implementing jQuery for the updation of the like counter in real time but failed :(
I referred to all the QnA related to this couldn't find the desired solution. I went through this [question]PHP/MySQL Like Button, and made the necessary changes but now there is no updation in the database when I click the button.
This is the code for one quote.
<div class="testimonial text-sm is-revealing">
<div class="testimonial-inner">
<div class="testimonial-main">
<div class="testimonial-body">
<p id="q1">
<?php
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?></p>
</div>
</div>
<div class="testimonial-footer">
<div class="testimonial-name">
<button method="POST" action='' name="like" type="submit" class="like"><b>Like</b></button>
<?php
if(isset($_POST['like'])){
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
<label>
<?php
$link = mysqli_connect("localhost","root","","success");
$sql = "SELECT likes from voted WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?>
</label>
<button class="btn" id="clipboard" onclick="copyFunction('#q1')"></button>
</div>
</div>
</div>
How do I make the like counter implement when I click on the like button?
How do I implement jQuery and AJAX to this, so that the counter is updated without a page refresh?
Please pardon my poor code structure.
Thanks for any help.
P.S This how a single quote will look like
You need three things for an asynchronous setup like this to work:
Your back-end script to handle ajax requests
Your front-end page
Your JQuery script to send ajax requests and receive data
Your back-end PHP script would look something like this (async.php):
<?php
if(isset($_POST['get_quotes'])) {
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
}
if(isset($_POST['like'])) {
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
Your front-end page will include an element with an ID to hook onto with the JQuery, and a button with a class or ID to capture the click event (page.html):
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="core.js"></script>
<body>
<button id="increment-like" value="Like" type="button" />
<p id="like-count">
</p>
</body>
<html>
Finally, your JavaScript file should look something like this, for a basic ajax request using JQuery (core.js):
$(document).ready(function() {
// initially grab the database value and present it to the view
$('#like-count').text(getDatabaseValue());
$('#increment-like').on('click', function() {
incrementDatabaseValue();
});
});
function getDatabaseValue() {
$.post("async.php",
{
get_quotes: true
},
function (data, status) {
// check status here
//return value
return data;
});
}
function incrementDatabaseValue() {
$.post("async.php",
{
like: true
},
function (data, status) {
// check status here
// update view
$('#like-count').text(getDatabaseValue());
});
}
I haven't tested this code but it should be clear and detailed enough to get you on the right track.
I have a 'Posts' table (containing submitted posts) and a 'Replies' table (containing all replies to all posts) in my database.
If a user replies to a post, I want the row in the database containing the reply to also contain the id of the original post.
Everything is inputting to the database fine, except for the post_id value, which is zero for every entry. How can I fix this?
home.php:
<?php
// top_content.php includes the database connection file.
include "top_content.php";
// Include our script to convert MySQL timestamp to 'ago' format.
include "time_ago.php";
// Create an object for the time conversion functions
$timeAgoObject = new convertToAgo;
include "menu_and_logo.php";
// Query the database for all submitted posts. //
$sql = "SELECT * FROM Posts ORDER BY date DESC";
// Store the result in a variable. //
$res = mysqli_query($db, $sql) or die(mysqli_error);
// Check that the result has > 0 rows; that at least one post exists in the database. //
if(mysqli_num_rows($res) != 0) {
// The mysqli_fetch_array retrieves and returns the next row of our query, which is then assigned to $row. //
// Then it executes the echos, and the procedure begins anew. This is how we get the post list. //
while($row = mysqli_fetch_array($res)) {
// Set the post_id variable equal to the post_id of each post. //
$post_id = $row['post_id'];
$ts = $row['date'];
$post_title = $row['post_title'];
$post_creator = $row['post_creator'];
// Convert Date Time
$convertedTime = ($timeAgoObject -> convert_datetime($ts));
// Then convert to 'ago' time
$when = ($timeAgoObject -> makeAgo($convertedTime));
// Display the data of each row. THe while row will execute all posts, creating a list
// display.
echo '<div>';
// The text is set as the post title, and points to post.php?id=*the post_id of the post. //
// In post.php, we check that $_GET['id'] is set (that the user is visiting post.php?id=some_integer),
// then query the database for the respective post, and echo the relevant content. //
echo ''.$post_title.'';
echo '<p>by '.$post_creator.' '.$when.'</p>';
echo '</div>';
}
}else {
echo "There are no posts.";
}
?>
post.php:
<!DOCTYPE html>
<?php
session_start();
// Include our script to convert MySQL timestamp to 'ago' format.
include "time_ago.php";
// Create an object for the time conversion functions
$timeAgoObject = new convertToAgo;
// Iniate connection to the database.
include "db_connect.php";
// Check that the user is visiting post.php?id=some_integer).
if($_GET['id']) {
// Set the post id as a variable, for convenience.
$post_id = $_GET['id'];
// Query the database for the post that corresponds to the post-title link that has been clicked.
$sql = "SELECT * FROM Posts WHERE post_id = '".$post_id."' ";
$res = mysqli_query($db, $sql)or die(mysqli_error());
// Check that there exists a row containing the relevant post id.
if(mysqli_num_rows($res) != 0) {
// Store the current row's array of data as a variable.
while($row = mysqli_fetch_array($res)) {
// Set the current row's data as variables.
$post_title = $row['post_title'];
$post_content = $row['post_content'];
$post_creator = $row['post_creator'];
$ts = $row['date'];
// Convert Date Time
$convertedTime = ($timeAgoObject -> convert_datetime($ts));
// Then convert to ago time
$when = ($timeAgoObject -> makeAgo($convertedTime));
// Display the relevant post data.
echo '<h2>'.$post_title.'</h2>';
echo '<p>Submitted by '.$post_creator.' '.$when.'</p><nr><br>';
echo ''.$post_content.'';
}
}else{
echo "This post does not exist.";
}
}else{
header("home.php");
}
?>
<!-- I've moved the html tags here because the file needs the $post_title variable before setting the title -->
<html>
<head><title><?php echo ''.$post_title.' - Lboro Maths'; ?></title></head>
<body>
<!-- #2: The form where users can submit replies to the original post. -->
<form action="reply_parse.php" method="POST">
<input type="textarea" name="reply_content" placeholder="Post a reply...">
<input type="submit" name="submit_reply" value="Reply">
</form>
</body>
</html>
reply_parse.php:
<?php
session_start();
include "db_connect.php";
$post_id = $_GET['id'];
$reply_content = $_POST['reply_content'];
$reply_creator = $_SESSION['username'];
$date = date('y-m-d H:i:s');
if(isset($_POST['submit_reply'])) {
$sql = "INSERT INTO Replies (post_id, reply_content, reply_creator, reply_date) VALUES ('$post_id', '$reply_content', '$reply_creator', '$date')";
$res = mysqli_query($db, $sql)or die(mysqli_error);
header("Location: home.php");
}else{
echo "Fail.";
}
?>
We needed to insert a hidden field and pass to it the variable GET value for 'id'.
Original:
<body>
<!-- #2: The form where users can submit replies to the original post. -->
<form action="reply_parse.php" method="POST">
<input type="textarea" name="reply_content" placeholder="Post a reply...">
<input type="submit" name="submit_reply" value="Reply">
</form>
</body>
Fixed:
<body>
<!-- #2: The form where users can submit replies to the original post. -->
<?php
echo "<form action='reply_parse.php' method='POST'>";
echo "<input type='hidden' name ='post_id' value='$post_id'>";
echo "<input type='textarea' name='reply_content' placeholder='Post a reply...'>";
echo "<input type='submit' name='submit_reply' value='Reply'>";
echo "</form>";
?>
</body>
You have no "id" field in your form in post.php, and the form is method POST not GET, so "reply_parse.php" is getting NOTHING as "id". I think that's the problem.
My database table has 2 fields: id (int) and state (enum -> 0,1).
What I need to do is to update my database (my state field) with the state of a checkbox (0 for empty, 1 for checked).
To show each of the fields in my database, I use a loop:
Loop:
<?php
foreach ( $posts_array as $module )
{
?>
<h2><?php echo $module->titre; ?></h2>
<input type="checkbox" name="chkbx_<?php echo $module->id; ?>"> id="chkbx_<?php echo $module->id; ?>" class="onoffswitch-checkbox"> On/Off <br />
<?php
}
?>
My update file:
foreach ($_GET['onoffswitch-checkbox'] as $id => $state)
{
// $_GET['onoffswitch-checkbox'] = class for all my checkboxed
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;
}
Where I need help is the AJAX part of the code. I'm guessing it looks something like this, but it doesn't seem to work:
AJAX
$(document).ready(function() {
$("onoffswitch-checkbox").click(function() {
var id = $(this).attr('id');
$("#state_span").load("module_update.php?"+id);
}
}
I've been looking around, seen a few examples where the we could do so with a submit button, but none where the information is automatically recorded when clicking the checkbox.
Try this:
AJAX
$(document).ready(function() {
$(".onoffswitch-checkbox").click(function() {
var id = this.id; //changed here also, just because jQuery is not needed here
var state = this.checked ? 1 : 0;
$("#state_span").load("module_update.php?id="+id+"&state="+state);
}
}
Changed 3 things:
added a dot in $("onoffswitch-checkbox") so its now $(".onoffswitch-checkbox")
added id= after module_update.php? and before id value.
since you need state also I added that also with a & to separate the values for $_GET in php to separate them
PHP
I don't know what you mean with $_GET['onoffswitch-checkbox'] in the php, maybe a mistake? My suggestion does not need it anyway, neither does your mysql query.
Since you will be only clicking one at a time I see no need for the foreach loop in php, so you could do this:
$id = $_GET['id'];
$state= $_GET['state'];
// $_GET['onoffswitch-checkbox'] ?? I don't think you need this...
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I refresh a detail select list when my master select changes using AJAX
I'm just working learning PHP again after some time away and after looking around think I need to use JS/ajax to make this happen which I intend to learn more about after I get more comforable with PHP. I would like to learn how to do this for some thing I am working on now.
I have a table of parent items which I display as a list of links. When a parent item is clicked I want the child items of the clicked parent to be displayed in another list. I can get the 2 lists to display with simple queries I just don't know how to get the page/sql query to update when clicked.
<?php require ('connection.inc.php'); ?>
<div id="lists">
<h3>Lists</h3>
<?php
$lists = mysql_query("SELECT * FROM lists")
or die(mysql_error());
while($info = mysql_fetch_array( $lists ))
{
echo "".$info['ListName']."<br />";
}
?>
</div>
<div id='listitems'>
<h3>List <?php $parent=2; echo $parent?> Items</h3>
<?php
$listitems = mysql_query("SELECT * FROM listitems WHERE parent=$parent")
or die(mysql_error());
while($info = mysql_fetch_array( $listitems ))
{
echo $info['itemName']."<br />";
}
?>
</div>
Code issues aside (mysql_* == mucho deprecato), you need to check if the request is AJAX and output listitems.
I used jquery to simplify the ajax request.
<?php
require ('connection.inc.php');
/* AJAX request */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
$query = sprintf('SELECT * FROM listitems WHERE parent=%d',
mysql_real_escape_string($_REQUEST['parent']));
$listitems = mysql_query($query)
or die(mysql_error());
printf('<h3>List %d Items</h3>', $_REQUEST['parent']);
while($info = mysql_fetch_array( $listitems ))
{
echo $info['itemName']."<br />";
}
exit;
}
/* Normal request */
?>
<div id="lists">
<h3>Lists</h3>
<?php
$lists = mysql_query("SELECT * FROM lists")
or die(mysql_error());
while($info = mysql_fetch_array( $lists ))
{
echo "".$info['ListName']."<br />";
}
?>
</div>
<div id='listitems'>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
jQuery(function($)){
$('#lists').delegate('a', 'click', function(){
$('#listitems').load(window.location.pathname, {parent: $(this).text()});
return false;
});
}
</script>
I would like to submit information to a mySql database using php and ajax.
The page that the info is being sent from (form.php) has multiple forms that are generated from a "while()" loop.
On success, I would a response to update a div above the particular form from which the data was submitted.
I am currently using jQuery and the jquery form plugin.
I have been successful in getting the data to the database, however I am having trouble with the response being sent back to the proper div. I have been successful in getting a response back to a div that is outside of the while() loop. I have not, however, been successful in getting a response back to a div within the loop. I have placed in the code below a div called:
">
Where I would like the note to be placed.
I know that this has everything to do with my javascript function:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() { $('#noteReturn').fadeIn('slow'); }
});
});
</script>
The #noteReturn function does not specify which businesses div it should be placed in.
I hope that this makes sense.
Thank you for your help.
The code is below:
<!-- the form.php page -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/forms.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() {
$('#noteReturn').fadeIn('slow'); }
});
});
</script>
<?php
$query = mysql_query("SELECT * FROM businesses");
while( $row = mysql_fetch_assoc( $query ) ):
$b_id = $row['bid'];
?>
<div class='notes'>
<?php
// query the db for notes associated with business... return notes texts and notes dates
$notesQuery = mysql_query("SELECT business_id, notes, messageDate FROM notes WHERE notes.business_id = $b_id ORDER BY messageDate");
while( $NoteRow = mysql_fetch_assoc( $notesQuery ) ) {
extract($NoteRow);
echo "$notes<br/><span class='noteDate'>$messageDate</span><br />";
} // end while$notesQuery
?>
<!-- this is where i would like jQuery to return the new note -->
<div id="noteReturn<?php echo $b_id; ?>"></div>
<!-- begin note form -->
<form name="noteForm" action="notesProcess.php" method="post">
<input type="text" name="note" />
<input type="hidden" value="<?php echo $b_id ?>" name="bid" />
<input type="submit" class="button" value="Send" />
</form>
</div> <!-- end div.notes -->
<?php
endwhile;
?>
<!-- /////////////////////////////////////////////////////
The page that the form submits to is this (notesProcess.php):
///////////////////////////////////////////////////// -->
<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if( $result ) {
echo " $note"; }
?>
Change this code:
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() {
$('#noteReturn').fadeIn('slow');
}
});
To this:
jQuery('form').ajaxForm({
target: '#noteReturn',
dataType: 'json',
success: function(data) {
$('#noteReturn' + data.id).html(data.note).fadeIn('slow');
}
});
And this code:
<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
echo " $note";
}
?>
To this:
<?php
$note = mysql_real_escape_string($_POST['note']);
$id = mysql_real_escape_string($_POST['bid']);
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
print json_encode(array("id" => $id, "note" => $note));
}
?>
What happened?
The change to the PHP code is making use of PHP's json_encode function to print out the id of the business to which the note was added as well as the actual note text. In the javascript code, I added the dataType of 'json' to tell the script what format of response to expect. Once the request is received in the success callback, the data variable is an object with the values we passed through json_encode. So data.id has the business id and data.note has the new note. Using jQuery's html() manipulation function, the inner html of the div is updated to the latest note. The div selector uses the id we passed, so we can update the corresponding div.
Also, this is slightly off topic, but make sure you always use mysql_real_escape_string when putting values into a query like you are. If you do not use this, your queries will be vulnerable and susceptible to injection attacks, and they are not pretty. If a customer decided to enter a note value of ');DROP TABLE businesses; you'd really feel the pain. Preferably, switch to PDO or MySQLi and use prepared statements, as they are the 'correct' way of doing queries nowadays.