Checkbox that updates dynamically - php

I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John

Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.

Related

Ajax Setting Session ID Failing Coordination with PHP query

So I am trying to make a discussion board and I have a table of posts being queried in one column of a table on the discussion board page. I then have the buttons of those post set up to a function onclick (where I am passing the post ID and then posting it to set_id.php to set as $_SESSION['name'] = $_REQUEST['name']):
scripts.js:
function getcomments(id){
$("#success_child").empty();
$.post("discussion_topics/set_id.php", {
"name": id}).done($("#success_child").load("discussion_topics/comments.php",
function(responseTxt, statusTxt, xhr){
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
}));
}
The problem is, although the Post ID is being set correctly, the php file being loaded will load the previously set SESSION variable that is the post ID. I have absolutely no idea why.
Basically, the SEssion variable is being set properly, however, when a new post is clicked, it will query in the comments.php the old session ID, then when you click again it will query that last one that didn't show. Basically a delay somehow. But it is not a time delay because I have tried that.
HELP!
comment.php:
<?php
session_start();
echo $_SESSION['name'];
function draw_table(){
/* draw table */
$table = '<table cellpadding="0" cellspacing="0" class="discuss_table">';
//Connect To Database
$hostname="localHost";
$username="removed";
$password="removed";
$dbname="removed";
$usertable="replys";
mysql_connect($hostname,$username, $password) or die ("<html> <script>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script>");
mysql_select_db($dbname);
# Check If Record Exists
$id = $_SESSION['name'];
$query = "SELECT * FROM $usertable WHERE post_id = $id";
$result = mysql_query($query);
if($result)
{
while($row = mysql_fetch_array($result))
{
//build table for post
$date = date("M d Y h:ia e", strtotime($row["date"]));
$table.="<tr>";
$table.= "<p class=\"discussion_title\">";
$table.= "<b>".$row["title"]."</b>"."<br>";
$table.=$row["name"].", ".$date." for topic ".$row["topic"]."<br>";
$table.=$row["content"]."<br>";
$table.="<button class=\"makecomment_buttons\">Reply</button>";
$table.="</p></tr>";
}
}
//end the table
$table.= '</table>';
//all done, return result
return $table;
}
echo draw_table();
echo "<br>";
?>
set_id.php
<?php
session_start();
$_SESSION['name'] = $_REQUEST['name'];
?>

How do I pass a GET parameter to ajax and load the data in a popup?

I have an html page that contains a table with course links. When you hover over a link, the information from the course table in the database should display inside of a bootstrap popup or information box and call on ajax so that the information is loaded asynchronously. I use $(this).attr('href') to pull the contents of the page. However, it pulls the entire contents of the page and I only want the information within the div. Here is the contents of my php script:
<?
// Display table for IT plan
$submitted = isset($_POST['submit']);
// when form is submitted, include the correct schedule
if ($submitted) {
$prog = $_POST['program'];
$qtr = $_POST['quarter'];
$class = $_POST['class'];
// if bas program is selected, modify the sched string
if ($prog == "bas-network" || $prog == "bas-software") {
$sched = $prog. '-' .$qtr. '-' .$class;
//echo $sched;
} else {
$sched = $prog. '-' .$qtr;
}
$path = "schedules/";
include ($path . $sched .'.html');
}
require 'connect.php';
$id = $_GET['courseid'];
//print_r($_GET);
if ($id) {
try {
// Create a new PDO connection object
$dbh = new PDO('mysql:host=localhost;dbname=jim_grcc', $user, $pass);
// Set the error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare('SELECT * FROM course WHERE courseid = :id');
$stmt->execute(array('id' => $id));
// Get array containing all of the result rows
$row = $stmt->fetch();
// Print data if one of the rows were returned
if ($row != null ) {
echo "<div>";
echo "<h3>".$row['coursenum']. ": " .$row['title'] . "</h3>";
echo "<strong>Course number: </strong>" .$row['coursenum'] ."<br><br>";
echo "<strong>Title: </strong>" .$row['title'] ."<br><br>";
echo "<strong>Description: </strong>" .$row['description'] ."<br><br>";
echo "<strong>Credits: </strong>" .$row['credits'] ."<br><br>";
echo "<strong>Prerequisites:</strong> " .$row['prereqs'] ."";
echo '</div>';
} else {
echo "No rows returned";
}
}
catch(PDOException $e)
{
echo 'Error: ' . $e->getMessage();
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("table a").hover(function() {
var href = $(this).attr('href');
$.get(href, function( data ) {
alert(data);
});
});
});
</script>
Here is how the table is set up:
<tr>
<td>IT 114</td>
<td>IT 131</td>
<td>IT 135</td>
<td>IT 190</td>
</tr>
<tr>
<td>IT 141</td>
<td>IT 160</td>
<td>IT 201</td>
<td> </td>
</tr>
I am using GET parameters since the courseid is passed through the link. An example of the query string would be: programs-process.php?courseid=it190. I thought I might be able to pass id as a data parameter in $.get, but the console is showing null or undefined.
Have a separate PHP file that only send those information based on a value you pass to it. You send an identifier variable to the file and let it return the data you need.
The reason why you are getting the whole page is most likely you have HMTL markup in the file you are using.

