How to increment a value in MySQL database with PHP? - php

I am trying this code, but it isn't working.
The main problem is in these variables or in the script given at the bottom.
<?PHP
$upVote1 = "UPDATE facerate SET votes = votes + 1 WHERE Picture = '".$idOptain1."'";
$upVote2 = "UPDATE facerate SET votes = votes + 1 WHERE Picture = '".$idOptain2."'";
$upIgnore1 = "UPDATE facerate SET ignores = ignores + 1 WHERE Picture = '".$idOptain2."'";
$upIgnore2 = "UPDATE facerate SET ignores = ignores + 1 WHERE Picture = '".$idOptain1."'";
?>
<img onClick='renderData1()' src="<?php echo $img1['Picture'] ?>" />
<img onClick='renderData2()' src="<?php echo $img2['Picture'] ?>" />
<!-- £££££££££££££££ SCRIPT HERE ££££££££££££££ -->
<script>
function renderData1()
{
document.write(<?php mysql_query("$update1, $upIgnore1") or die(mysql_error()); ?>);
};
function renderData2()
{
document.write(<?php mysql_query("$update2, $upIgnore2") or die(mysql_error()); ?>);
};
</script>

mysql_query does not support multiple queries. You will need to break it up into a single query per call.

You should set up some Ajax request to register user votes: This might give you some idea how to do it (using jQuery here):
Javascript function to execute on vote click event :
function upvote_picture(id){
$.ajax({
type: 'POST',
url: 'vote.php',
dataType: 'json',
data: {
picture_id: id
},
success: function (data) {
alert(data);
}
});
}
vote.php file:
<?php
// Any error or warning in this script will break JSON response !
function send_json($array)
{
header('Content-Type: application/json; charset=utf-8');
echo json_encode($array);
exit();
}
// Add query execution status variables and messages here
$response = array();
$id = !empty($_POST['picture_id']) ? $_POST['pciture_id'] : FALSE;
if($id){
// Do you query here
if ( mysql_query(....)) {
$response['success'] = TRUE;
} else {
$response['success'] = FALSE;
}
} else {
$response['success'] = FALSE;
}
send_json($response);
?>

Related

Creating Dynamic Pages with php and MySQL

I am creating a list of links in main.php using "donemler" table in mySQL database and would like to create a page that shows data from "sikkeler" table (which has a foreing key donemID that is used as a relationship between the two tables) as the user clicks it. (data.php is a part of the index.php which is a infinite scroll page)
Here I tried to call $row["donemID"] with GET method using
$k=$_GET['donemID'] in index.php but did not work.
I have also tried to use SESSIONS method where I add "$_SESSION['donemID']=$row$row["donemID"] to main.php
and called it back in index.php as
$k=$_SESSION['donemID']
but it also did not work.
I would like to learn how to create pages and show relevant data in php.
Thanks in advance!
main.php
<?php
require_once "config.php";
$sql = $conn->query("SELECT * FROM donemler ORDER BY donemID");
if ($sql->num_rows > 0) {
// output data of each row
while($row = $sql->fetch_assoc()) {
echo "<tr><td><a href='index.php?devletID=".$row["devletID"]."&donemID=".$row["donemID"]."'>" .$row["donemler"]. "</a></td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
index.php
<script type="text/javascript">
var start = 0;
var limit = 20;
var reachedMax = false;
var dnmID = $_GET("donemID");
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height() )
getData();
});
$(document).ready(function () {
getData();
});
function getData() {
if (reachedMax)
return;
$.ajax({
url: 'data.php',
method: 'POST',
dataType: 'text',
data: {
getData: 1,
start: start,
limit: limit,
dnmID: dnmID,
},
success: function(response) {
if (response == "reachedMax")
reachedMax = true;
else {
start += limit;
$(".results").append(response);
}
}
});
}
</script>
data.php
<?php
if (isset($_POST['getData']) ) {
$conn = new mysqli('localhost', 'usrnm', 'pss', 'db');
$dnmID = $conn->real_escape_string($_POST['dnmID']);
$start = $conn->real_escape_string($_POST['start']);
$limit = $conn->real_escape_string($_POST['limit']);
$sql = $conn->query("SELECT * FROM sikkeler WHERE donemID='$dnmID' ORDER BY kayit_no DESC LIMIT $start, $limit");
if ($sql->num_rows > 0) {
$response = "";
while($data = $sql->fetch_array()) {
$response .= '
<tr>
<td>ICD#'.$data['kayit_no'].'</td>
<td>'.$data['donemi'].'</td>
<td><img src="coin_images/'.$data['resim'].'" border="2" width="200px" /></td>
<td>'.$data['darp'].'</td>
<td>'.$data['tarih'].'</td>
<td>'.$data['birim'].'</td>
<td>'.$data['agirlik'].'</td>
<td>'.$data['cap'].'</td>
<td>'.$data['tip'].'</td>
<td>'.$data['reference'].'</td>
</tr>
';
}
exit($response);
} else
exit('reachedMax');
}
?>
You are checking through two different request methods:
$_POST['getData']
$k=$_GET['donemID']
Since you are using the query strings, it is a GET method to check with.
There is no such variable i.e. getData on main.php

e.preventDefault / return false breaks ajax script firing properly

I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];

AJAX not separating JSON string

