PHP - Fill pulldown with array results from web service method - php

I currently have a web service (C#) that returns an array of strings to my client in PHP.
I want to fill a pulldown with the string elements in the array results.
With the following code, no items appear in the pulldown.
<select name="name-list" id="name-list" class="pulldown" onchange="exportName();" >
$client = new SoapClient("http://localhost/MyService.asmx?wsdl", array('features' => SOAP_SINGLE_ELEMENT_ARRAYS));
$res = $client->GetServiceArray()->GetServiceArrayResult;
$array = (array)$res->ArrayOfString;
foreach($array as $val)
{
echo "<option value=\"" . $val . "\">" . $val . "</option>\n";
}
?>
I have also done var_dump($res) to make sure the web service is returning the data. I can confirm that the values show in the page source.
It seems to be doing nothing on this line:
$array = (array)$res->ArrayOfString;
Is there an alternative way of doing this?
Please can I have some advice on how to make the items appear.
Thank you.

It should be
foreach($array as $val)
{
echo "<option value='$val'>$val</option>";
}

Most likely you need to do this
echo "<option value=\"" . $val . "\">" . $val . "</option>\n";
And don't forget to escape $val, because if there are any quotation characters inside, they will break your HTML. You can use
$val = addslashes($val);

Can it be $client->GetServiceArray()->GetServiceArrayResult is actually a function?
It should be $client->GetServiceArray()->GetServiceArrayResult() then.
In any way you should first check, if $res does contain any data: var_dump($res);

Related

Updating select tag from database with multiple values

I have a table named 'item' in the database which has different columns, one of them named 'size' has two values separated by comma, i.e Medium, Large. Now When I'm retrieving those values to show in my 'select' tag it shows them together, I tried using explode(); but I'm messing up with its behavior. I have attached the pictures of the table and the resulted data inside my site along with the code.
The while loop is implemented above, this is only the 'Size:' part
Size :
<?php var_dump($row["item_size"]);
$arr = $row["item_size"];
$exp = explode("," , $arr);
var_dump($exp);
?>
<select name="product_size">
<?php
echo "<option value='".$row["item_size"]."'>".$row["item_size"]."</option>";
echo "</select>";
?>
You need to loop through the size array right after explode.
$arr = $row["item_size"];
$exp = explode("," , $arr);
echo "<select name='product_size'>";
foreach($exp as $key=>$val) {
echo "<option value='" . $val . "'>" . $val . "</option>";
}
echo "</select>";
Working Demo

How do I use quotation marks properly when echoing properties and attributes through PHP and SQL)?

while ($row = $arr_result ) {
echo "<option value='" . $row['fallacytype'] . "'>" . $row['fallacytype'] . "</option>";
}
I am trying to create a and menu in html by using the string values in my SQL table.
I've confirmed that the rest of my code (not shown here, but can be provided if needed to diagnose), is working. The only thing that goes wrong is that my loop up there becomes infinite (i know this because it creates infinite sql value).
I've looked up and tried all the variations of quotation marks to no avail.
I've checked in w3shool.com, and other video tutorials that my loop syntax is correct.
It seems that the $row variable is not incrementing or moving on to the next value in the loop for some curious reason.
Thanks in advance.
You have to loop via following way for all the elements:
foreach($arr_result as $row) {
echo "<option value='" . $row['fallacytype'] . "'>" . $row['fallacytype'] . "</option>";
}

Combine function that populates `select` elements with function that pre-selects options matching db values