trying to use combobox populated from mysql to send the $id to a second page to be used in a query

Trying to use ComboBox populated from mysql to send the $id to a second page to be used in a query to populate data.
Here is my code sitting in the bootsrap nav bar on page 1
<form class="navbar-form navbar-left" action='customerpage.php' method='post'>
<div class="form-group">
<select type="submit" id="navbarcustomer" class="form-control" name='customerid' placeholder="Customer Lookup">
<option>Customer Lookup</option>
<?php
require ('dbconnect.php');
$result = $con->query("select id, lastname, firstname from customer");
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$name = $row['lastname'];
$firstname = $row['firstname'];
echo '<option value="/customerpage.php?id='.$id.'">'.$name.','.$firstname.'</option>';
}
echo "</select>";
mysqli_close($con);
?>
</div>
</form>
here is my code on page to that needs to receive the $id variable to be used in the query
<?php
$id = $_GET['custid'];
echo $id;
require ('dbconnect.php');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM customer WHERE id=' . $id . '");
//$result = mysqli_query($con,"SELECT * FROM customer WHERE id=$id");
while($row = mysqli_fetch_array($result)) {
echo $row['firstname'];
echo "<br>";
}
?>
Please help the name of page 2 is /customerpage.php Thank you.
It looks like you've set it up so that when you click the dropdown, it will automatically go to the customers page. We will need just a little bit of JavaScript for that.
Place this below your closing </form> tag, but preferably right before you closing </body> tag document.
<script>
var navbarcustomer = document.getElementById('navbarcustomer');
navbarcustomer.addEventListener('change', function (e) {
window.location = this.value;
});
</script>
If you're using jQuery, you can OPTIONALLY use this in your <script> tags instead of the code above:
$('#navbarcustomer').on('change', function () {
window.location = $(this).val();
});
Next, you need to make sure your GET vars match what you're sending it. Change $_GET variable to look like this, as you are providing id= in the query string (and not custid=):
$id = $_GET['id'];
Edit:
There are a few more things that need to be addressed. Also in the customerpage.php, your query is little broken. You can use something like to fetch your records, it's a little bit cleaner:
$id = (int) $id; // cast to integer to prevent SQL injection.
$result = $con->query("SELECT * FROM customer WHERE id = $id");
// there is only going to be 1 record so we don't need the while loop.
$row = $result->fetch_assoc();
echo $row['firstname'];
echo $row['lastname'];

updating a flag in mysql via radiobutton onclick handler in php

