I have 2 drop downs and I'm using the switch to populate the second after something has been selected in the first. It's mostly just an experiment because the jquery thing i had doing it before seemed really slow. If anyone has a better, faster way of doing this, I'm all ears. But I still want an answer to this because it's just irritating me now.
The first drop downs onchange="chngprog(this)" calls this function
function chngprog(facility)
{
if(facility.id == 'facilityview'){
var select = document.getElementById('programview');
} else {
var select = document.getElementById('program');
}
var testid = facility.value;
switch(testid){
<?php global $__CMS_CONN__;
$sqlqry = "SELECT * FROM facility_db";
$stmt = $__CMS_CONN__->prepare($sqlqry);
$stmt->execute();
$listfacility = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($listfacility as $case)
{
echo "case ".$case['id'].":\n";
echo "select.options = '';";
$boom = explode(";", $case['programs']);
foreach($boom as $program)
{
echo "select.options[select.options.length] = new Option('$program', '$program');\n";
}
echo "break;\n";
}
?>
}
}
The php creates all the cases from the database, as there are 50+, probably not helping the speed factor.
The if statement at the top is to determine which set of drop downs it's looking at, as there are 2 sets that do the same thing, but for different purposes.
The problem is getting the switch to hit a case. I've put alerts around to see what happens, and all the values are right, but it never hits a case unless is specify the number. If i put switch(20) it hits case 20 and adds the options to the second drop down just as it should.
So why isn't the switch evaluating the variable I put in?
Is facility.value a string? Try
var testid = parseInt(facility.value, 10);
Your testid is probably a string and your case statements are expecting integers.
Try:
switch (parseInt(testid)) {
...
You may want to put your values between ', like this:
echo "case '" . $case['id'] . "':\n";
If you don't, you will have to cast the variable to int before comparing with any value (I'm supossing also that id will never return anything different than a number).
Related
I got a little problem here with my SQL query...
I debugged where the problem resides and realized that the varchar/text column seemed to stop my php function.
Here is my code:
$queryTest = mysqli_query($link, "SELECT dos_nom,dos_id FROM dossier");
while($dataTest = mysqli_fetch_assoc($queryTest)) {
if($dataTest['dos_id'] == $myparameter) {
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" value="'.$dataTest['dos_nom'].'" selected>'.$dataTest['dos_nom'].'</option>';
}
}
The problem is in the value $dataTest['dos_nom']. Without which my query works (it prints the page normally), but I don't know why. With it, it doesn't work (it prints the top of the page, and nothing from/after my php function)...
To be precise, i use it in an ajax function.
Thanks in advance!
EDIT: I tried to print only 1 row from 'dos-nom', it works! But i when try to print out more than 1 row, the function stops!
My code:
$queryTest2 = mysqli_query($link, "SELECT * FROM dossier");
while($dataTest2 = mysqli_fetch_assoc($queryTest2))
{
$test[0] = $dataTest2['dos_nom'];
}
if($dataTest['dos_id'] == $dos_id)
{
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" >'.$test[0].'</option>';
}
It prints only the last line this way. If i put a WHERE in the query it will stop the function, so i don't know what to do!
ANSWER:
É / À were in my database, i replaced them by E and A, problem solved!
try to use addslashes() function like
addslashes($dataTest['dos_nom'])
maybe the value contains some backslash or some junk characters which may be breaking your code
I see nothing wrong with your code, except the logic - you only output when option is selected.
So as you said (it prints nothing)
Let's try print something:
$queryTest = mysqli_query($link, "SELECT dos_nom,dos_id FROM dossier");
while($dataTest = mysqli_fetch_assoc($queryTest)) {
$selected = ($dataTest['dos_id'] == $myparameter)?' selected ':' ';
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" value="'.$dataTest['dos_nom'].'" '.$selected.'>'.$dataTest['dos_nom'].'</option>';
}
So let me explain my problem, lets assume that I run query like so:
$myquery = sql_query("SELECT name FROM table WHERE name='example' LIMIT 0,1");
Now.. I want to store the retrieved name into a variable so I would do something like this:
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
print"Name: $row_name";
}
$stored_name = $row_name;
NOTE: transfer_row() is just a function I wrote that takes $myrow['name'] and stores it in $row_name, for easier reference
Now, all is fine at this stage, here is where it gets interesting. Note that at this stage I still have a name assigned to $row_name. Further down the page I run another query to retrieve some other information from the table, and one of the things I need to retrieve is a list of names again, so I would simply run this query:
$myquery = sql_query("SELECT name, year FROM table WHERE DESC LIMIT 0,10");
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
$year = $row_year;
$link = "/$year";
print "<li style=\"margin-bottom: 6px;\">$row_name\n";
}
Now, I want to write an if statement that executes something if the $row_name from this query matches the $row_name from the old query, this is why we stored the first $row_name inside the variable.
if ($row_name == $stored_name){
// execute code
}
However as most of you know, this WONT work, the reason is, it simply takes $stored_name again and puts the new $row_name into $stored_name, so therefore the value of the first $row_name is lost, now it is crucial for my application that I access the first $row_name and compare it AFTER the second query has been run, what can I do here people? if nothing can be done what is an alternative to achieving something like this.
Thanks.
EDIT, MY transfer_row() function:
function transfer_row($myrow) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["row_$key"] = $value;
}
}
}
Without you posting the code for the function transfer_row, we won't be able to give you an answer that exactly matches what you request, but I can give you an answer that will solve the problem at hand.
When matching to check if the names are the same, you can modify the if statement to the following.
if ($row_name == $myrow['name']){
// execute code
}
What I suggest you do though, but since I don't have the code to the transfer_row function, is to pass a second variable to that function. The second variable will be a prefix for the variable name, so you can have unique values stored and saved.
Refrain from using the transfor_row function in the second call so your comparison becomes:
if ($myrow['name'] == $row_name)
If you need to use this function, you could do an assignment before the second database call:
$stored_name = $row_name;
...
transfer_row($myrow);
In your first query you are selecting the name field WHERE name='example' , Why are you quering then? You already have what you want.
Your are querying like:
Hey? roll no 21 what is your roll no?
So perform the second query only and use the if condition as :
if ($row_name == 'example'){
// execute code
}
Does it make sense?
Update
//How about using prefix while storing the values in `$GLOBAL` ??
transfer_row($myrow, 'old_'); //for the first query
transfer_row($myrow, 'new_'); //for the second query
function transfer_row($myrow, $prefix) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["$prefix"."row_$key"] = $value;
}
}
}
//Now compare as
if ($new_row_name == $old_row_name){
// execute code
}
//You'll not need `$stored_name = $row_name;` any more
I have the function getDistance(). The function findDistance() inside the while loop, calculates the distance between 2 users, by using coordinates (latitude-longitude), and returns to var $djson the distance in meters. $distance is a string committed by the user for first time and $user_old["distance"] is a string which is called from a database in $query. I wanted to be able in $matched_names, to save all the names of the users from my database, for who the condition inside if() is true, regarding the sum of the distance of the new user who commits his data and the old ones inside the database. The problem is that $matched_names saves the first name which is called from the database and for as many times the loop goes on without even considering the if() restriction. For example if the first name called in $user is "Mike", and $user has 5 rows then the output will be: Mike,Mike,Mike,Mike,Mike.
I suppose that i have made some mistake in the way things work inside while..
<?php
public function getDistance($uuid, $name, $distance, $latstart, $lonstart, $latend, $lonend, $gcm_regId) {
$query = sprintf("SELECT uid, gcm_regid, name, distance,latstart, lonstart, latend, lonend FROM user_demand WHERE latstart='%s' AND lonstart='%s'",
mysql_real_escape_string($latstart),
mysql_real_escape_string($lonstart));
$user = mysql_query($query);
$no_of_rows = mysql_num_rows($user);
$user_old = mysql_fetch_assoc($user);
while( $user_old = mysql_fetch_assoc($user)) {
$djson = $this->findDistance($latend,$lonend,$user_old["latend"],$user_old["lonend"] );
if ($user_old["distance"] + $distance >= $djson) {
$match = $this ->df->addUserMatch($user_old['gcm_regid'],$user_old['name'],$gcm_regId,$name);
$matched_names = array_fill(0,$no_of_rows,$user_old['name']);
$matched_gcmz = array_fill(0,$no_of_rows,$user_old['gcm_regid']);
}
}
$registatoin_ids = array($gcm_regId);
$message = array("names" =>$matched_names,"gcm" => $matched_gcmz);
$result = $this ->gcm->send_notification($registatoin_ids, $message);
}
?>
What i usually do is, when I'm going to write something that is complicated, is to get it to working without being in a function then break it down into functions.
It is less confusing and easier to troubleshoot problems that way.
It is kind of hard to tell what it is doing since you didn't post your other function and the if statement relies on the output of that function.
Offhand, it could be this line where you are using the $name and $user_old['name']
$match = $this ->df->addUserMatch($user_old['gcm_regid'],$user_old['name'],$gcm_regId,$name);
I think you would want it to match each other. Like if $name = $user_old['name'] then add it, if not, do something else.
This question isn't really about what's wrong with some code. It's about how to go about doing something. This is why no code is posted. Is there a way to run a specific MySQL query based on what's selected in an HTML select box? Does a form have to be used here or is there another way?
I have now added the code and have tried using the switch statement way; however, the two textboxes are not being populated. Any ideas? The text in between the dashed lines isn't really in the code but just a placeholder for the purpose of the question.
<?php
---db login info here---
switch($_GET['string'])
{
case "another string":
$query = mysql_query("SELECT field1 FROM table1 WHERE id = '1'");
$row = mysql_fetch_row($query);
break;
}
echo "<script type='text/javascript'>";
echo "document.getElementById('textbox').value = '$row[0]'";
echo "document.getElementById('textbox2').value = '$row[1]'";
echo "</script>";
?>
Yes, its possible. You can use forms or javascript URL call or ajax to perform this operation.
What you need to do it, based on the value selected in the selectbox, you need to run the sql statement in a switch case or if conditions.
The best option would be switch case for these kind of operations.
Hope this helps.
There are more ways to do this
put the MySQL in the value of each option (VERY USEFUL WHEN YOU DON'T WANT YOUR DATABASE ANYMORE) <-- DON'T DO THIS ITS VERY UNSAFE
mysql_query($_GET["selectbox"]);
make a array with MySQL queries and put the key in the value of each option
$mysqlqueryarr = array("SELECT banana FROM monkey","UPDATE monkey SET mouth='open'");
mysql_query($mysqlqueryarr[$_GET["selectbox"]]);
make a switch what executes the queries
switch($_GET['selectbox']){
case 'monkey':
mysql_query("SELECT monkey FROM zoo");
break;
case 'dog':
mysql_query("SELECT dog FROM farm");
break;
}
make a superlong if(){ ... }else if(){ ... }else if(){etc. what looks for what there is in the selectbox and executes SQL
if(isset($_GET['selectbox']) && $_GET['selectbox'] == "foood"){
mysql_query("UPDATE wishlist SET needs = needs");
} else if(isset($_GET['selectbox']) && $_GET['selectbox'] == "satisfied") {
mysql_query("UPDATE wishlist SET needs = NULL");
}
That's every way I know,
I'm using Drupal's db_fetch_array to fetch rows from my db_query. However, every row returned is equal to NULL. Typing the query into PHP myadmin works, so I have no idea whats going on. db_num_rows returns the number of rows as well. Here is the code:
if(count($rebuild_ids))
{
$ids=implode(",",$rebuild_ids);
$type_stmt = "SELECT * from {" . ItemType::$type_table_name . "} where id IN ($ids)";
$new_items=db_query($type_stmt);
if(!$new_items || db_num_rows($new_items) == 0)
{
return;
}
while($row = db_fetch_array($new_items));
{
if ($row!=NULL)
{
echo "I work!"
$game_items[] = $row['id'];
ItemInstance::$nid_to_item_type_code[$row['nid']] = $row['id'];
}
}
}
However, it never gets into the third if statement (i.e. never echos "I work!") Any ideas?
Friendly advice: Drupal has a coding standards http://drupal.org/coding-standards -- it helps to keep them. This error would have been a lot more obvious that way....
Also putting variables in a query is a huge no-no see http://drupal.org/writing-secure-code
$row is not NULL by definition, otherwise it wouldn´t even reach the third if statement.
There is no need to check if $row contains information, the while loop already takes care of that, but if you want to check anyway, use something like empty($row) or count($row) > 0; don´t compare an array with NULL.
The checking is completely unnecessary though...
K figured it out. It was the semicolon after the while loop!