I want to modify function checkSelectedOption so that I don't have to hardcode the array every time it's called.
The 1rst function pre-selects the option matching the information in the db, but it uses hardcoded arrays to populate select elements. The 2nd function creates arrays from db values and dynamically populates select elements. How can I combine these two functions so that I can populate select elements dynamically, and then pre-select the option matching the information in the db?
Function checkSelectedOption populates the element with the values specified in array "$options", and then pre-selects the option matching the information in the "customer_info" table of the db. This function currently requires that the arrays be hardcoded, and I want to replace this part of the function with the method from function printSelectOptions which uses arrays created from db values.
Function printSelectOptions populates select elements from values fetched from the db. It does this by creating an array with the values in the column fetched from the "form_fields" table.
Function checkSelectedOption
function checkSelectedOption($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
}
}
try {
$stmt = $conn->prepare("SELECT * FROM customer_info WHERE user_id = :user_id");
$stmt->bindValue(':user_id', $user_id);
$stmt->execute();
} catch(PDOException $e) {
echo $e->getMessage();
}
$row = $stmt->fetch();
To call function
<select name="first_name">
<?php
// Populates the element with values from array $options
$options = array("John"=>"John", "Robert"=>"Robert");
$selected = $row['first_name'];
echo checkSelectedOption($options, $selected);
?>
</select>
Function printSelectOptions
function printSelectOptions($dataArray, $currentSelection, $fieldname) {
$output = '';
foreach ($dataArray as $key => $value) {
// Only add to array if row has value
if ($value[$fieldname] !="" && $value[$fieldname] !="Null") {
$output .= '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . str_replace('_', ' ', $value[$fieldname]) . '</option>';
}
}
return $output;
}
try {
$stmt = $conn->prepare("SELECT * FROM form_fields");
$stmt->execute();
} catch(PDOException $e) {
echo $e->getMessage();
}
$rows = $stmt->fetchAll();
To call function
<select name="first_name">
<?php
// Dynamically populates element with array created from column first_name
echo printSelectOptions($rows, $currentSelection, 'first_name');
?>
</select>
#metal_fan, I'm not sure what you're referring to, can you elaborate a
bit?
600 chars won't be enough, I guess.
How can I combine these two functions so that I can populate select
elements dynamically and then pre-select the option matching the
information in the db?
You have to fetch the data you need then compare it against a value "inside" selectbox inside a loop (or it would be a hell).
PHP itself is meant to be used as a template engine. That means, people should use it as a template engine - Don't print/echo html tags, inject php "things" instead.
All what you're doing now doesn't make sense at all.
The common solution is to create a helper function that does calculation.
Remember, one function should only do single task. If you have several ones, create a function for each one.
UPDATE
Well, I'm kinda confused even more now, after your edit.
// Assume that array we got from the table looks like:
$array = array('John' => 'John', 'Dave' => 'Dave', 'Jason' => 'Jason');
$__AGAINST__ = 'Jason'; // <-- VERY IMPORTANT
function is_selected($expected, $actual){
if ( $expected === $actual ){
print 'selected="selected"';
}
}
?>
<select>
<?php foreach($array as $key => $val):?>
<option value="<?php echo $key; ?>" <?php is_selected($key, $__AGAINST__); ?>><?php echo $val; ?></option>
<?php endforeach; ?>
</select>
$__AGAINST__ you would take from configuration or something like that. This is what you're comparing against.
Now replace $__AGAINST__ = 'Jason'; with $__AGAINST__ = 'Dave'; You see how it works? The core idea is to iterate over $array and compare $key against something. Nothing more.
UPDATE 2
I guess you got an idea how "select against" works. But you didn't understand what I've told you at all :( Look at this:
$output .= '<option ' . is_selected($key, $__AGAINST__) . ' value="' . $key . '">' . str_replace('_', ' ', $value[$fieldname]) . '</option>';
You're keep making the same mistake again and again. PHP itself is meant to be used as a template engine. You should avoid printing/echoing HTML tags. Why? What if you decide to replace that select with another element (say Jquery ComboBox plugin). What happens then? You would have to re-factor the "generation" logic itself as well as a presentation. Sounds so bad. Why sounds bad? This is because presentation should be totally decoupled from application/generation logic. Why should be decoupled? Flexibility, Maintainability would answer this question, I guess.
Keep your templates as dumb as possible They should NEVER do any calculations directly. If you want to calculate something within a HTML template, then define a function somewhere in bootstrap.php (or the like), but not inside a markup itself.
PHP is meant to be used as a template engine. But what does it really mean?
This means (we are not in Perl/Python), you should ALWAYS avoid code like this one:
$ouptut = '<option>' . $foo . '</option>';
echo '<table>';
echo '<tr>';
echo '<td>' . $bad . '</td>';
echo '</tr>';
But write something like this instead:
<select>
<option><?php echo $foo; ?></option>
</select>
Keeping this thing in mind, you would keep your HTML things totally decouple from PHP parser. Which is great for future maintains.

Dynamically setting the selected option in a HTML drop down list - PHP

I am aware there are examples out there that hover around the issue of dynamically setting the selected tag in a HTML option tag, but I am hitting a pretty difficult issue of break statements and quotations in what I am trying to accomplish.
while($info = mysql_fetch_array($companydesc))
{
$output3 .= '<option value="'. $info['company_code'] . if ($result['company']==$info['description']){echo 'selected=\"selected\"'} . '">' . $info['description'] . '</option>';
}
echo $output3;
The error that I receive is a unexpected T_IF on the line with the if statement. Is it not legal to put an if statement in there? Or is it a matter of doing proper breaks? Any help would be greatly appreciated (and hopefully the formatting for the code worked)
Use a ternary statement:
while($info = mysql_fetch_array($companydesc)) {
$output3 .= '<option value="'. $info['company_code'].'"'.($result['company']==$info['description'] ? ' selected=\"selected\"' : '') . '>' . $info['description'] . '</option>';
}
echo $output3;
yeah, it is illegal, my suggestion is:
while($info = mysql_fetch_array($companydesc))
{
if($result['company']==$info['description'])
{
$output3 .= '<option value="' . $info['company_code'] . '" selected = selected>' . $info['description'] . '</option>';
}
else
{
$output3 .= '<option value="' . $info['company_code'] . '">' . $info['description'] . '</option>';
}
}
echo $output3;
Trying to fix everything with an individual solution in the way that you originally intended to with stuff like
while($info = mysql_fetch_array($companydesc))
is, I feel, one of the big things that is holding php back and eventually makes the code extremely difficult to maintain, although it's very easy on the learning curve.
This function takes an optional selected parameter and will build out your select box. This is much much better than doing every single select box for every query with its own custom code.
There might be a syntax error in here, but generally,
function selectBox($array, $selected=false){
foreach($array as $name => $value){
$options .= '
<option value=" . $name . '"'
. ($selected != false && $selected == $value) ? 'SELECTED' : ''
. '>".$name."</option>";
}
}
Worth mentioning that select box is requiring you to pass a predefined array of key=>value pairs, so you'll need to have an additional helper function (you can't just pass it your database return)
Also probably worth mentioning is that using mysql_fetch_array($companydesc) is not abstracting the database level at all. Down the line, code like this will prohibit a migration to something like Postgres or a different database system entirely.

