ghicks — 2012-09-27T05:25:15-04:00 — #1
I'm fairly new to creating functions and am wondering if this shouldn't actually be written some other way. Basically what I am trying to do is create a list of items to populate a drop down list from a database. This list is used in multiple locations on a single form (and in multiple forms for that matter) so I thought it would be best to write this as it's own function. I am not returning any value, and I am not sure if it is in my code for the function itself, or someplace else.
Here is the code for the function:
// Build the ALL Jobs drop down list
// First clear the returned variable of old data
$AllJobs = '';
// Connect to DB and retrieve records
$GetSQL = 'SELECT Job_Number, Company_Name FROM Jobs ORDER BY Job_Number';
$GetResult = mysqli_query($db_server, $GetSQL) or die("Unable to run query: " . mysqli_error());
// Set the first/default value
$AllJobs = "<option value=\\"None\\">None</option>";
// Now loop through the results and populate the variable
while ($GetRow = mysqli_fetch_array($GetResult))
$JobNum = $GetRow['Job_Number'];
$DropInfo = $JobNum . " ~ " . $GetRow['Company_Name'];
$AllJobs .= "<option value=\\"$JobNum\\">$DropInfo</option>";
In my form I make a call to the function at the top of the file, then echo $AllJobs where I want the results to be displayed (i.e. between the <select> statements. I know the database calls are working, and the proper records are being pulled from the db.
Any guidance is greatly appreciated, even if that guidance starts with "What the heck are you thinking?!?!?!) :nono:
lampcms_com — 2012-09-27T07:07:36-04:00 — #2
Hard to tell. I would suggest you temporarily add print_r($GetRow); statements inside your loop to see if $GetRow has any data in it.
cpradio — 2012-09-27T07:45:18-04:00 — #3
Show me this code, because if I had to guess you have something like this:
<?php GetAllJobs(); ?>
<?php echo $AllJobs; ?>
Where you really need to do either of the following:
<?php $AllJobs = GetAllJobs(); ?>
<?php echo $AllJobs; ?>
<?php echo GetAllJobs(); ?>
ghicks — 2012-09-28T01:58:21-04:00 — #4
Your solution was spot on, I wasn't properly calling the function. But then it caused another problem with my connect or die command for the database link. I commented out the "or die" part and it functions properly (using your first suggestions ($AllJobs = GetAllJobs(); then echo $AllJobs)
Now to figure out how to deal with an error if the database is not properly connected to. I'm considering rewriting this slightly in OOP, but I'm even less versed there and that would require quite a bit of other "re-thinking" for the rest of this project so I'm not exactly sure how I will proceed just yet.
Thanks for the fix!!!