Value row and empty row added to MySQL table - php

I'm inputting values into a MySQL database. The values are always being inputted correctly. However, each time a new row enters the table, two rows are being added to the database (one empty row and with a value of either 1 or 2). Any ideas how to stop this empty row being added? Thanks
<div id="post" data-value="1"></div></div>
<div id="post" data-value="2"></div></div>
$('div').click( function(e){
console.log("a")
x= $(e)[0].currentTarget
var data = {"emotion":$(x).context.dataset["value"]}
$.ajax({
type: "POST",
url: "insert.php",
data: data
})
});
insert.php
$number = $_POST["number"];
$sql = "INSERT INTO test(number) VALUES ('$number');";

in your insert.php file check condition
if(isset($_POST["number"]) && $_POST["number"]!='' )
{
$number = $_POST["number"];
$sql = "INSERT INTO test(number) VALUES ('$number');";
}

$('div').click(...
... means you add a click event on any div. Try using
$('div#post').click(...

Related

Loop through a list of div using setInterval to refresh data every x seconds

I have this page that consists of a list of user posts / message. When a post is liked, I want it to reflect on all other users, and based on my research setInterval can get the job done by refreshing a specific content for a number of seconds. Currently, I'm having trouble looping through all the user messages and show the updated number of likes. What's happening is that the number displayed is constantly changing and looping through all the values for a single post. Example: If I have 1, 0, and 2 likes respectively on three different posts, the number for the first post changes to 1, 0, and 2 instead of just showing "1". I'm kind of a beginner when it comes to AJAX.
Here's my code:
Jquery / Ajax
function refreshPostLikes() {
setInterval(function() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
}, 1000);
}
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
PHP Query
<?php
require_once('../connection.php');
$postID = $_POST['postid'];
$likeCountQuery = "select count(*) as total_likes from posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while($likeNumber = mysqli_fetch_assoc($likeQueryResult)) {
$likes = $likeNumber['total_likes'];
if($likes != 0) {
echo $likes;
}
else {
echo '';
}
}
?>
Still not sure this is the best way to go, but the reason your code doesn't work is due to omitting the postid when updating the HTML in the success part of your code.
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
with this command $(".posts .like").html(data); //output number of likes
You are updating all the divs which have these classes specified with the same value.
Set postid as id for the div and change the command to
$("#postid").html(data); //output number of likes
is constantly changing and looping through all the values for a single
post
This happens because there is no reference to the post that needs to be updated. What you are doing now is to cycle through all the elements that have the ".posts .id" classes, therefore the update applies to all the posts and not the single one. You should modify your function to make it update only that post (try passing it a unique id in html)
Where N is the id of your post. (For example postid)
Then update the value using this
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {
postid: postid
}, //send data to php file
success: function(data) {
//$(".posts .like").html(data); //output number of likes
$("#post-"+postid).html(data); // in this way we're get the right post
}
});
}
function refreshPostLikes() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
setTimeout(refreshPostLikes, 1000); //Check every sec if there are update
}
setTimeout(updateChat, 1000); //Start the check
Prevent SQL Injection
Escape is not enough
<?php
require_once ('../connection.php');
$postID = $_POST['postid']; //Escape this value before use inside the query see linked question
// NEVER TRUST USER INPUT
//$likeCountQuery it could be used for perform a SQL Injection NEVER TRUST USER INPUT
//NEVER !!!
$likeCountQuery = "SELECT COUNT(*) AS total_likes FROM posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while ($likeNumber = mysqli_fetch_assoc($likeQueryResult))
{
$likes = $likeNumber['total_likes'];
if ($likes != 0)
{
echo $likes;
}
else
{
echo '';
}
}
?>

Updating Mysql database data using Php and Ajax

