Displaying data from the database when user selects single value - php

I am trying to display the data from the database when a dropdown value is selected by the user. There is dropdown for all the registered members. when a admin user selects a registered member name from the drop down it has to populate all the details for that member.
My selection box code is like this
if ($_SESSION['admin_privs'] == "yes" || $_SESSION['edit_all_listings'] == "yes") {
$display .= '<tr><td align="right"><strong>' . $lang['listing_editor_listing_agent'] . ':</strong></td>';
$display .= '<td align="left" class="row_main">';
$agent_select = array();
// find the name of the agent listed as ID in $edit_or_owner
$sql = "SELECT userdb_user_first_name, userdb_user_last_name FROM " . $config['table_prefix'] . "userdb WHERE (userdb_id = $_SESSION[userID])";
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$recordSet = $conn->Execute($sql);
if ($recordSet === false) {
$misc->log_error($sql);
}
// strip slashes so input appears correctly
$agent_first_name = $misc->make_db_unsafe($recordSet->fields['userdb_user_first_name']);
$agent_last_name = $misc->make_db_unsafe($recordSet->fields['userdb_user_last_name']);
if ($_SESSION['admin_privs'] != "yes")
{
$agent_select[$_SESSION['userID']] = $agent_last_name.','.$agent_first_name;
}
// fill list with names of all agents
$sql = "SELECT userdb_id, userdb_user_first_name, userdb_user_last_name FROM " . $config['table_prefix'] . "userdb where userdb_is_agent = 'yes' or userdb_is_admin = 'yes' ORDER BY userdb_user_last_name,userdb_user_first_name";
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$recordSet = $conn->Execute($sql);
if ($recordSet === false) {
$misc->log_error($sql);
}
while (!$recordSet->EOF) {
// strip slashes so input appears correctly
$agent_ID = $recordSet->fields['userdb_id'];
$agent_first_name = $misc->make_db_unsafe($recordSet->fields['userdb_user_first_name']);
$agent_last_name = $misc->make_db_unsafe($recordSet->fields['userdb_user_last_name']);
if ($agent_ID == $_SESSION['userID']) {
$agent_select[$agent_ID] = $agent_last_name.','.$agent_first_name;
$selected = $agent_ID;
}else {
$agent_select[$agent_ID] = $agent_last_name.','.$agent_first_name;
}
$recordSet->MoveNext();
}
$display .= $form->selectBox($agent_select, $selected, 'or_owner');
$display .= "</td>";
$display .= '</tr>';
}
I have different function for forms , like this
function selectBox($array, $selected='', $name='', $size=1, $multiple=false, $additional='') {
$res = '';
static $count = 0;
if (is_array($array)) {
if ($name == '') {
$name = 'selectBox' . ++$count;
}
$res .= "<select name=\"$name\" size=\"$size\"" . ($multiple==false ? '' : " multiple=\"multiple\"") . ($additional ? " $additional" : '') . ">\n";
$i = 0;
foreach($array as $key => $value) {
$res .= "<option value=\"$key\"" . ($key == $selected ? " selected=\"selected\"" : '') . ">$value</option>\n";
}
$res .="</select>\n";
}
return $res;
}
function textField($value, $name='', $hidden=false, $size =-1, $length =-1, $additional='') {
$res = '';
static $count = 0;
if ($name == '') {
$name = 'textField' . ++$count;
}
$res .= "<input name=\"$name\" type=\"" . ($hidden ? 'password' : 'text') . "\" value=\"$value\"";
$res .= ($size != -1 ? " size=\"$size\"" : '');
$res .= ($length != -1 ? " maxlength=\"$length\"" : '');
$res .= ($additional ? " $additional" : '') . ">";
return $res;
}
Now i want to display the details of selected user from database, can somebody tell me how can i achieve this :(
thanks

I am not from php but after looking your code its look like your session cause this problem try to debug from session points..

This can best be achieved using AJAX. There is a tutorial on w3schools.com which explains how ajax works. You will simply have to modify the code they supply.
Fundamentally, what you need is:
<SELECT name='name' id='123' onchange='userhint(this.value)'><OPTION value='usercode'...
As your select. The key is putting the onchange call in the SELECT.
You will also need a form goes here
The JS looks like:
function userhint(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("changingdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","myphpfile.php?q="+str,true);
xmlhttp.send();
}
This will replace the content of 'changingdiv' with whatever myphpfile.php returns in response to a get request of q. You are clearly capable of writing that file yourself.
Depending on how you want to do it, the php can either create the complete HTML of the new div or return a json string which you can then use to populate your original areas. For a beginner, the first option is definitely easiest (and is expected by the very basic js above) but the json method will use a fair bit less bandwidth and makes it easier to re-use the same file to feed multiple pages.

Related

PHP: $_POST cannot retrieve existing inputs

I'm attempting to make a button that, based on the selected form/inputs on the page, will bring you to a page called "typeDefine.php?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism=1"(the numbers varying based on the selected inputs). However, $selectedNum- the variable that would ideally be containing the $_POST for each input- is returning an error immediately once the page is loaded, saying:
Undefined index
<?php
$typeWords = array("openness", "conscientiousness", "extroversion", "agreeableness", "neuroticism");
$typeLetters = array("o", "c", "e", "a", "n");
$typePath = "";
$correspondingLetters = array("I", "II", "III");
$isFirst = true;
foreach($typeWords as $typeWord)
{
$selectedNum = $_POST[$typeWord];//error here!!!
if(isset($selectedNum))//if got $typeWord in a form
{
$separationChar;
if($isFirst)
{
$separationChar = "?";
$isFirst = false;
}
else
{
$separationChar = "&";
}
$typePath = $typePath . $separationChar . $typeWord . "=" . $selectedNum;//e.g. $typePath = "?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism=1" for $_GET method after arriving on next page
}
}
echo 'search for type
<div>';
foreach($typeWords as $typeWord)
{
$typeLetter = substr($typeWord, 0, 1);
echo '<form method = "post" class = "column">';
for($i = 1; $i <= 3; $i++)
{
echo '<input type = "radio" name = "' . $typeWord . '" id = "' . $typeLetter . $i . '"><label for = "' . $typeLetter . $i . '">' . $correspondingLetters[$i - 1] . '</label>';//sets each input name to $typeWord for $_POST above
}
echo '<li class = "textHighlight">' . $typeWord . '</li>
</form>';
}
echo '</div>';
?>
What can I do to fix this error, in turn filling $typePath and making the script correctly bring you to the desired url upon the button's click?
Thanks in advance!
You should perform the isset() test on the $_POST element, not the variable that you set from it.
foreach ($typeWords as $typeWord)
{
if (isset($_POST[$typeWord])) {
$selectedNum = $_POST[$typeWord];
$typePath = $typePath . "?" . $typeWord . "=" . $selectedNum;
}
}
Note that multiple parameters need to be separated with &, ? should only be used at the beginning. There's a built-in function that will create a query string from an array, you can use that:
$typeArray = [];
foreach ($typeWords as $typeWord)
{
if (isset($_POST[$typeWord])) {
$selectedNum = $_POST[$typeWord];
$typeArray[$typeWord] = $selectedNum;
}
}
$typePath = $typePath . "?" . http_build_query($typeArray);
You can also replace the loop with:
$typeArray = array_intersect_key($_POST, array_flip($typeWords));
You execute your code immidiately without a present $_POST array.
You have to wrap your post related code with an if statement like this:
if ($_POST) {
$selectedNum = $_POST[$typeWord];
}

After ajax request php function not receiving variables

I'm developing a searcher and I made a function that gets the data from a db, saves each ad in a variable and saves pagination (from another function) in another variable, so they can be returned in an array to be printed in the html later.
It works like this: you hit a buy or rent button and you go to the search page (/search?do?=buy/rent) then you have to select the property type, optionally a city/zone and hit search. Ajax sends the data via post (to search.php, the same file), hides the first container and shows the second container that has the list of properties with a pagination at the end of the page.
These are the main variables and a script to hide/show containers:
$mode = filter_input(INPUT_GET, 'do', FILTER_SANITIZE_STRING); // buy or rent
$prop_type = filter_input(INPUT_POST, 'prop_type', FILTER_SANITIZE_STRING); // res or com AJAX
$city = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_NUMBER_INT); // AJAX
$zone = filter_input(INPUT_POST, 'zone', FILTER_SANITIZE_NUMBER_INT); // AJAX
$page_number = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT);
if (isset($page_number) && $page_number >= 1) {
$cont1 = 'display: none;';
$cont2 = NULL;
// need a way to get the prop_type (the checked checkbox before changing the page) without using $_GET.
} else {
$cont1 = NULL;
$cont2 = 'display: none;';
}
This is the function:
function get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage) {
if ($prop_type == 'res') {
$table2 = 'res_prop';
} else if ($prop_type == 'com') {
$table2 = 'com_prop';
}
if ($city != 0) {
$optional_cond = ' WHERE t2.city = ' . $city;
$optional_cond2 = NULL;
if ($zone != 0) {
$optional_cond2 = ' AND t2.zone = ' . $zone;
}
} else $optional_cond = $optional_cond2 = NULL;
$mysqli = new mysqli('127.0.0.1', 'db', '123456', 'name');
// pagination
if ($stmt = $mysqli->prepare('SELECT COUNT(id) FROM ' . $table)) {
$stmt->execute();
$stmt->bind_result($totalitems);
$stmt->fetch();
if (!isset($page)) {
$page = (int)$page_number <= 0 ? 1 : (int)$page_number;
}
$limit = 4;
if ($page > ceil($totalitems / $limit)) {
$page = ceil($totalitems / $limit);
}
$start = ($page - 1) * $limit;
$stmt->close();
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1
INNER JOIN ' . $table2 . ' t2 ON t2.id = t1.id
' . $optional_cond . $optional_cond2 . '
LIMIT ?, ?')) {
$stmt->bind_param('ii', $start, $limit);
$stmt->execute();
$stmt->bind_result($id, $id, $type, $status, $bhk, $baths, $area1, $area2, $age, $description, $price, $city, $zone, $img1, $img2, $img3, $img4);
$test = "";
while ($row = $stmt->fetch()) {
if ($status === 0) {
$possesion = 'En construcción';
} else if ($status === 1 || $status === 2) {
$possesion = 'Inmediata';
} else $possesion = 'Desconocida';
if ($prop_type == 'res') {
$is_res = '<p><span class="bath">Bed</span>: <span class="two">' . $bhk . ' BHK</span></p>
<p><span class="bath1">Baths</span>: <span class="two">' . $baths . '</span></p>';
} else $is_res = NULL;
$test .= '<div class="box-col">
<div class="col-sm-6 left-side ">
<img class="img-responsive" src="' . $img1 . '" alt="">
</div>
<div class="col-sm-6 middle-side">
<h4>Disponibilidad: ' . $possesion . '</h4>
' . $is_res . '
<p><span class="bath2">Built-up Area</span>: <span class="two">' . $area1 . ' m²</span></p>
<p><span class="bath3">Plot Area</span>: <span class="two">' . $area2 . ' m²</span></p>
<p><span class="bath4">Age of property</span>: <span class="two">' . $age . ' Year(s)</span></p>
<p><span class="bath5">Price</span>: <span class="two">' . $price . ' €</span></p>
<div class="right-side">
Contact Builder
</div>
</div>
<div class="clearfix"> </div>
</div>
';
$pagination = functions::getPaginationString($page, $totalitems, $limit, $adjacents = 1, $targetpage, $pagestring = "&page=");
}
} //else echo "Statement failed: " . $mysqli->error . "<br>";
} //else echo "Statement failed: " . $mysqli->error . "<br>";
return array($test, $pagination);
}
This is the main code:
if (empty($_GET)) {
echo 'under construction';
}
else if (isset($mode) && $mode == 'buy') {
$table = 'to_sell';
$targetpage = '/search?do=buy';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else if (isset($mode) && $mode == 'rent') {
$table = 'to_rent';
$targetpage = '/search?do=rent';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else {
echo 'invalid url';
}
This is the AJAX script that sends the checkbox value via post (it's not working correctly, I don't get an undefined error in $prop_type (I don't know why???) but I get it in $table2, that it's inside the if ($prop_type == '')):
$('.search, .pagination').click(function() { // search button and change page
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.post('search.php', { // same file, maybe self
prop_type: $prop_type,
city: $('select[name=city]').val(), // optional
zone: $('select[name=zone]').val(), // option value="0" by default
success: function(){
$('.cont-1').hide();
$('.cont-2').show();
}
});
});
It works perfectly if I manually set $prop_type = 'res';. Any ideas?
Another problem is that the pagination buttons link does not work, it just triggers the ajax script (they need to send the data, otherwise the script will restart when changing pages).
I really would appreciate any optimization to the scripts. Thanks.
You're mixing your javascript and php here.
In PHP you declare a variable with $varname, in Javascript, $ represents the jQuery operator. As such your code that says $prop_type is totally invalid since this is javascript code. You're telling jQuery to execute some functionality called prop_type which doesn't exist, and as such you're getting an error that this is undefined.
if ($('#res_prop').is(':checked')) {
var prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
var prop_type = $('#com_prop').val();
}
And change the line which reads prop_type: $prop_type, to prop_type: prop_type,
If you want to import the <div class="results"></div> container with ajax:
you should use this tested and working code:
$(document).ready(function(){
$('.search, .pagination').click(function() { // search button and change page
$prop_type = '';
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.ajax({
method: "POST",
url: "go.php",
data: {
'prop_type': $prop_type,
'city': $('select[name="city"]').val(),
'zone': $('select[name="zone"]').val()
}
}).done(function(data) {
var _html = $.parseHTML(data);
$('.cont-1').hide();
$('.cont-2').show();
$(_html).each(function(i, el) {
if (el.className == 'results') {
$('.results').html($(el).html());
};
});
});
return false;
});
});

Query not display rows only on IE

In my php class I created a method for concatenated select form (ajax call)
Now I've a strange problem because in firefox, chrome and other browsers the method
go well displaying the rows of my query select while in ie 8-9 no display rows but only a "white" window.
public function ShowCat_2( $idca2, $idca1 ) {
// for edit function
$where = "";
if(isset($idca1)){ $where .= " idcat_1='$idca1'"; }
if(isset($_POST['idcat_1'])) { $where .= " idcat_1='$_POST[idcat_1]'"; }
// query
$this->db->result = $this->db->mysqli->query("SELECT * FROM cat_2 WHERE $where");
$cat_2 = '<option value="0">Select</option>';
while($row = $this->db->result->fetch_assoc()) {
$cat_2 .= '<option value="' . $row['idcat_2'] . '"';
if($idca2 == $row['idcat_2']){ $cat_2 .= ' selected'; } // for edit fun
$cat_2 .= '>' . utf8_encode(ucfirst(strtolower($row['descr']))) . '</option>';
}
return $cat_2;
}
Can you tell me what could be the problem and how to solve?
Thanks
Take a look at the page source. There may be a PHP warning / notice in there that's breaking the HTML code.

How to split part of table into 2 columns over specific number of td's with PHP?

The site I'm working on wants data organized in a specific way. I need to split it into two columns if it's over 8 td's long. Here is my code right now. I've put it into an array as I had an idea about doing that and using the count to display data but I haven't figured out how to make that work.
$resultFound = false;
$prevWeek = -1;
$count = 0;
while($row = mysqli_fetch_array($result)) {
$adjustedWeek = dateToWeek($row['date']) - 35;
if($_GET['keywords'] != "") {
$id = search($row, $_GET['keywords']);
if($row['id'] == $id) {
if($validWeek) {
if($week == $adjustedWeek) {
include('test2.php');
}
}
else {
include('test2.php');
}
}
}
foreach($tableArray as $table) {
echo $table;
}
Here is my code for test2.php
$table = "";
if($prevWeek != $adjustedWeek) {
$table .= ('<th colspan=2>Week' . $adjustedWeek . '</th>');
$prevWeek = $adjustedWeek;
}
$table .= '<tr>';
$table .= ('<td colspan=12><a href="details.php?id=' . $row['id'] . '">'
. getGameTitleText($row) . '</a></td>');
$table .= '</tr>';
$resultFound = true;
$tableArray[] = $table;
$count++;
I need the code to do something like this:
If (all items of any week > 8)
write out 8 items to column one
then write the rest to column two
I've accounted for the total number of entries it's searching but not specific to a week, and I don't want to have to make lots of variables for that either to keep track.
How could I get the result like I want?
Warning!! the following code is to illustrate the idea only. Not tested on machine, but I think you can iron the possible error out.
pseudo code example:
$arr=array();
while($row = mysqli_fetch_array($result)) {
$arr[]['data']=$row['data'];
$arr[]['whatever']=$row['whatever'];
}
$columns=floor(count($arr)/8);
$output="<table>";
foreach ($arr as $i=>$a){
$output.="<tr>";
$output.="<td>{$arr[$i]['data']}</td>";
if ($columes>0){
for($j=0;$j<$columes;$j++){
$row_number=$i+($j+1)*8;
$output.="<td>{$arr[$row_number]['data']}</td>";
}
}
$output.="</tr>";
}
$output.="</table>";
This code will continue to add the third column if 2 is not enough.
You may still want to put a test for the end of array, so you don't get a bunch of warning when the $row_number is larger than count($arr)
This is how I ended up doing it. It's a bit "dirty" because it echo's out an extra /table and /tr at the beginning but it works for my purposes and is simpler than the code already posted. That was too complex for me
$table = "";
if($prevWeek != $adjustedWeek) {
$table .= '</tr></table><table class="vault_table">';
$table .= ('<tr><th>Week ' . $adjustedWeek . '</th></tr>');
$table .= '<table class="vault_table">';
$prevWeek = $adjustedWeek;
}
if($count % 2 == 0) {
$table .= '<tr>';
}
$table .= ('<td><a href="details.php?id=' . $row['id'] . '">'
. getGameTitleText($row) . '</a></td>');
$resultFound = true;
$tableArray[] = $table;
$count++;
The class is just for styling the table. Didn't have anything to do with how it's being layed out. other than each side of the table being 50% width of the container

how to set pagination on a lot of data rows after selection a option from the dropdown list with onchange event in php

I have a php page on which has a ajax function makerequest(serverPage, objID) , it works fine it has three links they also works fine my content comes on that page in the <div id=pageId>. in this page the third page has a dropdown list populated by mysql with on change event. in this page a lot of rows on every option so I have to decide that the data show on multiple page by php pagination class,it also works fine, but when I click on next page all the data lost due to reload the page and get the default value in the dropdown list.
Some of code content is here:
<div id="menu">
<!-- <a href="?id=AllIndiaengineringCollege" What part we want to link to onClick="makerequest('page.php?id=AllIndiaengineringCollege', 'content'); return false;" For AJAX - Load page into the div>AllIndiaengineringCollege</a>-->
<a href="?id=AllIndiaengineringCollege" onClick="makerequest('id=AllIndiaengineringCollege', 'content'); return false;" style="text-decoration:none;color: #3E5AAB" >All India Engineering College</a>
Deemed Universities
State Engineering College
</div>
</font></div>
<div id='content'style="text-align:left;width:897px; height:auto; background-color:#99CCFF;padding:1px">
<?PHP
if (isset($_GET['id'])) {
$pageId = $_GET['id'];
if ($pageId == 'AllIndiaengineringCollege') {
include("/pagination/index.php");
}
if ($pageId == 'Deemed') {
include("/pagination/state.php");
}
if ($pageId == 'state') {
include("/pagination/state.php");
}
}
?>
</div>
it works fine
my third page is
<?php
$result = mysql_query("SELECT Id,state FROM state");
echo "<select name=State id='Id' class='select' onchange='showUser(this.value)'>";
while ($nt = mysql_fetch_array($result)) {
echo ('<option value="' . $nt['Id'] . '" if($State===' . $nt['Id'] . ') echo $sel; >' . $nt['state'] . '</option>');
}
echo "</select>";
?>
</div>
<div id="state"><b><center>xxxxxxxx.</center></b>
showUser function is like here
function showUser(str) {
if (str == "") {
document.getElementById("state").innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("state").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "pagination/statelist.php?state=" + str, false);
xmlhttp.send();
}
And the pagination code is like here:
<?php
include('db.php');
include('function.php');
$q = $_GET["state"];
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 2;
$statement = "college where State= '" . $q . "'";
$url = "BTech.php?id=state&State=" . $q . "&";
$startpoint = ($page * $limit) - $limit;
?>
I think if you corrected this, it would be fine
while ($nt = mysql_fetch_array($result)) {
echo ('<option value="' . $nt['Id'] . '" if($State===' . $nt['Id'] . ') echo $sel; >' . $nt['state'] . '</option>');
}
as something like this,
while ($nt = mysql_fetch_array($result)) {
echo "<option value=\"{$nt['Id']}\"".(($State===$nt['Id'])?'selected="selected"':"") .">{$nt['state']}</option>";
}
You can't evaluate conditions that way, nested echo wont work either.
Look at this previous SO question

Categories