How to update only one field on a table with specific id - php

I have a table with multiple fields and i want to update only one when same ID.The code that im using to update is next
<?php
require('db.php');
mysql_query("SET NAMES 'utf8'");
date_default_timezone_set('UTC');
include("auth.php"); //include auth.php file on all secure pages
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
$id=$_REQUEST['id'];
$query = "SELECT * from base where `id`='$id'";
$result = mysql_query($query) or die ( mysql_error());
$row = mysql_fetch_assoc($result);
$scantime = date("Y-m-d H:i:s");
$trn_date = date("Y-m-d H:i:s");
$id=$_REQUEST['id'];
$surname =$_REQUEST['surname'];
$name= $_REQUEST['name'];
$company_name=$_REQUEST['company_name'];
$firm= $_REQUEST['firm'];
$visitors= $_REQUEST['visitors'];
$barcode= $_REQUEST['barcode'];
$submittedby = $_SESSION["username"];
$update="update base set `scantime`='$scantime' where `id`='$id'";
mysql_query($update) or die(mysql_error());
}
?>
To search data i using ajax autocomplete function
require_once 'config.php';
mysql_query("SET NAMES 'utf8'");
if($_POST['type'] == 'country_table'){
$row_num = $_POST['row_num'];
$surname = $_POST['name_startsWith'];
$query = "SELECT custId,id,name, surname, company_name, firm,barcode,trn_date,scantime FROM base where UPPER(surname) LIKE '".strtoupper($surname)."%'";
$result = mysqli_query($con, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['barcode'].'|'.$row['surname'].'|'.$row['name'].'|'.$row['company_name'].'|'.$row['firm'].'|'.$row['trn_date'].'|'.$row['scantime'].'|'.$row['id'].'|'.$row['custId'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
And to fill data to input fields
$('#barcodescanr').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'barcodescanr',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#name_1').val(names[2]);
$('#company_name_1').val(names[3]);
$('#surname_1').val(names[1]);
$('#firm_1').val(names[4]);
$('#info').val(names[5]);
$('#scanbartime').val(names[6]);
$('#Id').val(names[7]);
$('#custId').val(names[8]);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
The problem that i have is that when i press submit to form it doesnt update scantime .
Thank you

Related

How can I call PHP from dayClick?

I need to save a date in my database through fullcalendar dayclick function, because I'm working with days and not with events.
I have my marcarsenhas.php where I display the calendar and my insert.php where I program the Insert.
I have a Select example that is working so I will provide you everything.
marcarsenhas.php (Where I display the calendar / Showing only the script)
<script>
$(document).ready(function() {
var day;
var iduser = $("#iduser").attr("valor");
//alert($("#iduser").attr("valor"));
//funcionar
$('#calendar').fullCalendar({
selectable: true,
editable: false,
events: {
url: 'getdados.php',
data: {iduser : iduser},
//data: {d : dia, m : mes, a: ano, id : iduser},
success: function(){
// alert("ok");
/*var data_array = $.parseJSON(data);
$("#response").empty().append( data );
$("#id_oc").empty().append( data_array['idoc'] );
$("#design").empty().append( data_array['design'] );
$("#qtd").empty().append( data_array['qtd'] );
//$("#box_detail").html(data_array["design"]);*/
}
},
dayClick: function(date, jsEvent, view) {
//alert(date.format());
var d = new Date(date._d);
var dia = d.getDate();
var mes = d.getMonth()+1;
var ano = d.getFullYear();
day=$(this).closest('.'+(view.type=='month'?'fc-row':'fc-time-grid')).find('.fc-bg td:eq('+$(this).closest('td').index()+')').data('date');
// if (checkDay.dia() == 6 || checkDay.dia() == 0) alert('Weekend!');
console.log(day);
//alert(day);
$(this).css('background-color', 'green');
$.ajax({
type: 'POST',
url: 'insert.php',
data: {dia : dia, mes : mes, ano : ano, iduser : iduser},
success: function(data){
alert(data);
}
});
}, //end dayclick
});
});
insert.php
<?php
include('connection.php');
$dia = mysqli_real_escape_string($conn, $_POST['dia']);
$mes = mysqli_real_escape_string($conn, $_POST['mes']);
$ano = mysqli_real_escape_string($conn, $_POST['ano']);
$iduser = mysqli_real_escape_string($conn, $_POST['iduser']);
if(empty($_POST['dia']) || empty($_POST['mes']) || empty($_POST['ano']) || empty($_POST['iduser'])){
echo"<script language='javascript' type='text/javascript'>alert('Erro!');</script>";
exit();
}
if(isset($_POST['dayClick'])) { // I know that this doesn't work, it's only to guide you
if(!empty($_POST['dia']) || !empty($_POST['mes']) || !empty($_POST['ano']) || !empty($_POST['iduser'])){
$query = "INSERT INTO `t_marcacoes` (dia, mes, ano, iduser) VALUES ('$dia','$mes','$ano','$iduser')";
$successok = mysqli_query($conn, $query);
}
}
header('Location:marcarsenhas.php');
?>
getdados.php (The php file where I do the Select)
<?php
//echo "entrei";
require_once('connection.php');
$dados = array();
$_POST["iduser"] = 5;
if(isset($_POST["iduser"]) ){
$iduser = $_POST["iduser"];
$query = "SELECT id, iduser, dia, mes, ano, ismarcado FROM t_marcacoes WHERE iduser = ".$iduser;
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)){
$dia=$row['dia'];
$mes=$row['mes'];
$ano=$row['ano'];
$date = date('Y-m-d', strtotime($ano.'-'.$mes.'-'.$dia));
$temp = array(
'start' => $date,
'end' => $date,
'overlap' => true,
'rendering' => 'background',
'color' => '#15a515',
'editable' => false
);
array_push($dados, $temp);
}
}
echo json_encode($dados);
?>

Bootstrap Graph not rendered while using a dynamic query

The graph executes correctly when i use a static query. But when i use a dynamic query it doesnt render even when the query returned is same to the static query.
//$sql = "SELECT `". $_GET["field2"] ."`, COUNT(*) as defectCount FROM `defects` GROUP BY `". $_GET["field2"] ."`";
$sql = "SELECT `user_13`, COUNT(*) as defectCount FROM `defects` GROUP BY `user_13`";
Here the commented code doesnot works but the other one works though they throw the same query when i checked on my console.
//code in pie.php
$("#submitgraph").click(function()
{
var graph_type=$("#graph_type").val();
var field_one=$("#field_type1").val();
var field_two=$("#field_type2").val();
$.ajax({
url: "http://localhost/ac/data/data.php?field1="+field_one+"&field2="+field_two,
type: "GET",
async: true,
success: function(response){
console.log(response);
setTimeout(function(){
if(graph_type=="piechart")
{
document.getElementById("pie_draw").style.display = "block";
}
}, 1000);
}
});
});
////code in data.php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `". $_GET["field2"] ."`, COUNT(*) as defectCount FROM `defects` GROUP BY `". $_GET["field2"] ."`";
//the commented code works
//$sql = "SELECT `user_13`, COUNT(*) as defectCount FROM `defects` GROUP BY `user_13`";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$conn->close();
echo json_encode($data);
?>
//code in data_a.js
//Flot Pie Chart
$(function() {
//var data ;
$.ajax({
url : "data/data.php",
type : "GET",
dataType: 'json',
success : function(data){
var datas = [];
for(i=0;i<data.length;i++) {
var obj = {
label : data[i].user_13,
data : data[i].defectCount
};
datas.push(obj);
}
var plotObj = $.plot($("#flot-pie-chart"), datas, {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
});
}
});
});
I Think one of the problem is that your ajax request type is
type : "POST"
in code in pie.php
but in your data.php your request type become GET
Try to change the
$_GET["field2"]
to
$_POST["field2"]
let me know if it works.

why jquery-ui autocomplete list does not show on large list

On smaller list of options the autocomplete drop down list does show on focus. but if the options are more than a specific number (50 to be exact) it no longer shows.
How to make it show no matter what the number of options in the list ?
$(document).ready(function() {
var sst;
//auto complete for artist
$('#artist').autocomplete({
source: 'artists.php',
minLength: 0,
select: function(a, b) {
sst = b.item.value;
}
}).focus(function() {
$(this).data("uiAutocomplete").search($(this).val());
});
//auto complete for title
$('#title').autocomplete({
source: function(request, response) {
$.ajax({
url: "titles.php",
dataType: "json",
data: {
q1: sst,
q2: request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 0
}).on('focus', function(event) {
$(this).autocomplete("search", "");
});
});
the mysql query :
<?php
$db = mysql_connect('localhost','root','1313');
if(!$db){
die( "connection failed ");
}
$db_s = mysql_select_db("LYRICSFINDER",$db);
$data = array();
$searchTerm1 = trim(strip_tags($_GET["q1"]));
$searchTerm1 = addslashes($searchTerm1);
$searchTerm2 = trim(strip_tags($_GET["q2"]));
$searchTerm2 = addslashes($searchTerm2);
$query = "SELECT TITLE FROM DATA WHERE ARTIST LIKE '%".$searchTerm1."%' AND TITLE LIKE '%".$searchTerm2."%' ORDER BY TITLE ASC";
$result = mysql_query($query,$db);
$i=0;
while($row = mysql_fetch_assoc($result) ){
$data[] = $row['TITLE'];
$i++;
if($i>50)break;
}
mysql_close($db);
echo json_encode($data);
?>

$_SESSION variable not setting in AJAX call

I wrote this call for user authentication:
$( '.sign-in' ).click( function(e) {
e.preventDefault();
var logincall = $.ajax({
type: "POST",
url: "../snippets/auth.php",
data: { username: $('#id_email').val(), password: $('#id_password').val() }
});
logincall.done(function( result ) {
alert( 'finished: ' + result );
if( result == 'valid' ) {
location.reload();
} else {
$( '.warning' ).toggleClass('hidden');
}
});
logincall.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
and here's the auth.php function
if( isset($_POST['username']) && isset($_POST['password']) ) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$query = "SELECT COUNT(*) FROM member WHERE username='$username' AND password='$password';";
$result = $mysqli->query($query);
$result = $result->fetch_array(MYSQLI_ASSOC);
if( $result['COUNT(*)'] !== 0 ) {
$_SESSION['logged'] = true; //this sets
$query = "SELECT id, level FROM member WHERE username='$username' AND password='$password';";
$result = $mysqli->query($query);
$result = $result->fetch_array(MYSQLI_ASSOC);
$_SESSION['uid'] = $result['id']; //this DOES NOT set
$_SESSION['lvl'] = $result['level']; //this DOES NOT set
echo json_encode('valid');
} else {
echo json_encode('invalid');
}
}
The odd thing is, if I navigate directly to
myurl.com/snippets/auth.php?username=myusername&password=mypassword
it DOES set the other two session variables, but I can never get index.php to pick them up.
I even added that refresh line to it to ensure it could pick them up, and it gets $_SESSION['logged'] just fine, but not ['uid'] or ['level']

How to Retrieve Values Resulting From AJAX Live Search?

Below is a jQuery function that retrieves 2 textbox values and posts them to another file ("Student Search Results.php"), where a live search is run using the values.
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = Team_Name + '?????' + Teacher;
$.ajax({
type: "POST",
url: "Student Search Results.php",
data: {
query: Search_Data
},
cache: false,
success: function() {
alert('The values were sent');
}
});
});
</script>
Below is the PHP script on the search page ("Student Search Results.php") that makes use of these values.
<?php
include "Connection.php";
if(isset($_POST['query'])){
$searchData = explode('?????', $_POST['query']);
$teamName = $searchData[0];
$teacher = $searchData[1];
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
echo $query;
?>
How would I be able to take variables from the PHP script (such as $result) to the first page, so I can create a result table? Simply including the PHP file does not work, as the file is only included once.
Thank you for your time.
Best option is to serialize to JSON using json_encode
I think best you can do is,
success: function(result) {
alert(result);
}
and Student Search Results.php print result in tabular format.
P.S. : Please follow proper file naming convention
use a proper URL, and send the data (and stop using camelcase for everything) :
$(".search").on('keyup', function() {
var data = {
team_name : $('#TeamName').val(),
teacher : $('#Teacher').val()
}
$.ajax({
type: "POST",
url: "student_search_results.php",
data: data,
cache: false
}).done(function(result) {
console.log(result);
});
});
And in PHP, you have to actually get the result into an array and json_encode it :
<?php
include "Connection.php";
$team_name = !empty( $_POST['team_name'] ) ? $_POST['team_name'] : null;
$teacher = !empty( $_POST['teacher'] ) ? $_POST['teacher'] : null;
if ($team_name && $teacher) {
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );
?>
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = "Team_Name="+'Team_Name'&Teacher='+Teacher;
$.ajax({
type: "POST",
url: "Student_Search_Results.php",
data: Search_Data,
cache: false,
success: function(result) {
$('$output').html(result);
}
});
});
</script>
Here is output div
<div id="output"></div>
On Student_Search_Results.php page get
$tname = $_POST['Team_Name'];
$teacher = $_POST['Teacher'];
//your search query & print data

Categories