I have already made a post regarding this issue no longer than 2hours ago but I really need to get this finished ASAP.
What I am trying to do is create a drop down container of 32 different locations in Scotland and when one of the selections is selected, for example, Glasgow it should go to a URL which displays content such as heading, text, for each article in a div WHERE location = Glasgow.
Currently I do not have URL's for each location.
I the following message when I select a new option: "Load Result: success ||| 200 OK"
Can someone be so kind to provide me with the last piece to this frustrating puzzle?
Here is my files which are being used:
header.php
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#location').change(function(){
//Retrieve Content from the back-end PHP page, and pass the ID selected
var url = 'location.php?location=' + $(this).val();
$('#txtHint').load(url, function (response, status, xhr) { alert("Load result: " + status + " ||| " + xhr.status + " " + xhr.statusText);
});
});
});
</script>
</head>
<body>
<div id="header">
<div class="headerLeftContent">
<select id="location">
<option value="Glasgow">Glasgow</option>
<option value="x">x</option>
<option value="test">test</option>
<option value="Edinburgh">Edinburgh</option>
</select>
<div id='txtHint'></div>
</div>
</div>
</body>
</html>
location.php
<?php
$connect = mysql_connect('xxx', 'xxx', 'xxx');
$select_db = mysql_select_db('xxx');
$location = $_REQUEST['location'];
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
$result = mysql_query( $query, $connect );
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}
?>
Thanks.
Correct this
$query = "SELECT * FROM podContent WHERE location = ".$location;
Two things:
$query = "SELECT * FROM podContent WHERE location = '.$location.'"; has two additional dots. It should be $query = "SELECT * FROM podContent WHERE location = '$location'";.
Before using the value $location from the user, you should escape it with mysql_real_escape_string(). Note this function is deprecated, and will be removed on future versions of PHP. You should take a look into PDO and prepared statements.
Related
I have a combobox that contains a project number id. Based on the selection of this combobox I want to display the amount of rows in another table containing the same project number id. This value will be appended to the blue box "Number of POs".
My file "new-customer-po.php". I'll display it in parts for simplicity.
<?php
//Query for projectnumber
$query_1 = "SELECT PROJECTNOID, ProjectNumber, ProjectTitle, (SELECT (SELECT
CustomerName FROM tblCustomers WHERE Customer = CUSTOMERID) AS Customer
FROM tblCustomerContacts WHERE CustomerProjectLeadID =
CUSTOMERCONTACTID) AS CustomerProjectLeadID FROM tblProjects ORDER BY
ProjectNumber DESC";
$result_1 = mysqli_query($conn, $query_1);
$options_1 = "";
while($row_1 = mysqli_fetch_array($result_1))
{
$options_1.='<option value="'.$row_1[0].'">'.$row_1[1]." - ".$row_1[2]." - ".$row_1[3].'</option>';
}
?>
further down this page I have the following html
<label>Project Number <b style="color:red;">*</b></label>
<select id="proj" name="projectnum" class="inputvalues" required>
<option disabled selected value>-- Project # - Title - Customer --</option>
<?php echo $options_1; ?>
</select><br>
<div id="currentnumpo">
<label>Number of POs</label><input name="numpos" class="inputvalues" id="reqtxtfield" readonly/><br>
</div>
and after the closing html tag
<script type="text/javascript" >
jQuery(document).ready(function($) {
$("#proj").on('change', function() {
var num = $(this).val();
if(num){
$.ajax ({
type: 'POST',
url: 'getnumberpo.php',
data: { num },
success : function(htmlresponse) {
$('#currentnumpo').html(htmlresponse);
console.log(htmlresponse);
}
});
}
});
});
</script>
My "getnumberpo.php"
<?php
echo $_POST['projectnum'];
if(isset($_POST['projectnum'])){
$sql = "SELECT COUNT(*) FROM tblCustomerPOs WHERE ProjectNum = '".$_POST['projectnum']."'";
$result = $conn->query($sql);
if ($sql) {
while($row = $conn->query($sql)) {
echo '<label>Number of POs</label><input name="numpos" class="inputvalues" id="reqtxtfield" placeholder="';
echo $row[0];
echo '" readonly/><br>';
}
}
$sql = NULL;
}
?>
I'm very new to javascript/ajax so i'm sorry if none of what i'm doing makes sense.
So far when I change the dropdown the whole textbox for "number of po's" dissappears. I've ran the query on "getnumberpo.php" on mysql workbench and it works just fine.
Ex: When I select a project from the dropdown. It will query another table called tblCustomerPOs and check how many rows contain the project number that was selected.
Thanks for the help
If anyone comes across this in the future and wanted the answer...
getnumberpo.php (Server-Side Script)
<?php
require "../inc/dbinfo.inc";
$projectnum =$_POST['projectnum'];
$sql = mysqli_query($conn, "SELECT COUNT(*) AS mycount FROM tblCustomerPOs WHERE ProjectNum = '$projectnum'"); //RESPONSE IS QUERY WITH REAL $PROJECTNUM
$res = mysqli_fetch_object($sql)
$count = $res->mycount;
echo json_encode($count);
exit();
?>
new-customer-po.php (Javascript)
//AUTO UPDATE NUMBER OF POS
$(document).ready(function(){
$('#projectnum').change(function(){
var projectnum = $(this).val();
var data_String;
data_String = 'projectnum='+projectnum;
$.post('getnumberpo.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#currentnumpo').val(data)
});
});
});
new-customer-po.php (html)
<label>Project Number <b style="color:red;">*</b></label>
<select id="projectnum" name="projectnum" class="inputvalues" required>
<option disabled selected value>-- Project # - Title</option>
<?php echo $options_1; ?>
</select><br>
<label>Number of Customer POs</label><input type="text" name="currentnumpo" id="currentnumpo" class="inputvalues" readonly/><br>
When I used page=1 ,everything is OK.BUT if I changed
$.get("getajax.php","page=1" ,function(data){ }
to
$.get("getajax.php","page="+pageno ,function(data){ }
then the program return a false and "fatal error: Call to a member function fetch_assoc() on a non-object", I think this means the $result has problems.Thus , the $query has a problem?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<div id="showdata"></div>
<input type="hidden" id="currentresult" value="1" />
<button id="show">Load</button>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#show',function(e){
var pageno = $('#currentresult').val();
$.get("getajax.php","page="+pageno ,function(data){
pageno++;
$('#currentresult').val(pageno);
$('#showdata').append(data);
});
});
});
</script>
</body>
</html>
And the getajax.php
<!-- This is ajax data. -->
<?php
$con = mysqli_connect("localhost", "root", "", "maroon5");
$page=isset($_GET["page"])?$_GET["page"]:0;
$pageNo = $page;
$startLimit = ($pageNo-1)*2;
$query = "SELECT * from tour LIMIT $startLimit,2 ";
$result = mysqli_query($con,$query);
var_dump($result);
while($row = $result -> fetch_assoc()){
?>
<div>
<h4>
month:<?php echo $row["month"]; ?>day:<?php echo $row["day"]; ?>
</h4>
</div>
<?php
}
?>
The reason why $.get("getajax.php","page=1" ,function(data){ works is because it always sends 1 to your php, thus creating the sql query of SELECT * from tour LIMIT 0,2
However if you were to change to $.get("getajax.php","page="+pageno ,function(data){, page will get assigned pageno which increases dynamically every time the button is clicked thus creating different queries to the DB like:
first click: "SELECT * from tour LIMIT 0,2"
second click: "SELECT * from tour LIMIT 2,2"
third click: "SELECT * from tour LIMIT 4,2"
As you can see the second, or third click would be different. Not completely sure but this is most likely your case. One of these queries is not finding any results, thus throwing the error at fetch_assoc()
Try mysqli_error function to get real error
$result = mysqli_query($con,$query)or die (mysqli_error($con));
If your page if 0 then startLimit would be -2
Add a bit of logic here
$startLimit = ($pageNo-1)*2;
if($startLimit < 0)
{
$startLimit = 0;
}
Should work! Though not the perfect solution but would work
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>
What I am trying to do is create a drop down container of 32 different locations in Scotland and when one of the selections is selected, for example, Glasgow it should go to a URL which displays content such as heading, text, for each article in a div WHERE location = Glasgow.
I have no error messages or any sort of recognition that my code has worked as when I select one of the four on the drop down it does absolutely nothing.
Can come clean up and put right what I've done so far? I would be extremely greatful!
Here is my files which are being used:
header.php
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#location').change(function(){
//Retrieve Content from the back-end PHP page, and pass the ID selected
var url = 'location.php?location=' + $(this).val();
$('#txtHint').load(url);
});
});
</script>
</head>
<body>
<div id="header">
<div class="headerLeftContent">
<select id='location'>
<option href="Link to a dynamic page with all the content from glasgow" value="Glasgow">Glasgow</option>
<option href="Link to a dynamic page with all the content from x" value="x">x</option>
<option href="Link to a dynamic page with all the content from test" value="test">test</option>
<option href="Link to a dynamic page with all the content from edinburgh" value="Edinburgh">Edinburgh</option>
</select>
<div id='txtHint'></div>
</div>
</div>
</body>
</html>
location.php
<?php
$connect = mysql_connect('xxxxxx', 'xxxxxx', 'xxxxxx');
$select_db = mysql_select_db('xxxxxx');
$location = $_REQUEST['location'];
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
while($row = mysql_fetch_array($query))
{
echo $row['text'];
}
mysql_close($connect);
?>
And please any comments regarding 'SQL injection' or how 'mysql' should be 'PDO' are unwanted as I do understand this but I am simply testing at the moment and will amend this.
Thanks.
You seem to have a mistake concatenating your location name inside your MySQL query, and it's not matching anything (so nothing is echoed back). Change this:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
to
$query = "SELECT * FROM podContent WHERE location = '$location'";
(Unless you have stuff like .Glasgow. in your database...)
Then you have to call mysql_query($query) as Alon suggested.
You need to use mysql_query and pass the resource to the mysql_fetch_array function:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}
I've a select populated by a php query, that loads the nicknames of the users logged in a specific div, called “UserList”.
<div id=”UserList” name=”UserList”>
</div>
This select is placed in a php page, “userlist.php”, loaded by jquery. The php query works fine, so I've avoided writing here the db connection.
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>
</select>
My problem is that I need to reload only the select and refreshing it when a user clicks the select itself, so new users that enter the page are added by the php query and those that changed page are removed from the list. But whit every event that I tried the jquery loops, instead of activating the reload only once every time a user clicks the form and the first click event not even reload properly the php query.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#UserList").load('userlist.php');
$("#UserList").click(function() {
$("#UserList").load('userlist.php');
evt.preventDefault();
});
});
</script>
Thanks for your help.
I would suggest using AJAX to do this. AJAX allows you to query the web-server with out refreshing the entire page. This example
seems like almost exactly what you want to do.
Edit:
Put this inside your template:
<div id=”UserList” name=”UserList”>
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result))
{
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result);
?>
</select>
</div>
Then Change the Javascript
<script type="text/javascript">
$(document).ready(function() {
$("#User").click(function() {
$("#User").load('userlist.php');
});
});
</script>
And finally change the userlist.php file:
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>