cant fillter characters in jcombo - javascript

Can someone help me with this? My sql code only works if I match only integers like 2=2 but if I change it to like this orange=orange it wont work...can anyone help me figure whats wrong with my code.
index.php:
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<form>
Caraga Region: <select name="region" id="region"></select>
Municipalities: <select name="town" id="town"></select>
Unique ID: <select name="uniq_id" id="uniq_id"></select> <br />
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#region").jCombo({ url: "getRegion.php" } );
$("#town").jCombo({ url: "getTown.php?townid=", parent: "#region", selected_value : '510' } );
$("#uniq_id").jCombo({ url: "getID.php?unqid=", parent: "#town", data: String, selected_value : '150' } );
});
</script>
getRegion.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Execute Query in the right order
//(value,text)
$query = "SELECT id, municipalities FROM regions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getTown.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$townid = !empty($_GET['townid'])
?intval($_GET['townid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT town FROM towns WHERE tcode = $townid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['town'], "value" => htmlentities($row['town']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
getID.php: The problem is in this code. It wont work if I match character to character it only works if its integer=integer.
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT uid, unq_pos_id FROM tb_uniqid WHERE tb_uniqid.uid = '$unqid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['uid'], "value" => htmlentities($row['unq_pos_id']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
(uid)field is stored with character values just like in the (town)field. I want to match it but it won't work.

Try to in getID.php replace:
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
with:
$unqid = !empty($_GET['unqid'])
?$_GET['unqid']:0;
if you want to be able to match strings as well as integers. You see, intval() returns only the integer value of the variable, thus you strip of the other characters when you send a string to that page, and therefore you can't match anything with the code you had before.

Related

How to store MySQL date in Javascript array?

I have searched over the Internet, there is a lot of way to store MySQL records into Javascript array though PHP, like this one. However I can't really store the date record in Javascript.
Let say,
My MySQL date record rows in column called holiday_date: 2017-06-25, 2017-06-26, 2017-06-27.
How can I store in Javascript after I converted them into json by
<?php
$sql = "SELECT public_holiday.holiday_date
FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
$json_array = json_encode($result_array);
echo $json_array;
?>
?
I have tried to store them into a javascript date array like
var holidays = [<?php //sample array for example
$loop_one = true;
foreach ($result_array as $date)
{
if ($loop_one)
{
echo "'new Date(\'$date\')'";
$loop_one=false;
}
else
{
echo ", 'new Date(\'$date\')'";
}
}
?>];
but all of these are invalid.
I need your help, much appreciated.
To get a javaScript date object array you need to change your script code only no need to change the PHP code.
You can use JSON.parse and forEach loop.
Try like this
<script>
var holidays = '<?php echo $json_array;?>';
holidays=JSON.parse(holidays);
var holidayArray=[];
holidays.forEach(function (key) {
holidayArray.push(new Date(key));
});
console.log(holidays);
console.log(holidayArray);
</script>
It will produce an out put as
I thing it will help you.
So in your sample, the $result_array variable will be a PHP array like:
$result_array = ['2017-06-25', '2017-06-26', '2017-06-27'];
You do not really need to convert this to JSON before passing it to your Javascript. Instead, you could print those string values directly into your Javascript to instantiate the date object, i.e.
<?php
$sql = "SELECT holiday_date FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['holiday_date']; # Return the actual date value and not an array
}
?>
Javascript Part:
var holidays = [<?php
$firstLoop = true;
foreach ($result_array as $date_result) {
# Here you could format your $date_result variable as a specific datetime format if needed to make it compatible with Javascripts Date class.
if ($firstLoop) {
$firstLoop = false;
echo "new Date('$date_result')";
} else {
echo ", new Date('$date_result')";
}
}
?>];
In this example, I'm constructing a javascript array of new Date($phpDateTime) objects.
Your while loop should be like this and push the date into new array
<?php
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['public_holiday.holiday_dat'];
}
//$result_array contains date like this $result_array = ['2017-06-26', '2017-06-27'];
?>
Javascript example
<script>
var holidays = [<?php $result_array = ['2017-06-26', '2017-06-27']; //sample array for example
$loop_one = true;
foreach ($result_array as $date) {
if ($loop_one) {
echo "'new Date(\'$date\')'";
$loop_one=false;
} else {
echo ", 'new Date(\'$date\')'";
}
}
?>];
console.log(holidays);
</script>
Update 1: Finally your code should be like this
<?php
$sql = "SELECT public_holiday.holiday_date FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['public_holiday.holiday_dat'];
}
?>
<script>
var holidays = [<?php
$loop_one = true;
foreach ($result_array as $date) {
if ($loop_one) {
echo "'new Date(\'$date\')'";
$loop_one=false;
} else {
echo ", 'new Date(\'$date\')'";
}
}
?>];
console.log(holidays);
</script>

How to remove multiple rows from mysql table, using an array of IDs in PHP