I want to update a column in a table in mysql. Basically the column is the flag for the entries of that db table.
The modification of the column is resetting all values to 0 and setting the desired row to 1, for this reason I have post.php file which looks like
<?php
require_once('class.uuid.php');
$connection = mysql_connect("---logindetailshere---");
$db = mysql_select_db("---dbnamehere---",$connection);
switch($_REQUEST['action']){
case ...
break;
case ...
break;
case 'changeDisp':
changeDisp($_REQUEST['uid']);
break;
}
mysql_close($connection);
...
function changeDisp($uid){
global $connection, $db;
$q_string = "UPDATE Questions SET Displayed = 0";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
$q_string = "UPDATE Questions SET Displayed = 1 WHERE Uid='${uid}'";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
}
?>
on the webpage I display the items and radiobuttons next to the items, the purpose is to select the radiobuttons and post to set the flag 1 for the selected item, for this reason I have a item.php file
<?php
$i = 1;
foreach ($qitem as &$q) {
$options = explode(";", $q["Options"]);
$displayed = '';
if ($q["Displayed"] == 1) { $displayed='checked="yes"'; }
echo("<div class='item' name='".$q["iUid"]."'>");
echo("<div class='count'>".$i.".</div>");
echo ("<div class='radio'><input type='radio' onclick='changeDisp("".$q["Uid"]."")' name='disp' ".$displayed."></div>");
echo("<div class='left'>");
echo("<h4>".$q["Value"]."</h4>");
echo("<div class='details'>Typ: ".$q["Type"]."</div>");
echo("<div class='details'>Skala: ".$options[0]." / ".$options[1]."</div>");
echo("</div>");
echo("</div>");
$i++;
}
?>
here I am using radiobuttons to select the related item, I checked the unique id values using firebug the values are fine, I just want to click on any radiobutton and want to trigger the onclick=changeDisp() function.
I have no idea why the page doesn't reload itself and change the selected flag to 1. Could you please help me to solve this problem?
Thanks in advance.
You cannot use an onclick function to call php function without going there with a javascript, jQuery or ajax call. You could create an ajax script to call the post.php From the item.php page and return the results to you.
Here is an example of creating the function you want. This assumes that $uid is coming from a radio button and not an actual user input. If the user can directly input something you need to use a prepared statment
function changeDisp($uid)
{
$Mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($Mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $Mysqli->connect_errno . ") " . $Mysqli->connect_error;
$Mysqli->close();
}
$query = "UPDATE Questions SET Displayed = 1 WHERE Uid='".$uid."'";
$update = $Mysqli->query($query);
if($update)
{
return true;
}
return false;
}

accessing a set of values through single query in postgres

Im trying to use postgres for the first time.. I want to retrieve the value company name from a the values inside an array named testArray
The ajax request that I wrote is
$(document).ready(function()
{
var testArray=[0001001871, 0001001843, 0001001853];
$.ajax({
type:'GET',
url: 'php/databaseAccess.php',
data: {'CIKs': testArray},
success: function(success)
{
document.write(success);
}
});
});
and the PHP file that Ive used to access db is
<?php
$link = pg_connect("host=hostname dbname=dbNAme user=username password=password");
if(!$link)
{
//echo "Connection cannot be established";
exit;
}
else
{
$cik_array = $_GET['CIKs'];
$safe_ciks = array();
foreach($cik_array as $cik)
{
$safe_ciks[] = pg_escape_string($cik);
}
$in_string = "'" . implode("','", $safe_ciks) . "'";
$result = pg_exec($link, "select company_name from company_names where cik=".$in_string);
if (!$result) {
//echo "<br> Could not successfully run query from DB";
exit;
}
else
{
echo "<br> Query Executed Successfully<br>";
echo pg_result($result, 0);
}
}
?>
This code will only output the company name with cik 0001001807, I want to get the company names of all values inside the array "testArray" through a single query itself.. How is that possible?
The SQL Query should be
SELECT
company_name
FROM
company_names
WHERE
cik= IN('0001001807','0001001843', '0001001853')
This will return all company names with a CIK in that list. The IN parameter accepts a comma separated list of values.
In terms of passing the Array of CIKs, you could change the "data" parameter of the Ajax request to send the CIKs.
data: {'CIKs': testArray},
Which I believe would pass all of the CIKs to databaseAccess.php, and could then be accessed by the following command
$cik_array = $_GET['CIKs'];
//escape the CIKs, to prevent SQL injection
$safe_ciks = array();
foreach($cik_array as $cik)
{
$safe_ciks[] = pg_escape_string($cik);
}
//get the CIKs in a format compatible with the IN function
$in_string = "'" . implode("','", $safe_ciks) . "'";
That would produce $in_string, which could be used with the SQL query above.

Categories