Loading table column names with spaces with ms sql in php

I am using php to connect to my ms sql server. I am using php 5.3, using the microsoft database dll to connect. The problem i have is that in my database, i have tables wich there column's names have blank spaces, mean there is a table called bills whit a column named "Shipper Code" or "Shipper name"... something like that... i want to know how i can read the rows using fetch_object
while($row = sqlsrv_fetch_object($stmt))
{
echo "<li>" . $row->Code . $row->MasterId . "</li>";
echo "<li>". $row->Shipper Code . "</li>"; <== HERE HOW I MUST PUT SHIPPER CODE?
}
Do i must use () or {} or []...
thank you in advanced!
You should avoid the usage of spaces in column or object names. If you wish to separate the strings then use an underscore _ instead. This will retain the readability and ensure that the item can be accessed properly.
Other than that you can use the following:
while($row = sqlsrv_fetch_object($stmt)) {
$results[] = $row;
echo "<li>" . $results['Code'] . $results['MasterId'] . "</li>";
echo "<li>". $results['Shipper Code'] . "</li>";
}
I've got the answer. I only need to use "{" and "}". Something like this
while($row = sqlsrv_fetch_object($stmt))
{
echo "<li>" . $row->{"Num"} . $row->{"MasterId"} . "</li>";
echo "<li>". $row->{"Shipper Code"}. "</li>";
}
Thanks for all your help.

Categories