I'm having trouble using an array to make an sql query delete multiple rows of data at once. Please ignore that I'm using sql injection for now.
EDIT: A somewhat better explanation - my php does not work at all. I have edited it somewhat, after checking the link Sebastian provided in the comments
NOTE: I'm using AngularJS to post
This is my $data structure, from my controller.js function. devicesToDelete is just a simple array, e.g. ["1", "2", "3"]:
$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete })
.success(function(data) {
$scope.results = data;
devicesToDelete = [];
})
.error(function(err) {
$log.error(err);
})
This is the updated php code im having trouble with. On clicking my deleteMultiple button, only the confirm alert fires, the selected items aren't deleted and the console is clear of errors:
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$sql = "DELETE FROM devices WHERE devID in ( implode(",", $data) )";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if($qry->num_rows > 0){
while($row = $qry->fetch_object()){
$data[] = $row;
}
}else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
EDIT 2: I managed to solve the issue on my own. Here is the solution:
I used .join() on my array on the javascript side to have all of the IDs for deletion be separated by commas (e.g. 1, 2, 3):
$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete.join(", ") })
.success(function(data) {
$scope.results = data;
devicesToDelete = [];
})
.error(function(err) {
$log.error(err);
})
Then I just added what I completely glanced over in my php code which is the name of the array i was passing into it - devicesToDeleteArray
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$sql = "DELETE FROM devices WHERE devID in ($data->devicesToDeleteArray)";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if($qry->num_rows > 0){
while($row = $qry->fetch_object()){
$data[] = $row;
}
}else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
here is php code:
<?php
$ids = $_POST['devicesToDeleteArray'];
if(!is_array($data)) {
$ids = json_decode($data, true);
}
if(!empty($ids)) {
include 'config.php';
$sql = "DELETE FROM devices WHERE devID in (implode(",", $ids))";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_object()) {
$data[] = $row;
}
} else {
$data[] = null;
}
$conn->close();
echo json_encode($data);

Why isn't my ajax code updating my second dropdown?

I have no idea why my code isn't working. I basically have two dropdowns, the first is populated from an mssql database and I want the second dropdown to update dependant on the selection in the first.
Below is my code which populates a dropdown box:
<?php
session_start();
$serverName = "REDACTED";
$connectionInfo = array( "Database"=>"REDACTED", "UID"=>"REDACTED", "PWD"=>"REDACTED");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if (!isset($_SESSION['nID']))
{
header("Location: Login.php");
die();
}
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['region']."</option>";
}
return $output;
}
?>
I then use this to populate the first dropdown:
<p>Select a Region
<select name ="region" id ="region">
<option value ="">Select Region</option>
<?php echo loadRegion(); ?>
</select></p>
For the second dropdown box I have the following:
<p>Select a Territory
<select name="territory" id="territory">
<option value="">Select Territory</option>
</select></p>
I call my ajax via:
<script>
$(document).ready(function(){
alert("ready");
$('#region').change(function(){
var region_id = $(this).val();
$.ajax({
url:"getter.php",
method:"POST",
data:{regionId:region_id},
dataType:"text",
success:function(data){
$('#territory').html(data);
}
});
});
});
</script>
My getter page reads as follows:
<?php
session_start();
include 'config.php';
$output = '';
$sql = "SELECT distinct id,territory,rid FROM territoriesHaiss where RID = '".$_POST["regionId"]."' order by id";
$result = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$output = '<option value ="">Select Territory</option>';
while($row = sqlsrv_fetch_array($result))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['territory']."</option>";
}
echo $output;
?>
As pointed out by the 2 comments above (thanks again for the help!) the error was in the code that populates the first dropdown. It should have been a lowercase 'ID', like follows:
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['id'])."\">".$row['region']."</option>";
}
return $output;
}
?>

I am populating a text box with data from a select, it works, but

My select consists of two fields and the text field only picks up one of them. Here is my code:
<script>
function ProdValue(data) {
document.getElementById("ProdName").value = data.value;
}
</script>
<select name="ProdName" id="ProdName" onchange ="ProdValue(this)">
<?php
$sql = "Select * from tblProduct";
if ($result = mysqli_query($conn, $sql));
while ($row = mysqli_fetch_assoc($result))
{
echo "<option value='". $row['Brand']."', '".$row['ProductName']."'>".$row['Brand']." ".$row['ProductName']. '</option>';
}
?>
</select>
How can I get ProductName too?
Since your option value contains brand and productname separated by comma, you could do:
function ProdValue(data) {
var optval = data,
prod_name = optval.split(",")[1];
console.log( prod_name ); //here is your product name
document.getElementById("ProdName").value = optval;
}
use this instead. If both columns are actually defined as NOT NULL, CONCAT() will be quite enough:
<?php
$sql = "Select CONCAT(Brand, ProductName) as CombineColumn from tblProduct";
if ($result = mysqli_query($conn, $sql))
{
while ($row = mysqli_fetch_assoc($result))
{
echo "<option value='". $row['CombineColumn']."'>".$row['CombineColumn']."</option>";
}
}
?>

Why is this jQuery autocomplete not working?

I have the following in my page header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/autoSuggest.js"></script>
<script type="text/javascript" src="javascript/suggest.js"></script>
suggest.js is made of:
$(function(){
$("#idName input").autoSuggest("../Test.php", {minChars: 2, matchCase: true});
});
and autoSuggest.js is a plugin by Drew Wilson (http://code.drewwilson.com/entry/autosuggest-jquery-plugin)
Test.php is
<?php
include('database_info.inc');
$input = $_POST["idName"];
$data = array();
var_dump($data);
// query database to see which entries match the input
$query = mysql_query("SELECT * FROM test WHERE title LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['title'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
My var_dump() doesn't do anything and no items are suggested ...what could I be doing wrong? seems like there's no communication with Test.php
A quick look at the plug-in suggests it expects a parameter called q passed as a GET string, not as a POST.
<?
$input = $_GET["q"];
$data = array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>

Categories