autocomplete shows all entries, Does not do any searching - php

Please help me ...
I'm a newbie! Please tell me what to do.
processed.php
<?php
include_once('../../dbConnect.inc.php');
$sql="SELECT name FROM artist";
$artist = select($sql);
disconnect();
$output_items = array();
while($row = mysql_fetch_array($artist))
{
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
?>
index.php
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#artist").autocomplete(
{
source: 'processed.php',
});
});
</script>
I have this problem: http://jsbin.com/alaci5

Autocomplete expects the source (when an URL is specified to filter out the results).
From documentation:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
So in your PHP code you have to do:
include_once('../../dbConnect.inc.php');
$sql="SELECT name FROM artist WHERE `name` like '%".mysql_real_escape_string($_GET['term'])."%'";
$artist = select($sql);
$output_items = array();
while($row = mysql_fetch_array($artist)) {
$results[] = array('label' => $row['name']);
}
echo json_encode($results);

That autocomplete function is probably passing a few variables to your processed.php page.
Use var_dump($_GET) to see all the things you're being passed.
Inside one of those $_GET elements, you'll have the contents of the text box as they exist on the page. For the sake of demonstration, I'm going to use $_GET['text']. You'll need to find out which part holds the data you need.
What you'll need to do is search the database using this value for a list of results to return.
$sql="SELECT name FROM artist";
$artist = select($sql);
This is your script as it exists. What it may end up looking similar to is this.
$text_input = mysql_escape_string($_GET['text']);
$sql="SELECT name FROM artists WHERE name LIKE '%$text_input%'";
$artist = select($sql);
You'll want to get results that are similar to the inputted text on the user-facing page.
A few notes for you
I used mysql_escape_string() solely to may what you already have. While this does work (driving around a busted-ass chevy pacer works too, but there are much better ways though), its not recommended, which sets us up for point 2.
Using the old mysql extension is not really a good idea, its been replaced by mysqli, and PDO.
you'll need to escape your data, this is how its done with mysqli.

Related

How do I pass a variable from PHP to generated JavaScript?

