I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
Related
I have a simple section in which I am displaying data from the database, my database looks like this.
Now I have four buttons looks like this
When a user clicks one of the above buttons it displays this
So now when user eg select construction and next select eg Egypt' in the console and clicks buttonconfirmdisplays [855,599075], user can select multiple countries, this works as expected forconstruction ,power,oil`,
Now I want if user eg clicks All available industries button in those four buttons and next select eg Egypt and click confirm it should display
the sum of egypt total projects in construction, oil, power sector 855+337+406 =1598 and the sum of total budgets in both sectors 1136173
Here is my solution
HTML
<div id="interactive-layers">
<div buttonid="43" class="video-btns">
<span class="label">Construction</span></div>
<div buttonid="44" class="video-btns">
<span class="label">Power</span></div>
<div buttonid="45" class="video-btns">
<span class="label">Oil</span></div>
<div buttonid="103" class="video-btns">
<span class="label">All available industries</span>
</div>
</div>
Here is js ajax
$("#interactive-layers").on("click", ".video-btns", function(){
if( $(e.target).find("span.label").html()=="Confirm" ) {
var selectedCountries = [];
$('.video-btns .selected').each(function () {
selectedCountries.push( $(this).parent().find("span.label").html() ) ;
});
if( selectedCountries.length>0 ) {
if(selectedCountries.indexOf("All available countries")>-1) {
selectedCountries = [];
}
} else {
return;
}
var ajaxurl = "";
if(selectedCountries.length>0) {
ajaxurl = "data.php";
} else {
ajaxurl = "dataall.php";
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
countries: selectedCountries.join(","),
sector: selectedSector
},
success: function(result){
console.log(result);
result = JSON.parse(result);
$(".video-btns").each(function () {
var getBtn = $(this).attr('buttonid');
if (getBtn == 106) {
var totalProjects = $("<span class='totalprojects'>"+ result[0] + "</span>");
$(this).append(totalProjects)
}else if(getBtn ==107){
var resultBudget = result[1]
var totalBudgets = $("<span class='totalbudget'>"+ '$m' +" " + resultBudget +"</span>");
$(this).append( totalBudgets)
}
});
return;
}
});
}
});
Here is php to get all dataall.php
$selectedSectorByUser = $_POST['sector'];
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser ) {
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>
Here is data.php
<?php
$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);
//var_dump($countries);
$conn = mysqli_connect("localhost", "root", "", "meedadb");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) {
// array_push($data, $row);
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
// array_push($wynik, $row);
echo json_encode([ $totalProjects, $totalBudget ] );
//echo json_encode($data);
exit();
?>
Now when the user clicks All available industries btn and selects a country I get [0,0] on the console.
What do I need to change to get what I want? any help or suggestion will be appreciated,
in you dataAll.php
If you have select All available industries
you shold not check for sector because you need all sector (eventually you should check for countries )
so you should avoid the check for this condition
<?php
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = [];
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result)) {
$totalProjects += $row['SumofNoOfProjects'];
$totalBudget += $row['SumofTotalBudgetValue'];
}
echo json_encode([$totalProjects, $totalBudget]);
You can use the SQL JOIN operator, or in this case an implicit join would be cleanest:
$result = mysqli_query($conn, "SELECT * FROM construction, power, oil_and_gas, industrial WHERE construction.Countries = power.Countries AND power.Countries = oil_and_gas.Countries AND oil_and_gas.Countries = industrial.Countries");
You need the WHERE conditions so it knows how the rows of each different table are related to each other. You can shorten it a bit with aliases for the tables:
$result = mysqli_query($conn, "SELECT * FROM construction as C, power as P, oil_and_gas as G, industrial as I WHERE C.Countries = P.Countries AND P.Countries = G.Countries AND G.Countries = I.Countries");
In this case, however, I think you may want to consider changing the structure of your database. It seems like you repeat columns quite a bit across them. Perhaps these can all be in a single table, with a "type" column that specifies whether it's power, construction, etc. Then you can query just the one table and group by country name to get all your results without the messy joins across 4 tables.
The single table looks OK.
(The rest of this Answer is not complete, but might be useful.)
First, let's design the URL that will request the data.
.../foo.php?industry=...&country=...
But, rather than special casing the "all" in the client, do it in the server. That is, the last button for industry will generate
?industry=all
and the PHP code will not include this in the WHERE clause:
AND industry IN (...)
Similarly for &country=all versus &country=egypt,iran,iraq
Now, let me focus briefly on the PHP:
$wheres = array();
$industry = #$_GET['industry'];
if (! isset($industry)) { ...issue error message or use some default... }
elseif ($industry != 'all') {
$inds = array();
foreach (explode(',', $industry) as $ind) {
// .. should test validity here; left to user ...
$inds[] = "'$ind'";
}
$wheres[] = "industry IN (" . implode(',', $inds) . )";
}
// ... repeat for country ...
$where_clause = '';
if (! empty($wheres)) {
$where_clause = "WHERE " . implode(' AND ', $wheres);
}
// (Note that this is a generic way to build arbitrary WHEREs from the data)
// Build the SQL:
$sql = "SELECT ... FROM ...
$where_clause
ORDER BY ...";
// then execute it via mysqli or pdo (NOT mysql_query)
Now, let's talk about using AJAX. Or not. There were 2 choices:
you could have had the call to PHP be via a GET and have that PHP display a new page. This means that PHP will be constructing the table of results.
you could have used AJAX to request the data. This means that Javascript will be constructing the data of results.
Which choice to pick probably depends on which language you are more comfortable in.
I'm working on a script that forms a web page based on what is in my database. For his I call a java script function when the page loads and whenever the page needs to update.
Firstly I made a script that gets the information from the database, passes it to java script by echo "var region_list = ". $js_region_list . ";\n"; and then proceeded to generate the page itself which worked.
After that I tried to get this to work based on an AJAX request but this failed horribly. As it stands I get correct information from the database but it does not change the value of echo "var region_list = ". $js_region_list . ";\n"; which prevents the page from updating.
The PHP part of my script:
if(isset($_POST["campaign_id"])){
// Get variables and sanetize
$campaign_id = preg_replace('#[^0-9]#i', '', $campaign_id);
// Create planet list
$planet_list = array();
$sql = "SELECT planet_nr, size, moon FROM planets WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($planet_list, array($row["planet_nr"],$row["size"],$row["moon"]));
}
/* free result set */
mysqli_free_result($result);
}
// Create region list
$region_list = array();
$sql = "SELECT planet_id, region_id, region_type, owner FROM regions WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($region_list, array($row["planet_id"],$row["region_id"],$row["region_type"],$row["owner"]));
}
/* free result set */
mysqli_free_result($result);
}
// Convert array's for use in java
$js_planet_list = json_encode($planet_list);
$js_region_list = json_encode($region_list);
$list = array($planet_list, $region_list);
$list = json_encode($list);
echo $list;
exit();
The javascript part:
<?php
echo "var planet_list = ". $js_planet_list . ";\n";
echo "var region_list = ". $js_region_list . ";\n";
?>
var ajax = ajaxObj("POST", "campaign.php?c="+campaign_id);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "Fail"){
alert(ajax.responseText);
}
}
}
ajax.send("campaign_id="+campaign_id);
NOTE: These are just snippets of the whole script. The whole script is in the same PHP file with the PHP up above between it's tags and the java down between the script tags.
In your ajax success part, you need to just update the values of the the variables planet_list and region_list as shown below
planet_list = JSON.parse(ajax.responseText[0]);
region_list = JSON.parse(ajax.responseText[1]);
I'd like to find a way of having a single page in the root of each of my web sections to hold all of the databae queries I'm calling.
I'm using a little script .....
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fn-search-em.php'); ?>;
$("#quick-add").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
.... to do SQL searches that appear as the user is typing. Similar to this ....
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result))
{
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){
$p_mark = 'x';
}
else {
$p_mark = '';
}
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
Echos a list in the form of a JSON array back to the text box and voila, a list. However, the site I'm working on at the moment has about 20 search boxes for various reasons scattered around (user request), does this mean I have to have 20 separate php function pages, each with their own query on, or can a single page be used?
I suspect the java needs modifying a little to call a specific function on a page of multiple queries, but I'm not good with Java, so some help would be greatly appreciated.
I did initially try adding ?action= to the end of the PHP address in the Java script, hoping a GET on the other end would be able to separate the PHP end into sections, but had no luck.
You need to change <?php include('fn-search-em.php'); ?>; to <?php $action = 'mode1'; include('fn-search-em.php'); ?>;.
Then in your fn-search-em.php file, use the $action variable to determine what kind of MySQL query you make.
For example:
if ($action == 'mode1')
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
else
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'mode1' AND deleted = 'no'";
You can do this with by creating a php file with a switch statement to control what code is executed during your Ajax call:
JS:
$.ajax({url: 'ajax.php', method: 'POST', async:true, data: 'ari=1&'+formData,complete: function(xhr){ var availableTags = JSON.parse(xhr.responseText);}});
PHP:
<?php
switch($_REQUEST['ari']){
case 1:
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){$p_mark = 'x';}
else { $p_mark = ''; }
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
break;
case 2:
// another SQL Query can go here and will only get run if ARI == 2
break;
}
?>
This allows you to keep multiple AJAX handlers in the same file, you just need to pass the index for the desired handler when you make calls to the PHP file or nothing will happen.
I have this JavaScript code that is working well:
var lookup = {
"dog-black":{url:'images/dog-black.jpg'},
"dog-white":{url:'images/dog-white.jpg'},
"cat-black":{url:'images/cat-black.jpg'},
"cat-white":{url:'images/cat-white.jpg'}
};
I'm tring to generate same code dynamically using PHP to have lines as much as there in the DB, like this:
var lookup = {
<?php
$sql = "SELECT name FROM swords ORDER BY animals, colors";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '"'.$row['name'].'":{url:images/'.$row['name'].'.jpg';
}
} else {echo "No records";}
?>
};
I tried to define the php code as string using quotes or heredoc and alert the string variable, but seems like the script is not excuted
note: i'm already connected to the DB before this part of code and pass data from/to it.
Don't try to echo this out manually. What you can do is build the same structure in PHP, then use json_encode.
JSON is actually valid JavaScript code, so it will work.
Try it like this:
<?php
$lookup = array();
$sql = "SELECT name FROM swords ORDER BY animals, colors";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$lookup[$row['name']] = array('url' => 'images/'.$row['name'].'.jpg');
}
}
else {
//echo "No records";
}
?>
var lookup = <?=json_encode($lookup); ?>;
There seems to be a mistake in the echo in the while loop. You're not closing the string correctly, it is missing the closing part },. Which should look something like this:
echo '"'.$row['name'].'":{url:"images/'.$row['name'].'.jpg"},';
Form a php page I am sending some value using json.
$result = mysql_query("SELECT * FROM user_info");
$i=1;
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
if(is_array($row) && count($row)>0)
{
$res['user_name'.$i] = $row[1];
$res['user_email'.$i] = $row[2];
$res['gender'.$i] = $row[4];
$res['i'] = $i;
$i++;
}
}
echo json_encode($res);
I have no problem with this code.But in another page I want to get that data code follows
$.post(urlName, function(data) {
var obj = jQuery.parseJSON ( data );
$noOfUser = obj.i;
alert("No of user- "+$noOfUser);
for($i=0;$i<=$noOfUser;$i++)
{
$user_name = obj.user_name+$i;
$user_emai = obj.user_email+$i;
$gender = obj.gender+$i;
alert("User Name- "+$user_name);
alert("User Email- "+$user_emai);
alert("User Gender- "+$gender);
}
});
But the problem is when I am adding this obj.user_name+$i instead of simple obj.user_name it can't retrieve the data properly but I need to get those value how to do that?
What you are trying to do attempts to get the user_name member of obj and appending the value of $i. Since user_name is not defined, the script fails.
This is because in javascript to access a member of an object using a dynamically generated key you must use the [] accessor, so in your case, the following example should work.
$user_name = obj['user_name' + $i];