Dynamically creating array elements

Asked

Viewed 223 times

-3

The form below on a page a.php submits to a page b.php.

<form method="post" action="b.php">
   <select name="zzz" id="zzz">
    <option value="id1" label="aaa">aaa</option>
    ..................
    ..................

On the page b.php I have the following code created manually that returns the label of the option selected from the page a.php, i said the label and not the value.

<?php

  $options = array();

  $options["id1"] = "aaa";
  $options["id2"] = "bbb";
  $options["id3"] = "ccc";

  $label = $options[$_POST['zzz']];

  echo $label;

You can create these lines

 $options["id1"] = "aaa";
 $options["id2"] = "bbb";
 $options["id3"] = "ccc";

dynamically from a select being id1, id2 .... and aaa, bbb ... the values in the database table.

Is there any way to create these lines and work as manually created? That is, instead of typing in the code id1 = "aaa" do something like $row["id"] = "$row["xxx"]

  • That? https://repl.it/J8L2/1

  • 1

    Related: https://answall.com/a/54561/14262

  • Or, https://repl.it/J8L2/3 I didn’t quite understand your question Leo, but that’s the way to go

  • I would suggest creating the options using the same data source that generates the <option> in order to update the data in one place.

  • I didn’t get it right. Do you want to assemble the options from the database data? That’s it?

  • @Marceloboni, I did not comment in the sense of denigrating, as may have been interpreted by the comments that have been removed, I think I expressed myself badly. I only meant that if you did not understand the question you could have simply asked for more information and then indicated related information. Even because you are part of the people I cherish on this site!

  • 1

    downvoto is easy to give, it is difficult to explain why of the given downvoto. Worthy of pity this type of behavior. It does not add anything useful to the site or to who asked the question

  • Just to clarify, I never downvoted your question, but I still found it a little confusing the way it was put. I couldn’t understand its purpose, really Leo... Perhaps it would explain its initial difficulty....

  • @Marceloboni got a solution, see the answer

Show 4 more comments

2 answers

3


Despite the downvotos, I made a point of reopening this post and show a solution.

On the page a.php create the file optionsArray.php

$servidor = "localhost";
$usuario = "Usuario";
$senha = "SENHA";
$dbname = "NOME_DB";

$mysqli = mysqli_connect($servidor, $usuario, $senha, $dbname);


$query = "SELECT id_regional, regional FROM t_regional ORDER BY regional";
$resultado=$mysqli->query($query);


$filename="optionsArray.php";

if (!file_exists($filename)) {

    $linhas="";

    while ($row = mysqli_fetch_assoc($resultado)){

    $linhas .= "\n".'$options["'.$row['id_regional'].'"] = "'.$row['regional'].'";';

    }

    $linhas ="<?php \n".$linhas."\n ?>";

    file_put_contents($filename, $linhas);

}

On the page b.php include the archive optionsArray.php created on the page a.php

$options = array();

include_once("optionsArray.php");

$label = $options[$_POST['cbx_regional']];

echo $label; 

The two pages above could merge into one without problems.

Question: why you want to create this file dynamically?

Answer: Anderson Carlos Woss' answer is certainly the most obvious.

However I do not know if I understood well the comment in the accepted reply of this post target HTML option label Instead of its value in PHP? what it says (google translation) "Okay, this works in a way. BUT, about whether there are 100 options on the page? Do I have to add $options ["music / three"] = "somename"; $ Options ["music / four"] = "somename"; For each one? Or is there another way to do this?".

That is the reason for the question and that is the reason for my reply.

Summary of the opera: The usefulness of this only the American could explain :)

NOTE: It is not clear where this information would come from, but I believe they are from a database.

  • 1

    Usually when used select, the attribute value receives the column value id and the label a record-related value that is human-readable (e.g.: name). Then in the file b.php, just search the database for id and verify their name.

2

Supposing we have the table browsers in the database:

id | name
---+------------------
1  + Google Chrome
---+------------------
2  + Firefox
---+------------------
3  + Opera
---+------------------
4  + Safari
---+------------------
5  + Internet Explorer
---+------------------

We can generate the following HTML with PHP:

<?php

//...

$result = mysqli_query($mysqli, "SELECT `id`, `name` FROM `browsers`");

echo "<select name='browser'>";

while ($row = mysqli_fetch_assoc($result)) {
    echo "<option value='{$row['id']}' label='{$row['name']}'>{$row['name']}</option>";
}

echo "</select>";

The HTML output will be:

<select name='browser'>
    <option value='1' label='Google Chrome'>Google Chrome</option>
    <option value='2' label='Firefox'>Firefox</option>
    <option value='3' label='Opera'>Opera</option>
    <option value='4' label='Safari'>Safari</option>
    <option value='5' label='Internet Explorer'>Internet Explorer</option>
</select>

When the form is submitted, in PHP you can recover the attribute value value selected. This value is the id of the selected table record browsers, then, to get the name of the selected browser, just select the respective database record:

<?php

// ...

if ($stmt = mysqli_prepare($mysqli, "SELECT `id`, `name` FROM `browsers` WHERE `id` = ?")) {

    mysqli_stmt_bind_param($stmt, "i", $_POST["browser"]);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $id, $name);
    mysqli_stmt_fetch($stmt);

    echo "O navegador selecionado foi: ", $name;

}

The complete code tested was:

<form action="" method="post">
    <select name="browser">
        <?php

            $mysqli = mysqli_connect("localhost", "root", "", "sopt");

            $result = mysqli_query($mysqli, "SELECT `id`, `name` FROM `browsers`");

            while ($row = mysqli_fetch_assoc($result)) {
                echo "<option value='{$row['id']}' label='{$row['name']}'>{$row['name']}</option>";
            }

        ?>
    </select>
    <button>Enviar</button>
</form>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if ($stmt = mysqli_prepare($mysqli, "SELECT `id`, `name` FROM `browsers` WHERE `id` = ?")) {

        mysqli_stmt_bind_param($stmt, "i", $_POST["browser"]);

        mysqli_stmt_execute($stmt);

        mysqli_stmt_bind_result($stmt, $id, $name);

        mysqli_stmt_fetch($stmt);

        echo "O navegador selecionado foi: ", $name;

    }

}

?>
  • Your answer is certainly the most obvious. I do not know if I understood the comment in the accepted reply of this post https://stackoverflow.com/questions/18411463/target-html-option-label-instead-of-its-value-in-php that says okay this Works in a way. BUT how about if there are 100’s of options on the page? do I have to add $options["music/three"] = "somename"; $options["music/four"] = "somename"; for Every single one? Or is there Another way to do this ? Before that I wanted to find a solution to my question.

  • That’s the question. You don’t need to define these variables. They are available in the database, just access it, regardless of how many records are.

  • But the American doesn’t want to connect them all?

  • If the data of select comes from the database, this is the solution. If they do not come, it simply does not make sense this relationship with the label. The value that will be used should always be in value. At most it is possible to create this relationship with Javascript, but that is on the client side.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.