This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
I am developing a Like and Unlike feature, So that a user can Like/Unlike a product.
I am done with everything after following this tutorial https://www.sourcecodester.com/tutorials/php/11588/easy-and-simple-likeunlike-using-ajaxjquery.html
The problem is that it is not storing anything into the database(like table).
And no error was shown. When I click Like, it shows Unlike as it should but thats just it - The likes counter doesn't increase and nothing is stored in database.
index.php
<?php
$bid = $_GET['id'];
$stmt = "SELECT * FROM `like` WHERE postid = :postid AND userid = :userid";
if($querys = $pdo->prepare($stmt)){
$querys->bindValue(':postid', $bid);
$querys->bindValue(':userid', $userid);
$querys->execute();
$check = $querys->rowCount();
}
if($check>0)
{
$like = '<button value="'.$bid.'" class="unlike">Unlike</button>';
}else{
$like = '<button value="'.$bid.'" class="like">Like</button>';
}
$sql = "SELECT count(*) FROM `like` WHERE postid = :postid";
if($query = $pdo->prepare($sql)){
$query->bindValue(':postid', $bid);
$query->execute();
$nlikes = $query->fetchColumn();
//rest of code here
}
echo $like;
<span id="show_like<?php echo $bid; ?>">
<?php echo $nlikes;
?>
javascript/ajax
<script type = "text/javascript">
$(document).ready(function(){
$(document).on('click', '.like', function(){
var id=$(this).val();
var $this = $(this);
$this.toggleClass('like');
if($this.hasClass('like')){
$this.text('Like');
} else {
$this.text('Unlike');
$this.addClass("unlike");
}
$.ajax({
type: "POST",
url: "like.php",
data: {
id: id,
like: 1,
},
success: function(){
showLike(id);
}
});
});
$(document).on('click', '.unlike', function(){
var id=$(this).val();
var $this = $(this);
$this.toggleClass('unlike');
if($this.hasClass('unlike')){
$this.text('Unlike');
} else {
$this.text('Like');
$this.addClass("like");
}
$.ajax({
type: "POST",
url: "like.php",
data: {
id: id,
like: 1,
},
success: function(){
showLike(id);
}
});
});
});
function showLike(id){
$.ajax({
url: 'show_like.php',
type: 'POST',
async: false,
data:{
id: id,
showlike: 1
},
success: function(response){
$('#show_like'+id).html(response);
}
});
}
like.php
<?php
session_start();
ERROR_REPORTING(E_ALL & ~E_NOTICE);
include('php/connect.php');
include('php/function.php');
if (isset($_COOKIE['remember']) && $userid!==null) {
getcookie();
}
if (isset($_POST['like'])){
$id = $_POST['id'];
$sql = "SELECT * FROM `like` WHERE postid = :postid AND userid = :userid";
if($query = $pdo->prepare($sql)){
$query->bindValue(':postid', $id);
$query->bindValue(':userid', $userid);
$query->execute();
$nlikes = $query->rowCount();
}
if($nlikes>0) {
$stmt2 = $pdo->prepare("DELETE FROM like WHERE userid=:userid AND postid=:bid");
$stmt2->bindValue(':userid', $userid);
$stmt2->bindValue(':bid', $id);
$stmt2->execute();
} else{
$stmt3 = $pdo->prepare("INSERT INTO like (userid,postid) VALUES (:userid, :postid)");
$stmt3->bindValue(':userid', $userid);
$stmt3->bindValue(':postid', $id);
$stmt3->execute();
}
}
?>
show_like.php
<?php
session_start();
ERROR_REPORTING(E_ALL & ~E_NOTICE);
include('php/connect.php');
include('php/function.php');
if (isset($_POST['showlike'])){
$id = $_POST['id'];
$sql = "SELECT count(*) FROM `like` WHERE postid = :postid";
if($query = $pdo->prepare($sql)){
$query->bindValue(':postid', $id);
$query->execute();
$nlikes = $query->fetchColumn();
echo $nlikes;
}
}
?>
Fixed by merely changing the name of the database table from like to likes
as like is a mysql reserved word.
Related
I have a small script that runs a php file in the background and gets a variable every 3 seconds and put it in a div
script in document with div
<script>
$(document).ready(function() {
setInterval(function () {
$('#statmoney').load('safe.php');
}, 3000);
});
</script>
PHP FILE (safe.php)
$sql = "SELECT * FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$money = htmlspecialchars($row->money);
echo $money;
If i need to add another variable i would need to make a new document is there a easy way to go about it?
UPDATE
menu.php
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['money', 'ore', 'energy']; // array of needed fields
$.ajax({
type: "POST",
url: "menusafe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
console.log(response)
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
<div class="menustats"><img src="graphics/logos/moneylogo.png" class="menustatimage"><div class="menustattext" id='money'></div></div>
<div class="menustats"><img src="graphics/logos/energylogo.png" class="menustatimage"><div class="menustattext" id="energy"></div></div>
<div class="menustats"><img src="graphics/logos/orelogo.png" class="menustatimage"><div class="menustattext" id='ore'></div></div>
PHP(menusafe.php)
<?php
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
?>
Let's imagine that we want to retrieve three fields from users table : firstname, age and money. In such case it would be better to use $.post or $.ajax method:
js part:
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['firstname', 'age', 'money']; // array of needed fields
$.ajax({
type: "POST",
url: "safe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
php part: (safe.php)
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
I have a JQuery on click that sends a php query to MySql and then I want to send the data back 1 by 1 on JQuery.
But I only know how to send back results from php to JQuery as a whole.
my current JQuery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
alert(data);
}
});
});
});
my current php:
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['UserID'];;
echo $row['EmailAddr'];
}
?>
the outputs are both UserID and EmailAddr, I don't know how to just display either the UserID or EmailAddr out only
I tried alert(data[0]), but it only displayed one letter of the result.. Any ideas on how to do this?
UPDATE: After sean's help i have the current updated code
Jquery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
PHP
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>
In your php, save the results to an array -
<?php
include 'dbAuthen.php';
$array = array(); // create a blank array
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// add each result to the array
$array[] = array('UserID'=> $row['UserID'], 'EmailAddr'=> $row['EmailAddr']);
}
echo json_encode($array); // json_encode() the array
?>
Then in your js/ajax you can loop through each value
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
// loop through each returned value
$.each(data, function(){
//alert each result, this is just an example as alert() for each result is not a great idea
alert("UserID:"+ this.UserID + " EmailAddr:" + this.EmailAddr);
});
}
});
});
});
jquery
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
php
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>
Using a few answers on here I have got row being added to MySQL upon a button press but the data is blank and so I can only assume the variables are not being passed.
I really don't know what I am doing wrong, any help would be greatly appreciated.
PHP
<? $sql = "SELECT itemname FROM items ORDER BY itemname ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<button onclick='javascript:ajaxCall(" . $row['id'] . ")'><span class='btn-text'>" . $row['itemname'] . "</span></button>";
}
?>
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function ajaxCall(id){
$.ajax({
type: "POST",
url: "additem.php",
success: function(data){
// callback function
}
});
return false;
}
</script>
additem.php
// Connect database.
include("settings.php");
mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name);
$id = $_POST['id'];
$itemsearch = mysql_query("SELECT itemname, itemcategory, price, qty FROM presales WHERE id='$id'");
$itemsearchrest = mysql_num_rows($itemsearch);
$itemname = $itemsearchrest['itemname'];
$itemcategory = $itemsearchrest['itemcategory'];
$price = $itemsearchrest['price'];
$qty = $itemsearchrest['qty'];
$sql = "INSERT INTO presales (itemname, itemcategory, price, qty) VALUES('$itemname', '$itemcategory', '$price', '0')";
if(mysql_query($sql)){
return "success!";
}
else {
return "failed!";
}
?>
mysql_num_rows returns the number of rows. It's not an array. Use fetch_assoc or similiar.
See sample in the PHP documentation!
Also your AJAX call is missing the data:
$.ajax({
type: "POST",
url: "additem.php",
data: {
id: id
}
});
Please switch to PDO or MySQLi. MySQLi will use the same function names but it is object orientated. PDO will name the functions slightly different but basically work the same way.
I'm trying to create upvote/downvote buttons on a list of articles that I get from a MySql database. The buttons work in the sense that you press on the button and it gets the id of the article. However I can't get the id from article page to the php voting page. When I press the button the database doesn't register the vote. What am I doing wrong?
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
alert('you upvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
else
{
alert('you downvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
return false;
});
});
</script>
This is the php file:
<?php
$pid = $_POST['id'];
try {
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result=mysql_query("SELECT * FROM database WHERE pid = '$pid' ") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
// temp user array
$lecturelist = array();
$lecturelist["pid"] = $row["pid"];
$lecturelist["upvote"] = $row["upvote"];
$lecturelist["downvote"] = $row["downvote"];
$lecturelist["vote"] = $row["vote"];
}
$upvote= $row["upvote"];
$downvote = $row["downvote"];
$vote = $row["vote"];
$upvote = $upvote + 1;
$query = $db->prepare('UPDATE database SET upvote = :upvote WHERE pid = :pid');
$query->execute(array(
':upvote' => $upvote,
':pid' => $pid
));
$query = $db->prepare('UPDATE database SET vote=:vote WHERE pid = :pid');
$query->execute(array(
':vote' => $vote,
':pid' => $pid
));
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
data: {id: id}
this will get to your php file a "id" variable ( this is the first id ) and with some value ( from the second id )
now
$pid = $_POST['id'];
this should work, as you weren't sending "much" to the server
my database table
course subject is my table name
course subject
-----------------
bsc1 s1
bsc1 s2
bsc2 s3
if i select bsc1 it need to display only subject (s1,s2),if i select bsc2 it need to display only subject (s3) i.e it should corresponding values from MySQL database,please any one help me to rectify this problem. i tried i con't able to rectify.
In controller:
function studentupdate()
{
$data = array();
$exam_name = $this->input->post('exam_name');
$course_name = $this->input->post('course_name');
if($query = $this->student_model->get_exam_data())
{
$data['exam_data'] = $query;
}
if($query = $this->student_model->get_records($exam_name))
{
$data['records'] = $query;
}
if($query = $this->student_model->get_course_code_records($exam_name))
{
$data['course_records'] = $query;
}
if($query = $this->student_model->get_all_coursesubject_records($course_name))
{
$data['all_coursesubject_records'] = $query;
}
$this->load->view('student_detail_view', $data);
}
In model:
function get_all_coursesubject_records($course_name)
{
$this->db->distinct();
$this->db->select('subject_code');
$this->db->where('course_code',$course_name);
$query = $this->db->get('coursesubject');
return $query->result();
}
In view:
function get_subjectdetailsforupdate(index){
alert ("enter first inside");
var course_name = jQuery('#course_code_id'+index).val();
alert("course_name"+course_name);
var exam_name = jQuery('#exam_name_id').val();
alert("course_name"+course_name);
var ssubject_code = jQuery('#subject_code_id'+index).val();
alert("course_name"+course_name);
jQuery.ajax({
data: 'exam_name='+exam_name+'&course_name=' + course_name,
type: 'POST',
url: 'student_site/subjectfilter',
success: function(data){
console.log(data);
jQuery('#subject_code_id'+index).empty().append(data);
}
});
}
<?php
$js = 'class="dropdown_class" id="course_code_id'.$row->id.'" onChange="get_subjectdetailsforupdate()" ';
$js_name = 'course_code_id'.$row->id;
echo form_dropdown($js_name, $data, $row->course_code, $js);
?>
</td>
<td>
<?php
$js = 'class="dropdown_class" id="subject_code_id'.$row->id.'"';
$js_name = 'subject_code_id'.$row->id;
echo form_dropdown($js_name, $subject_data, $row->subject_code, $js);
?>