I'm trying to set up a button which when clicked adds a fixed number to the database value. The database is called var_stat and consists of id and value. The table has one row so far where id = var and value = 35. If clicked, the button should add 5 to the value making it 40.
I'm not sure what to do here, as all answers I found used a completely different approach and strings instead of integers. So far I have done this:
if (isset($_POST['n'])){
$n = $_POST['n'] ;
$stmt = $con->prepare('UPDATE var_stat SET value = value + $n WHERE id = ? ');
$stmt->bind_param('s', $id);
$id = "var";
$stmt->execute();
$stmt->close();
}
<script src="js/jQuery-3.4.1.js"></script>
<script>
function add(n){
$.ajax({
type: "POST",
url: "update.php",
data: {
'n' : n
},
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
<form>
<input type="button" value="+5" class="btn btn-circle btn-grey col-sm-10" onclick="add(5);">
</form>
If I change $n in the update.php to an integer and run the update.php by itself it works, however I can't seem to get this to run through my html page, so I guess there's something wrong with my javascript code?
Bind the n as well, move the id before the binding statement
if (isset($_POST['n'])){
$n = $_POST['n'] ;
$id = "var";
$stmt = $con->prepare('UPDATE var_stat SET value = value + ? WHERE id = ? ');
$stmt->bind_param('is',$n, $id);
$stmt->execute();
$stmt->close();
}

Inserting jQuery's Sortable list into MySql

I am trying to insert jquery's sortable list values into MySql. I have issues with looping in MySql while inserting.
I have sorted items like this
-------------
Sorted List
-------------
did-1
fid-1
fid-2
fid-3
After this I have used 'serialize' to get these sorted list
$('.sortable').sortable({
connectWith: '.sortable',
tolerance: 'pointer',
update: function (event, ui) {
$('#add_list').click(function(){
var data = $('#drop_list1').sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: 'addnewlist.php',
success: function(data){
}
});
});
}
What i want is - Multiple insertion for every 'did', a 'fid' should be inserted. In my MqSql - '(did-1 , fid-1)(did-1 , fid-2)(did-1 , fid-3)'
I have tried this in my PHP.
foreach($_POST['doc'] as $doc)
{
for($i=0;$i<count($_POST['doc']);$i++)
{
$form=$_POST[$i]['form'];
echo $sql="INSERT INTO addnewdoc(doc_id,form_id) VALUES ($doc,$form)";
$res=parent::_executeQuery($sql);
}
}
If I'm understanding this correctly you want to loop through the docs, and then loop through the forms for each doc. Will this work instead?
foreach($_POST['doc'] as $doc)
{
foreach($_POST['form'] as $form)
{
echo $sql="INSERT INTO addnewdoc(doc_id,form_id) VALUES ($doc,$form)";
$res=parent::_executeQuery($sql);
}
}
That ends up running an insert query for each combination. You would be better off building all of the values into a single query and then executing it one time. For example:
$sql = "INSERT INTO addnewdoc(doc_id,form_id) VALUES ";
$values = Array();
foreach($_POST['doc'] as $doc)
{
foreach($_POST['form'] as $form)
$values[] = "($doc,$form)";
}
$sql .= join(',', $values);
$res=parent::_executeQuery($sql);
That gathers all of the values into an array and then joins each of them into a string separated by commas. You can then run a single insert query to insert all of the values.

How to update mysql database fields in groups (using GROUP BY)

I have a table named youi in my database. All fields in the table already contain values except for the aff and desc fields. See image below.
Now, I have a form in my HTML page (See image below) where I want to update the desc and aff fields according to their camp. I have not yet dealt with this kind of setup before. I've been thinking how to do this for almost a day now but still can't seem to find a perfect solution. Could you give me ideas or solutions on how to achieve this? I'm using PHP and mySQL.
Thanks in advance!
The easiest way i see is using a different UPDATE for each of those lines.
You could do that in a loop in php where you construct your update with the values of aff, desc and campaign for each line.
The sql would be:
UPDATE tableName
SET aff = varAffiliate,
desc = varDescription
WHERE campaign = varCampaign;
The php part i'm not of much help, sorry.
You can use CASE, WHEN and THEN in a loop to make the one query.
This is a statement I created using a simple for loop to update a bunch of captions on a group of photos.
UPDATE Images SET caption = CASE imgID WHEN 389 THEN 'a' WHEN 390 THEN 'sdf' WHEN 391 THEN 'safasasadf' WHEN 392 THEN 'fs' WHEN 393 THEN 'dfdsf' WHEN 394 THEN 'sfdf' END WHERE imgID IN (389,390,391,392,393,394);
Hope that helps
aff = (case when somefield='slkd' then yyy end),
desc = (case when somefield='slkdfdsd' then xxx end)
I finally found a solution to this problem. I used combination of jQuery, AJAX, PHP and mySQL for it to work.
All <select> have the same id. The same for <input> and <label>. Here's a sample of my HTML code:
<select id="youiaff">
<option>1001</option>
<option>1007</option>
<option>1009</option>
<option>1013</option>
<option>1017</option>
<option>1018</option>
<option>1022</option>
</select>
<input id="youidesc" type="text" />
<label id="youicamp"></label>
<button type='button' class='btn btn-success saveyouiid'>Save</button>
What I did next was to create a jQuery code that will get all the values of <select>, <input> & <label> and put each of them in an array. I used their ids as identifiers. Here's the code:
var desc = $("input[id='youidesc']")
.map(function(){return $(this).val();}).get();
var aff = $("select[id='youiaff']")
.map(function(){return $(this).val();}).get();
var camp = $("label[id='youicamp']")
.map(function(){return $(this).text();}).get();
Then, I passed the variables to the PHP script using AJAX:
$.ajax({
type: 'post',
url: 'saveyouiid.php',
data: {
desc:desc,
aff:aff,
camp:camp,
},
success:function(data){
}
});
This codes will be executed upon clicking the save button. So the full jQuery/AJAX for this would be:
$('.saveyouiid').click(function(){
var desc = $("input[id='youidesc']")
.map(function(){return $(this).val();}).get();
var aff = $("select[id='youiaff']")
.map(function(){return $(this).val();}).get();
var camp = $("label[id='youicamp']")
.map(function(){return $(this).text();}).get();
$.ajax({
type: 'post',
url: 'saveyouiid.php',
data: {
desc:desc,
aff:aff,
camp:camp,
},
success:function(data){
}
});
});
The PHP script (saveyouiid.php) will then accept the values sent via AJAX. These values are arrays. What I did next was I combined the arrays to form a multidimensional array. Then, I get the individual values and perform the mySQL query. Here's what the script looks like:
<?php
$con = mysqli_connect("localhost","imu_fryu","frankyouiIMU2013","imu_frankyoui");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$aff = $_POST['aff'];
$desc = $_POST['desc'];
$camp = $_POST['camp'];
$arr = array_map(null, $aff, $desc, $camp);
foreach($arr as $array)
{
$aff = $array[0];
if ($aff == ">> Select Affiliate ID <<"){
$affID = "0";
}else{
$affID = $aff;
}
$desc = $array[1];
$camp = $array[2];
$sql1 = "UPDATE youi SET aff = '$affID', descr = '$desc' WHERE camp = '$camp'";
if (!mysqli_query($con,$sql1)) {
die('Error: ' . mysqli_error($con));
}
}
mysqli_close($con);
?>
I hope this could help someone in the future. :)

jQuery serialize selects and inputs in array how to pick them up in PHP loop

I'm trying to create a function where a user should select an option from a <select> and add a date to the value selected (inside <input type='text'> on the same row). Then when the fields have been inputted send as an array to a PHP file and inserted to a database.
I'm creating the <select>, and <input type='text'> dynamically on the same row in a table.
Selects look something like this: <input type='select' class='add_absence_type'>
Input fields: <input type='text' class='add_absence_date'>
The script I'm working on looks like this at the moment:
$('#save').click(function() {
function serealizeSelects (select)
{
var array = [];
select.each(function(){ array.push($(this).val()) });
return array;
}
function serealizeInputs (input)
{
var array = [];
input.each(function(){ array.push($(this).val()) });
return array;
}
var student_id = $('#student_id').val();
var add_absence_type = serealizeSelects($('.add_absence_type'));
var add_absence_date = serealizeInputs($('.add_absence_date'));
$.post('../updateAbsence.php', {
student_id: student_id,
add_absence_type: add_absence_type,
add_absence_date: add_absence_date
}, function(data) {
location.reload();
});
});
The $_POST data looks like this:
student_id 1
add_absence_date[] 2012-11-13
add_absence_date[] 2012-11-14
add_absence_type[] 1
add_absence_type[] 2
What do I need to do to create a PHP loop that creates mysql_query's like this? See below:
"INSERT INTO my_table (student_id, absence_type_id, absence_date) VALUES ('1', '1', '2012-11-13')"
"INSERT INTO my_table (student_id, absence_type_id, absence_date) VALUES ('1', '2', '2012-11-14')"
Try this way
<?php
$student_id = $_POST['student_id'] ;
$absence_date_arr = $_POST['add_absence_date'] ;
$absence_type = $_POST['add_absence_type'] ;
foreach($absence_date_arr as $key=> $absence_date){
mysql_query("INSERT INTO my_table (student_id, absence_type_id, absence_date) VALUES ('".$student_id."', '".$absence_type[$key]."', '".$absence_date."')");
}
?>

Categories