I'm working to try and establish a "safe" dynamic form using php/jquery. I am trying to figure out how to encode a query result in the URL, but also being able to display the query correctly in the browser. Ive tried wrapping a urlencode around the data in each of the for loops but it outputs the encoded data and disables the ability to populate the second drop down.
<!-- Populate First Dropdown -->
<select id="first-choice" name="cardset">
<?php foreach ($data as $row): ?>
<option><?=htmlentities($row["name"])?></option>
<?php endforeach ?>
</select>
<br />
<!-- Populate Second Dropdown -->
<select id="second-choice" name="card">
<option>Please choose from above</option>
</select>
<!-- Jquery to Populate second and Produce image -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language=JavaScript >
$(document).ready(function(){
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
$("#second-choice").change(function() {
var first = $("#first-choice").val();
var sec = $(this).val();
$("#image-swap").attr("src", (first !== "" && + sec !== "") ? "pics/" + first + "/" + sec + ".jpg" : "");
});
});
</script>
Here is the getter.php file I use to populate second drop down using above jquery:
$choice = $_GET['choice'];
$sth = $db->prepare("SELECT code FROM sets WHERE name='$choice'");
$sth->execute();
$choicecode = $sth->fetchColumn();
$stmt = $db->prepare("SELECT * FROM cards WHERE code='$choicecode'");
$stmt->execute();
$data2 = $stmt->fetchAll();
?>
<?php foreach ($data2 as $row): ?>
<option><?=$row["cardname"]?></option>
<?php endforeach ?>
Basically I want to encode the data that goes in the drop downs because they contain spaces and apostrophes. How can I still do this while at the same time output them correctly?
urlencode should be used when you're constructing the query parameters in a URL. When you're putting text into HTML, you should use htmlentities. Also, use the ID column as the value in your options.
<?php foreach ($data as $row): ?>
<option value="<?=$row["id"]?>"><?= htmlentities($row["name"]) ?></option>
<?php endforeach ?>
Also, you should use parametrized queries to prevent SQL injection and avoid other problems when constructing the query if it contains special characters:
$stmt = $db->prepare("SELECT * FROM cards
WHERE code = (SELECT code FROM sets WHERE id = :id)");
$stmt->execute(array(':id' => $_GET['choice']));
$data2 = $stmt->fetchAll();
Related
I have a table consists of three columns :
id
author
message
Once the user clicks on the More Button the button passes the Count parameter to .load function. And then new data should display but it
displays a blank page.What am i doing wrong?
this is index.php:
<div id="comments">
<?php
$v=$db->prepare('select * from comments limit 2');
$v->execute();
$data=$v->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo "<div>".$row['author']."</div>";
echo "<div>".$row['message']."</div>";
echo "</br>";
}
?>
</div>
<input type="submit" name="" id="submit" value="More">
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
var commentCount=2;
$('#submit').click(function(){
commentCount=commentCount+2;
$('#comments').load('loadComments.php',{count:commentCount});
});
});
</script>
this is loadComments.php:
<?php
$db=new PDO('mysql:host=localhost;dbname=ajax',"root","");
$newCount=$_POST['count'];
$ex=$db->prepare('select * from comments limit $newCount');
$ex->execute();
$data=$ex->fetchALL(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo "<div>".$row['author']."</div>";
echo "<div>".$row['message']."</div>";
echo "</br>";
}
?>
EDİT:
If I use this way everything is ok.
$v=$db->prepare('select * from comments limit 3');
But I have checked count parametre inside loadComment.php
echo $newCount;
and I am able to get the value Its funny
The issue is because of using Single quoted strings (as ') instead of Double quote strings (as ") - as #mrunion mention in the comments
In PHP when using ' the inner string is not being evaluate in contrast to the " mark. So the statement of 'select * from comments limit $newCount' is been sent as is and the $newCount is not been evaluate as 2 or what ever int it hold.
Full explanation about PHP quote can be found here
I'm pulling data from an Azure SQL database using PHP and have successfully created a drop-down (Select) box with Options that are pulled from the database.
The SQL query returns 2 columns, Title & Cycle_ID.
I have set the Title as the text string and the Cycle_ID as the value.
I now want to store the value (Cycle_ID) of the current selection in a variable (MyVariable), which I will use in the SQL query for the next drop-down box I'm creating, i.e. WHERE Cycle_ID = MyVariable.
This way the user progressively narrows their selection as they work their way down through my drop-down boxes.
My current code is below, but I don't know how to create and store the current selection to MyVariable.
<?php
//create the database connection and define the query
$serverName = "myserver";
$connectionOptions = array(
"Database" => "mydatabase",
"Uid" => "mysqlaccount",
"PWD" => "mypassword"
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//defines cycle query
$cyclesql= "SELECT [Cycle_ID]
,[Title]
FROM [ods].[Cycle]
WHERE End_Date > DATEADD(month,-6,GETDATE()) AND Updated IS NOT NULL
ORDER BY Cycle_ID Asc";
$cycleResults= sqlsrv_query($conn, $cyclesql);
if ($cycleResults == FALSE)
echo (sqlsrv_errors());
?>
<html>
<body>
<form action="cyclefile.php" method="post">
<div id="select">
<p>Select the week:</p><select name='Week'>
<option value="">Select...</option>
<?php
//starts loop
while ($row = sqlsrv_fetch_array($cycleResults, SQLSRV_FETCH_BOTH)) {
//defines cycle variable
$cycle = $row['Title'];
//defines cycle_id variable
$cycle_id = $row['Cycle_ID'];
//displays cycle variable as option in select (dropdown) list and cycle_id as value
echo '<option value="'.$cycle_id.'">'.$cycle.'</option>';
}
?>
</select>
</div>
</form>
</body>
</html>
I suggest you to make an ajax call on selection and pass the selected value to process your result in another file where you can run your query.
<select name="cycle_data" id="cycle_id">
<option value="cycle1" > Cycle 1</option>
<option value="cycle2" >Cycle 2</option>
</select>
Then lets do a script:
<script type="text/javascript">
$(document).ready(function(){
$("#cycle_id").change(function(){
var cycle_data = $(this).val();
var dataString = "cycle_data="+cycle_data;
$.ajax({
type: "POST",
url: "get-data.php",
data: dataString,
success: function(result){
// Process your result here
}
});
});
});
</script>
So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>
I'm trying to create an auto-complete function into a textbox but the result should come from my SQL database.
Here's the code that i'm trying to configure:
index.php:
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
"autocomplete.php"; ];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
EDIT: I changed the content of variable availableTags and made it into var availableTags = <?php include('autocomplete.php') ?>;
Variable availableTags is the source of words, so I try to change it and instead put a file name where fetching of words from my database is happening.
Here's my autocomplete.php file:
<?php
include('conn.php');
$sql="SELECT * FROM oldemp";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
while($row=mysqli_fetch_array($result))
{
echo "'".$row['name']."', ";
}
?>
EDIT: Also changed the content of the while loop and made it into
$name=mysqli_real_escape_string($con,$row['name']);
$json[]=$name;
How can I insert the fetched words from autocomplete.php into availableTags variable?
EDIT/UPDATE: There's a list showing up whenever I type something on the textbox, but it has no text in it. I know it's fetching, but the word itself is not showing on the list.
The jQuery UI autocomplete can take 3 different types of values of the source option:
An array containing the list of things to fill in the auto complete with
A string containing the URL of a script that filters a list and sends us the results. The plugin will take text typed into it and send it as a term parameter in a query-string appended to the URL we provided.
A function that retrieves the data and then calls a callback with that data.
Your original code uses the first, an array.
var availableTags = [
"autocomplete.php";
];
What that tells the autocomplete is that the string "autocomplete.php" is the only thing in the list of things to autocomplete with.
I think what you were trying to do is embed it with something like this:
$(function() {
var availableTags = [
<?php include("autocomplete.php"); /* include the output of autocomplete as array data */ ?>;
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
That would probably work okay assuming that the list of things that are being returned from the database will always remain short. Doing it this way is kind of fragile though since you are just shoving raw output from PHP into your JS. If the returned data contains " you might have to use addSlashes to escape it correctly. You should however change the query to return a single field rather than *, you probably only want one field as the label in the autocomplete not the entire row.
A better approach, especially if the list could potentially grow very large, would be to use the second method:
$(function() {
var availableTags = "autocomplete.php";
$( "#tags" ).autocomplete({
source: availableTags
});
});
This will require you to make a change to the back-end script that is grabbing the list so that it does the filtering. This example uses a prepared statement to ensure the user provided data in $term doesn't open you up to SQL injection:
<?php
include('conn.php');
// when it calls autocomplete.php, jQuery will add a term parameter
// for us to use in filtering the data we return. The % is appended
// because we will be using the LIKE operator.
$term = $_GET['term'] . '%';
$output = array();
// the ? will be replaced with the value that was passed via the
// term parameter in the query string
$sql="SELECT name FROM oldemp WHERE name LIKE ?";
$stmt = mysqli_stmt_init($mysqli);
if (mysqli_stmt_prepare($stmt, $sql)) {
// bind the value of $term to ? in the query as a string
mysqli_stmt_bind_param($stmt, 's', $term);
mysqli_stmt_execute($stmt);
// binds $somefield to the single field returned by the query
mysqli_stmt_bind_result($stmt, $somefield);
// loop through the results and build an array.
while (mysqli_stmt_fetch($stmt)) {
// because it is bound to the result
// $somefield will change on every loop
// and have the content of that field from
// the current row.
$output[] = $somefield;
}
mysqli_stmt_close($stmt);
}
mysqli_close($mysqli);
// output our results as JSON as jQuery expects
echo json_encode($output);
?>
It's been a while since I've worked with mysqli, so that code might need some tweaking as it hasn't been tested.
It would be good to get into the habit of using prepared statements since when properly used, they make SQL injection impossible. You can instead use a normal non-prepared statement, escaping every user-provided item with mysqli_real_escape_string before you insert it into your SQL statement. However, doing this is very error-prone. It only takes forgetting to escape one thing to open yourself up to attacks. Most of the major "hacks" in recent history are due to sloppy coding introducing SQL injection vulnerabilities.
If you really want to stick with the non-prepared statement, the code would look something like this:
<?php
include('conn.php');
$term = $_GET['term'];
$term = mysqli_real_escape_string($mysqli, $term);
$output = array();
$sql = "SELECT name FROM oldemp WHERE name LIKE '" . $term . "%';";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
while($row=mysqli_fetch_array($result))
{
$output[] = $row['name'];
}
mysqli_close($mysqli);
// output our results as JSON as jQuery expects
echo json_encode($output);
?>
When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data.
source: "autocomplete.php"
Therefore you need to return a JSON object.
$json = false;
while($row=mysqli_fetch_array($result))
{
$json[] = array(
'name' => $row['name']
);
}
echo json_encode($json);
Your autocomplete.php file,
include('conn.php');
$sql="SELECT * FROM oldemp";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
//Create an array
$arr = Array();
while($row=mysqli_fetch_array($result))
{
array_push($arr,$row['name']);
}
header('Content-Type: application/json');
echo json_encode($arr)
?>
The result of this will be an JSON array which can be directly used in JavaScript.
Hence, the script will be something like -
var availableTags = [];
$.ajax({
url:"autocomplete.php",success:function(result){
availableTags = result
}});
Solved my problem.
Have the script like this:
<!-- WITHOUT THESE THREE BELOW, THE AUTOCOMPLETE WILL LOOK UGLY OR WILL NOT WORK AT ALL -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "autocomplete.php"
});
});
</script>
And autocomplete.php (where we will get the data to fill the autocomplete input field):
<?php
include("conn.php"); /* ESTABLISH CONNECTION IN THIS FILE; MAKE SURE THAT IT IS mysqli_* */
$stmt = $con->prepare("SELECT description FROM table"); /* START PREPARED STATEMENT */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($description); /* BIND THE RESULT TO THIS VARIABLE */
while($stmt->fetch()){ /* FETCH ALL RESULTS */
$description_arr[] = $description; /* STORE EACH RESULT TO THIS VARIABLE IN ARRAY */
} /* END OF WHILE LOOP */
echo json_encode($description_arr); /* ECHO ALL THE RESULTS */
?>
Just a suggestion for the autocomplete file. Sorry, I would have added a comment above, but I don't have enough rep as of writing this.
After successfully implementing Useless Code's suggestion I was noticing my server overhead was going through the roof. It seemed bots were some how initiating the script, even though there was no letters being typed in the input area. I did a little test on the autocomplete file and found it would query my database even if the term was empty.
So, I just encpsulated the whole autocomplete script with an if statement... like so...
<?php
if(!empty($_GET['term']))
{
include('conn.php');
$term = $_GET['term'];
$term = mysqli_real_escape_string($mysqli, $term);
$output = array();
$sql = "SELECT name FROM oldemp WHERE name LIKE '" . $term . "%';";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
while($row=mysqli_fetch_array($result))
{
$output[] = $row['name'];
}
mysqli_close($mysqli);
// output our results as JSON as jQuery expects
echo json_encode($output);
}
?>
... and now my server is back to normal.
i tried to automatically select the value of multiselect box using data retrieved from database, but its not working...
this is the code for html multiselect
<select name="category" id="category" multiple="multiple" class="select validate[required]" style="width:100%">
</select>
at page load i dynamically load options for multiselect from database (mysql)
$.ajax({
url:'search/category.php',
type:'POST',
data:{cat_id:1}, //1 means jobs category
async:true,
success: function(data){
$("#category").html(data);
}
});
but if i have to auto select value in multiselect its not working
<?php
$qry ="select tags from posts where id='$id'";
$res = mysqli_query($con,$qry);
$row = mysqli_fetch_assoc($res);
$tags = $row['tags'];
?>
<script>
$(function(){
$("#category").val(<?php echo $tags; ?>); //example: .val(3);
}
</script>
ajax is correct but you need to echo select options correctly
in category function try this :
foreach ($tags as $tag=>$val) {
echo "<option value=".$val." > ".$tag."</option>";
}
You are just missing the quotes in your $("#category").val(); line. Check this fiddle out.
$("#category").val( "'" + <?php echo $tags; ?> + "'");
should get it to work