I'm using a star ratings system to display rating data from SQL. Each item that can be rated has unique identifyer variable $id and each rating in ratings tabl has unique identifyer $storyidr. I would like this script to display:
the average rating
the number of times the item has been rated.
The values are retirevable but they display on the page together and I can't see how to seperate them. FOr example, for an item that has an average rating of 4 and has been rated 200 times. when user clicks the data returns via AJAX looking like:
For 'response1' 4"200"
For 'response2' 4"200"
I would like to be able to seperate them to look like:
For 'response1' 4
For 'response2' 200
html page
<div id="products" style="">
<div class="rateit" data-storyidr="<?php echo $id; ?>">
</div>
<div class="averagevote">
<div style="display:block;" id="response<?php echo $id; ?>"><?php echo $avgratep; ?></div><br>
<div style="display:block;" id="response2<?php echo $id; ?>">RaTeD <?php echo $rankcount; ?> TiMeS</div>
</div>
</div>
<?php endwhile; mysqli_close($connection); ?>
<script type ="text/javascript">
$('#currentslide .rateit').bind('rated reset', function (e) {
var ri = $(this);
var value = ri.rateit('value');
var storyidr = ri.data('storyidr');
ri.rateit('readonly', true);
$.ajax({
dataType : 'json',
url: 'rate.php',
data: {storyidr: storyidr, value: value},
type: 'POST',
success: function (data) {
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg + '/5');
$('#response2'+storyidr).replaceWith('Rated ' + data.cnt + ' times');
},
error: function (jxhr, msg, err) {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
});
</script>
PHP
<?PHP
$storyidr=$_POST['storyidr'];
$mysqli = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());";
$sql .= "SELECT AVG(rank) AS avrank, COUNT(rank) AS countrank FROM ratings WHERE storyidr = $storyidr";
if($mysqli->multi_query($sql))
{ $mysqli->next_result();
if ($result = $mysqli->store_result())
{
$data = mysqli_fetch_assoc($result);
$avrank = $data['avrank'];
$countrank = $data['countrank'];
$avrankr = round($avrank,2);
if(is_null($avrank)){$avrank ="null";}
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
}
}
?>
You should only use json_encode() once and only echo the result of that function. Doing it more than once invalidates your json:
else
{
$results = array();
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
echo json_encode($results);
}
Then, in your javascript, you can access data.av and data.cnt directly:
$('#response'+storyidr).replaceWith('Avg rating ' + data.av +'/5');
$('#response2'+storyidr).replaceWith(data.cnt);
You could also set the dataType parameter in your ajax call as mentioned by #barell, but normally jQuery will figure that out correctly already.
Edit: To avoid the undefined errors you are getting you should do something like:
$results = array('status' => 'fail');
...
if () {
...
if ($result)
{
$results['status'] = 'success';
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
}
}
echo json_encode($results);
Now you can check for data.status first in the success callback of your ajax call and take the appropriate action:
success: function (data) {
if (data.status === 'fail') {
// show a warning message somewhere, this is just an example
alert('No results found!');
} else {
$('#response'+storyidr).replaceWith('Avg rating ' + data.av + '/5');
$('#response2'+storyidr).replaceWith('RaTeD ' + data.cnt + ' TiMeS');
}
},
I think the problem is you don't set the correct header. In the php file, before any output, put this:
header('Content-type: text/json');
And also, instead of write two objects, write it as an array:
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
Now it should work
Then, in your Javascript you will access this data like this:
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg +'/5');
$('#response'+storyidr).replaceWith(data.cnt); // Suppose you want the count here

AJAX Unique ID div color change per post if user logs in

There are many posts that are made by users, I want each post (or div in this case) to display the background color green or grey depending on the user status (logged in or not).
What I am trying to achieve is while idling on the page, you should see a user going online without refreshing the page
status.php
if (logged_in() === true){
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
echo "online";
}
}
}
}else {
echo "offline";
}
Main page
$res8 = mysql_query("SELECT * FROM `users` WHERE user_id='".$user_id."' LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
?>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
datatype:"application/json",
type: 'GET',
success: function(data) {
if (data === "online") {
$('.status').css({background: '#40A547'});
} else {
$('.status').css({background: '#7f8c8d'});
}
}
});
}, 5000);
});
</script>
<?php
}
}
}
echo '<div class="status">TEST</div></a></div>';
This code changes the background color of all the divs but I want it to only target the divs that correspond to the user that logged in (the creator of the post).
Not sure how to make the div have the dynamic styling using ajax.
Any help is much appreciated!
You can use the id user from the database to achieve this. Then add an id to the div corresponding to the user id. For instance :
Ajax Request in success :
$('.status #user'+ dataId).css({background: '#7f8c8d'});
In your HTML :
echo '<div class="status" id="user1">TEST</div></a></div>';
Edit
Your Main page (your AJAX request)
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.message === "online")
{
$('.status #user'+ data.userId).css({background: '#40A547'});
} else // data.message === "offline"
{
$('.status #user'+ data.userId).css({background: '#7f8c8d'});
}
}
});
//...
// HTML looks like...
echo '<div class="status" id="user1">TEST</div></a></div>';
echo '<div class="status" id="user2">TEST2</div></a></div>';
status.php
You set the dataType of your ajax request that you want return Json but it's unclea, your your status.php add the header content-type to json.
<?php
header('Content-Type: application/json'); // So add this
//...
$array = array(); // New variable which would be return as json
if (logged_in() === true) // Your online part
{
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
$array['message'] = 'online';
$array['userId'] = $row8['user_id']; // Here is the userId (adapt following your code)
}
}
}
}// Your offline part
else {
$array['message'] = 'offline';
}
echo json_encode($array);

how to update PHP variable with Jquery Ajax?

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Categories