I'm generating JavaScript from my PHP script, and I need to be able to copy a value directly into the generated JavaScript code.
My code is as follows:
PHP:
include "db-Info.php";
echo '<option value="">Please select item first...</option>';
$item = $_POST['itemId'];
$query = mysqli_query($con, "SELECT id, item, price, pointRequired FROM
tblprice WHERE item ='$item'");
$rowCount = $query->num_rows;
if($rowCount > 0) {
while($row = mysqli_fetch_array($query)){
$price = $row['price'];
$pointRequired = $row['pointRequired'];
echo "<option id='priceNew'>";
echo "Price : $price" ?> <?php echo "Point: $pointRequired";
echo "</option>";
}
if($item){
$price = $_POST[price];//shows undefined
$query1 = mysqli_query($con, "SELECT id FROM tblprice WHERE item
='$item'AND price ='$price'"); //it seems not picking up the same id with
the item I selected above
$rows = mysqli_fetch_array($query1);
$id = (string) reset($rows);
$barcodeNew = $id . $item;
echo $barcodeNew;
}
}
JavaScript:
$(document).ready(function() {
$('#price-select').on('change', function(){
var price = $(this).val($price); // This is where $price needs to copy
if(price){
$.ajax({
type:'POST',
url: 'functions/pos-getPrice.php',
data: {price:price},
success:function(html){
alert(price);
}
})
}
})
})//THIS CODE BLOCK IS PROBLEM
The problems are:
The line $price = $_POST[price] results an undefined value
I'm trying to copy $price into the PHP script but it's outputting $price verbatim in my script - not the value contained in $price
Problem 1:
You need to change $_POST[price] to $_POST['price'], like you have just above it. Without wrapping it in quotes, PHP will assume you're trying to use a constant defined with define().
Problem 2:
If you're using vanilla PHP and you want to inject a variable into a script, you'd do it like so:
var price = ($this).val(<?php echo json_encode($price); ?>);
This of course assumes that the JavaScript is being generated from the same PHP script you have above it.
You can read the documentation for json_encode here.
You have a huge security vulnerability in your code as well:
At the moment, your script is taking data in directly from the user request and putting it into an SQL query. This can lead to SQL injection attacks. Not good.
Official PHP documentation on the subject can be found here.
Recommendations:
First, I notice you're doing everything in the global space. I highly recommend that you learn how to wrap your code in classes and functions; it'll make things much easier to maintain and test.
Good things to search that will get you on the right path are:
PHP Object Oriented Programming (OOP)
PHP Standards Recommendation (PSR)
PHP Composer
Second, doing things this way is quite outmoded and makes it very easy to run into problems. I encourage you to look into more modern frameworks, such as Laravel. You might also look up single-page application (SPA) frameworks like Vue, Angular, or React, which work great with Laravel serving as a backend REST API.
Best of luck to you.

Using PHP code in the value of a variable

I am trying to send an email in PHP where the content of the email has some conditional checks and some database query lookups.
What I would like to acheive is having my email code as a variable (similar to below) so that I can sent mail() the content to the relevant people.
$emailContent = "<p>My email content</p>";
However the value of this variable would have some code like this:
<table>
<?php
$get_course_units = "SELECT * FROM course_units where course_units.course_code = {$courseCodeExtract}";
$course_units_results = $conn->query($get_course_units);
if ($course_units_results->num_rows > 0) {
while ($courseUnits = $course_units_results->fetch_assoc()) {
?>
<tr>
<td><?php echo $courseUnits["unit_code"]; ?> – <?php echo $courseUnits["unit_name"]; ?> </td>
</tr>
<?php
} //end loop for course units
} //end if for course units
?>
</table>
How should I continue?
Split up your script into an html template file and your php logic.
Use shortcodes in your templates where you want to have custom information and then use str_replace to replace that content with the actual values.
$template_string = file_get_contents('myfile.html');
$shortcodes = array("{{FNAME}}","{{LNAME}}","{{OTHER_STUFF}}");
for(/* all the people you want to mail */){
$custom_info = get_custom_info(/* person */); //eg returns assoc array
$result = $template_string;
foreach($shortcodes as $code){
$result = str_replace($code, $custom_info[$code], $result);
}
//do what you want with result and mail it
}
In the example above, get_custom_info would be returning an associative array with the same values as the shortcodes array, just for convenience.
Now anywhere I put {{FNAME}} in my html, it will be replaced with the value I get back from the custom info function.
You can easily extend this to scrape the template and look for {{ and }} (or whatever shortcode syntax you want) anddetermine what variables you will need from your custom info, shaping the query to only give you what you actually need.
Not sure if this is the best way, but it seems to work pretty well. (also best way is subjective, so might want to ask questions a little differently)

Changing options in second drop down menu by user input in first drop down menu

Thanks for taking time to look at this.
I have two drop down menus. The first is a list of clients, the second is a list of projects.
All projects are tied to just one client, so I'd like for the code to get user input for the client, then read that value, and modify the PHP code to only print out the values in the second drop down menu that correspond to the client selected.
Here's some code. For the first drop down menu:
<div class="item">
<label for='clSel' id='tsClLabel'>Client:</label>
<select name='clSel' id='wClient' onChange="bGroup();">
<option></option>
<?php
$cQuery = "SELECT * FROM Clients ORDER BY Client_Name";
$cResult = mysql_query($cQuery);
while($cData = mysql_fetch_assoc($cResult)) {
echo '<option id="Cid" value="'.$cData['Id'].'">'.$cData['Client_Name'].'</option>';
}
?>
</select>
Here's my jQuery function to get the user-selected value from the first drop down:
<script>
function bGroup(){
val1 = $("#wClient").val();
// window.alert(val1);
// $('#div1').html(val1);
return val1;
}
</script>
And the code for the second drop down menu:
<label for='billGroupId'>Billing Group: </label>
<select name='billGroupId'>
<option value=''></option>
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
echo "<option value='".$row['Id']."' > ".$row['Name']."</option>";
echo "<script> bGroup(); </script>"
}
}
?>
</select>
I know I need to include a WHERE statement in the second drop down menu
Basically Select * FROM Clients WHERE Client_ID == $jsVAR.
I already have the value I need in the var1 JavaScript variable. How can I get this little piece of data either read by PHP or sent to PHP via JS code?
Thanks!!
You can SELECT all records from the database, and then insert them to your page HTML using json_encode(). Something like that:
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
$projectData = array();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
$projectData[$row['Client_Id']][] = $row;
}
}
echo '<script type="text/javascript">var projects=', json_encode($projectData), ';</script>';
?>
Then, in your JS, you use the variable projects as an associative array (object), eg.:
<script type="text/javascript">
for (p in projects[clientId]) {
alert(projects[p].Name);
}
</script>
Tricky one,
You have a choice. One way is to use Ajax to grab the second level menu structure upon getting the first level choice, and populate the second level once that succeeds. That's likely to be a problem, as there will likely be some sort of network delay while that happens, of which you have no control (unless you are in a closed environment). So from a user point of view it could be counter intuitive and sluggish feeling, especially on a slow connection or shared hosting solution where timings can vary enormously.
The other way is to somehow pull all values possible and filter them (so hide the ones that don't apply) using jQuery, perhaps utilising classes or some other attribute as a method of filtering data. Using jQuery you can assign data to elements so you could also use that too. The second method may not be so good if there's a lot of data (can't tell from the scenario you've described). Looking at your second level code I don't see a WHERE condition so I'm not sure how the value from the first level is affecting that of the second level, so it's hard to know how to deal with that for this method.

How to pass json value php to js

In my one of php file I am running one query whatever query result is display that value I want to put in the number.js file. even I copied .js code in that PHP file but in the main file(index.php) I am facing conflict of the js file . Thats why I cant copied js file into that php file . Please provide me the soution. below that I am copied my code of PHP as well as js file.
In PHP code
$query_string = "SELECT COUNT(Email) AS total FROM Contact INNER JOIN CompanyBranch ON Contact.CompanyBranchID = CompanyBranch.CompanyBranchID INNER JOIN Company ON Company.CompanyID = CompanyBranch.CompanyID INNER JOIN CompanyIndustry ON Company.CompanyID = CompanyIndustry.CompanyID INNER JOIN IndustrySubindustry ON CompanyIndustry.IndustrySubindustryID = IndustrySubindustry.IndustrySubindustryID WHERE CompanyBranch.GlobalRegionID = '$global_region' AND IndustrySubindustry.IndustryID = '$industry' AND IndustrySubindustry.SubindustryID = '$sub_industry'";
$query_string = strtolower($query_string);
$result_data = mysql_query($query_string) or die();
//$tmp = mysql_fetch_array($result_data);
$row = mysql_fetch_assoc($result_data);
$total_lead = $row['total'];
echo json_encode($total_lead);
whatever value get in the $total_lead variable that I want to redirect into the number.js file
Code in the number.js file
var leads=0;
I want the var_leads=$total_lead (the value come from the php file).
How it is possible?
.js files will be default NOT be executed as PHP scripts on a server, unless you tell the webserver to do so. That means you cannot embed PHP code into a .js file and have it fill things in for you.
Unless you do want to modify your server to force PHP handling of .js files, you'd be better off doing something like this:
yourfile.php:
<?php
... do query stuff here ...
?>
<html>
<head>
<script type="text/javascript">var leads = <?php echo json_encode($total_leader) ?>;</script>
<script type="text/javascript" src="number.js"></script>
</head>
That'll set the leads variable for you with the query results, then load the rest of the number.js script which then (supposedly) uses that variable.
The alternative is having a piece of JS code that performs an AJAX call back to your server to fetch the number dynamically at page load time.
You can look here for appropriate PHP-JSON libraries to do this job:
http://www.php.net/releases/5_2_0.php
http://pecl.php.net/package/json
JSON page: http://www.json.org/
I don't know the full context of your application, but if you are making an AJAX request to this script, you need to use a callback or onreadystate change, depending on wether the call is asynchronous.
If this script also loads a page, then you need to echo out the value in the context of actual tags.
You could also run your PHP inline with the JavaScript. Take a look at this quick example for instance:
<?php
$query_string = "Your select statement...";
$query_string = strtolower($query_string);
$result_data = mysql_query($query_string) or die();
//$tmp = mysql_fetch_array($result_data);
$row = mysql_fetch_assoc($result_data);
$total_lead = $row['total'];
?>
<script type="text/javascript">
var leads = <?=$total_leads?>; //as integer
var leads = '<?=$total_leads?>'; //as string
//other js stuff
</script>
You can use this:
var obj = <?php echo json_encode(your_json_object) ?>
var jsonObject = JSON.parse(obj)

php - filling in form fields from database values

I'm trying to "pre-fill" (not sure if there's a technical term for this) form fields with values that the user has previously entered in the database. For this example it's a City and State. When the user loads the page to edit options, these values (which they have previously entered) will automatically be in the text boxes.
<tr><td>City</td><td><input type="text" name="city" value="<? $city = "usercity"; echo $formValue->location('$city'); ?>"></td>
<td>State</td><td><input type="text" name="state" value="<? $state = "userstate"; echo $formValue->location('$state'); ?>"></td>
Is there any way to set a value based on the input (from the boxes above)? If it was something like function location($input) I would know how to, but when there's nothing in the parenthesis, is there any way to set a value?
function location(){
$userid = $_SESSION['userid'];
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(testdb, $connection) or die(mysql_error());
$result = mysql_query("SELECT '$location' FROM userinfo WHERE userid = '$userid'");
$user_data = mysql_fetch_array($result);
if($location =='usercity'){
$userlocation = $user_data['usercity'];
return $userlocation;
}
else
$userlocation = $user_data['userstate'];
return $userlocation;
}
Instead of thinking about this from a global perspective think about the problem in it's context.
Your starting point (from the server perspective) is that an HTTP GET request has come in from a client for this page, or a client is returning to this page from after a POST request. In either case, the server has located the "resource" (the PHP script) that should handle this request and dispatched it by loading the PHP interpreter with the script file.
The context at this point is at the first line of the script; at the point where the interpreter has just finished parsing and started executing. Ask yourself: does the current request include an active session identifier? If it does have an active session, then check to see if the client has filled in this form before and if they have, substitute the default form values they've previously submitted for the normal form default values. If the client does not have an active session or has not used the form before then show a blank form with default values as needed.
Tip: Consider using this technique to debug your code. Pick a line in your code and place a mental "break point" at that place. Ask yourself: what is the context of this script at this point? What variables are defined? What is the server state? What is the client expecting? Once you have an answer to those questions, writing the code is simple.
From what I see in your code you have the variable in single quotes:
$city = "usercity"; echo $formValue->location('$city');
remove the single quotes, as it will pass '$city' as is, not the value of $city. Try
$city = "usercity"; echo $formValue->location($city);
to make it clearer:
$city = "usercity";
print ('$city'); // will print $city
print ($city); // will print usercity
My last few projects had forms all over the place and telling php to fill out the forms each time was a pain in the arse.
For my current project, I kept the input names the same as the mysql field names. Makes submitting and populating way easier.
When it comes to populating the forms, I use some ajax (jQuery used all over the project so using jquery's ajax() function;
FORM
<form>
<input name="field_one" type = "text" >
<input name="field_two" type = "text" >
<input type="button" value="Send">
</form>
I put a conditional statement at the top of the doc along the lines of:
<?php if($_POST['update']){
$query=mysql_query("SELECT * FROM table WHERE unique_id='$id' LIMIT 1");
echo json_encode(mysql_fetch_assoc($query));
exit;
} ?>
Lets say you have a list of items you want to be able to click on and edit (populate the form with it's corresponding data). I assign it a data- attribute and fill it with it's unique id, normally an AI PRIMARYKEY eg:
while($r=mysql_fetch_assoc($data)){
echo "<li data-unique_id=\"\">$r[name]<span class="edit">edit</span></li>";
?>
$('.edit').click(function(){
var toget = $(this).parent().data('unique_id');
$.ajax({
url:'here so it sends to itself',
data:'update='+toget,
success:function(data){
for (var key in data) {
if (data.hasOwnProperty(key)) {
$('input[name="'+key+'"]').each(function(){
$(this).val(data[key]);
});
}
}
}
});
There's a little more work required for <select>, <textarea>, checkboxes, but same general idea applies, (I threw in a couple of if statements, but it could probably be handled way better)
I could probably explain this better, but I hope you get the idea and i've been of some help.
FYI
my inserts are like...
foreach($_POST as $k=>$v){
$v=mysql_real_escape_string($v);
$fields.=" `$k`,";
$vals.=" '$v',";
}
$fields=substr($fields,0,strlen($fields)-1);//to get rid of the comma :)
$vals=substr($vals,0,strlen($vals)-1);//and again
mysql_query("INSERT INTO ($fields) VALUES ($vals)");

Categories