I am trying to learn php and now I am stucked with one thing.
I have the code like this:
<select name = "Option1" id ="Option1">
<option value="0">Option1</option>
<?php
include ("db_connect.php");
$option1 = $pdo->query("SELECT * FROM options");
while($row = $option1->fetch(PDO::FETCH_ASSOC)){
echo '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
}
?>
</select>
Which is select element with options from database.
But I need 5 of them and copying this piece of code 5 times just doesn't make sense, or am I wrong?
I tried something like this:
function renderSelect()
{
for ($a = 0; $a < 5; $a++){
echo '<select>
<option value="0">Option ' . $a . '</option>
' . renderOptions($a) . '
</select>';
}
}
function renderOptions(){
include ("db_connect.php");
$option1 = $pdo->query("SELECT * FROM options");
while($row = $option1->fetch(PDO::FETCH_ASSOC)){
echo '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
}
}
And then just call the renderSelect, but it's not working how expected.
Can you please give me little advice what to do here?
Thanks a lot I appreciate it!
Try to use return in your second function. If you echo it in the second function, it will add the echo output to the beginning, where you called the function. You create a String, where you add all your options to it and then return that string.
function renderOptions(){
include ("db_connect.php");
$option1 = $pdo->query("SELECT * FROM options");
$string = "";
while($row = $option1->fetch(PDO::FETCH_ASSOC)){
$string .= '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
}
return $string;
}
And another point to mention, you are calling renderOption function and passing $a to a function, which takes to parameter.
Related
I have a select (dropdown) box. On each button click, I'd like it to load previously saved position. My code is:
<select name="myVariables" style="width:150px">
<?php
foreach ( $variables as $var ) {
echo "<option value=\"" . $var . "\"". $var . " </option>";}
?>
</select>
I have a variable $previouslySelected, and every time the button is clicked, this variable can change. I'd like to also change the currently selected option in the select box to the same value. I've tried with:
echo "<option value=\"" . $var . "\" <?=$previouslySelected==$var ? ' selected=\"selected\"' : '';?\>>". $var . " </option>";}
but this doesn't seem to work.
Also, I've tried this but it only works the first time.
How do you submit the form. With GET or POST?
With GET, than you must take the submitted value in this way:
$previouslySelected = isset($_GET['myVariables']) ? $_GET['myVariables'] : '';
Otherwise with POST:
$previouslySelected = isset($_POST['myVariables']) ? $_POST['myVariables'] : '';
In PHP 7 you can also do:
$previouslySelected = $_POST['myVariables'] ?? '';
EDIT: Write your echo more readable.
$selected = ($previouslySelected === $var) ? ' selected="selected"' : '';
echo '<option value="' . $var . '" ' . $selected . '>' . $var . '</option>';
I'm running a script that fetches a row from a MySQL table and is supposed to then pass certain variables from that row to the next page to be used in a form that allows user updating.
Here's the excerpt from the script that is trying to pass the variables to the next page:
if ($row['home_score'] == '0' && $row['away_score'] == '0') {
echo '<td><img src="images/report_icon.png" alt="Report Score" /></td>';
}
If I omit everything after "&game_id=" in the href, it displays fine. However, once I start adding the variables, it cuts off the function and stops displaying the page.
Am I doing something simple wrong with the syntax? I've tried playing around with different ways to write it, but to no avail. Do I need to utilize a http_build_query() to make this work?
Here's the entire script code if you need more info:
<?php
// Connect to the database:
require ('../mysqli_connect.php');
// Make the query for games from the schedule database and determine the game location:
$q = "SELECT tl.game_date, tl.game_time, tl.away_team, tl.home_team, tl.home_score,tl.away_score, tl.arbiter_id, us.football_location, us.football_map
FROM test_league tl
INNER JOIN user_schools us ON (tl.home_team = us.school_name)
ORDER BY tl.game_id";
$r = mysqli_query($db, $q);
// Declare two variables to help determine the background color of each row:
$i = 0;
$bgcolor = array('row1', 'row2');
// Begin function to print each game as a row:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<tr class="' . $bgcolor[$i++ % 2] .'"><td>' . $row['game_date'] . '</td><td>' . $row['game_time'] . '</td><td class="alignleft">' . $row['away_team'] . ' vs<br>' . $row['home_team'] . '</td>';
// Determine if the score has been reported:
if ($row['home_score'] == '0' && $row['away_score'] == '0') {
echo '<td><img src="images/report_icon.png" alt="Report Score" /></td>';
} else {
echo '<td>' . $row['home_score'] . '<br>' . $row['away_score'] . '</td>';
}
echo '<td>' . $row['football_location'] . '</td><td>' . $row['arbiter_id'] . '</td></tr>';
}
mysqli_free_result ($r);
mysqli_close($db);
?>
Any and all advice is greatly appreciated!
Try this, you've got your speech marks and dots mixed up :)
if ($row['home_score'] == '0' && $row['away_score'] == '0') {
echo '<td><img src="images/report_icon.png" alt="Report Score" /></td>';
}
Hope this helps!
$url = 'www.example.com?' . http_build_query($row,'','&');
I know this should be simple but I just can't seem to get my head around it.
I have a list of continents in a sql database that I get back using PHP DBO and display in a drop down list. What I then want to do is get the users preferred continent from the sql database and select that one in the list. E.g if the list contains World, Africa, Europe, N America and S America but the users favorite is 'Europe' I want that one selected. $getContinent is the users preference.
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
if ($getContinent != ''){
echo '<option value="' . $getContinent . '" selected="selected" >' . $row['CONTINENT_NAME'] . '</option>';
}else{
echo '<option value=' . $row['CONTINENT_ID'] . '>' . $row['CONTINENT_NAME'] . '</option>';
}
}
I would be most grateful if someone could set me straight as I have found some examples on the internet but have been unable to get them to work :)
Your code should be like this
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
//just check if the option id is equal to the chosen value
if ($getContinent != '' && $getContinent==$row['CONTINENT_ID'] ){
echo '<option value="' . $getContinent . '" selected="selected" >' . $row['CONTINENT_NAME'] . '</option>';
}else{
echo '<option value=' . $row['CONTINENT_ID'] . '>' . $row['CONTINENT_NAME'] . '</option>';
}
}
Its simple, as you guessed :D
You would use something like this:
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . $row['CONTINENT_ID'] . '">' . $row['CONTINENT_NAME'] . '</option>';
}
I hope that helps!
--al
You can use ternary operator
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . $row['CONTINENT_ID'] .
($getContinent == $row['CONTINENT_NAME']) ? '" selected="selected"' : '"' . '>' .
$row['CONTINENT_NAME'] . '</option>';
}
In PHP Project, I'm creating page a which retrieve the data from database on page load then allow the user to change data & Update. I have to use input text and option controls to display data. Editing form data may involve in few POST requests. To load data from database and retain data between POSTs I use this approach.
Load Data from Database
$oClass = new DataClass();
$oClass ->GetRecordById($_REQUEST['id']);
$dataName = $oClass ->Name;
$dataYear = $oClass ->Year;
INPUT TEXTs
<input type="text" name="txtName" value="<?php echo isset($_POST['txtName']) ? $_POST['txtName'] : $dataName ?>" >
OPTIONs
$arrYears = GetYears();
foreach ($arrYears as $year) {
if (isset($_POST['ddlYear'])) {
if ($_POST['ddlYear'] == $year) {
echo '<option value="' . $year . '" selected="selected">' . $year . '</option>';
} else {
echo '<option value="' . $year . '">' . $year . '</option>';
}
} else {
if ($dataYear == $year) {
echo '<option value="' . $year . '" selected="selected">' . $year . '</option>';
} else {
echo '<option value="' . $year . '">' . $year . '</option>';
}
}
}
Is there a better approach to retain data between posts than using like
if (isset($_POST['NAME']))
{$_POST['NAME']}
else
{$name}
Is there a reason why you need to retain the info? If a user submits the form it will update the info and therefore will need to be fetched again for the next person to come in and update or read.
Above though you assign $year = $oClass ->Year; but it's not referenced anywhere. the $year in the foreach loop is a local scope variable only for that foreach loop, after that loop finishes executing it disappears.
you can do stuff like this.
if (isset($_POST['txtName']))
{
$name = $_POST['txtName'];
}
else
{
$name = '';
}
<input type="text" name="txtName" value="<?php echo $name; ?>" />
Since the only difference between the options in the foreach loops are whether or not the selected attribute is applied you can shorten both of them to the following.
if (isset($_POST['ddlYear'])) {
echo '<option value="' . $year . ($_POST['ddlYear'] == $year) ? '" selected="selected"' : '' . '>' . $year . '</option>';
}
else {
echo '<option value="' . $year . ($movieyear == $year) ? '" selected="selected"' : '' . '>' . $year . '</option>';
}
Also to get a quicker answer please provide the simplest working use case, for example above example has $_POST variables that aren't defined anywhere and others like $movieyear also not defined.
Once it loads in my page, if nothing has been saved in the DB table, all options are shown. As soon as i make a selection and reload the page, the selected option dissapears from the list and isn`t reloaded in the dropdown. Instead, it displays the next value which takes the place of the selected one.
if i check the SQL statement and the $str, it does load all the options except the one which is selected which is in $getBris (it has a value).
What could be causing my select to not display my selected option and instead removing it from the list?
*It specifically doesnt work in IE8, wasnt working in Firefox but now it does
<script src="validation.js" type="text/javascript"></script>
<html>
<body onLoad="checkSecondValue();">
</body>
</html>
<?php
//retrieve all the bris for the drop down
include '../../inc/database.php';
// ORDER BY RAND()
$res = BbqcDatabase::getInstance()->doQuery('SELECT * FROM T_TOURNOI_BRIS');
$str = "<select name='ddlBrisSelected' id='ddlBrisSelected' onChange='checkSecondValue()'>";
$getBris = $_GET['bris'];
$getBris = $getBris - 1;
print_r("bris is : "+ $getBris);
if($getBris == null)
{
$str .= "<option value='' selected></option>";
}
else
{
$str .= "<option value='999'>Choisir un bris</option>";
}
$i = 0;
while($data = mysql_fetch_assoc($res))
{
if($data['F_BRISID'] == $getBris)
{
$str .= "<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>";
}
else
{
$str .= "<option value='" . $data['F_BRISID'] . "'>" . $data['F_BRISTITLE'] . "</option>";
}
$i++;
}
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
$str .= "</select>";
echo $str;
if(is_numeric($bris))
{
echo "<script type=\"text/javascript\">alert('test');checkSecondValue();</script>";
}
?>
Use your browser's View Source feature to inspect the actual HTML you are generating (which is, in fact, the only see the browser ever sees). It looks like you're inserting random single quotes.
Update:
<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>"
... will render as:
<option value='blah' selected '>blah</option>
It's the only error I've cared to spot but an HTML validator should find them all. Also, I recommend you use this syntax:
<option value="blah" selected="selected">blah</option>
A construct like this
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
is highly wasteful of space and forces you to duplicate a big chunk of html whose only difference is the "selected" attribute. Why not do something like this:
$selected = ($getBris == 12) ? ' selected' : '';
$str .= "<option value=12{$selected}>Autre</option>";