I'm building a very basic questionnaire (with response page) and it works but my form takes up too much space and looks clunky. How would i loop these question arrays so i can save space?
Here is a small bit of my code asking 2 questions:
<h3>Organisation?</h3>
<p><b>It was well organised</b><p>
<?php
$answers = array("Disagree","Agree");
for($i=0;$i<2;$i++) {
print '<input type="radio" name="org" value="'.$answers[$i].'">'.$answers[$i];
};
?>
</p>
<p><b>Adequate materials?</b><p>
<?php
$answers = array("Disagree","Agree");
for($i=0;$i<2;$i++) {
print '<input type="radio" name="lib" value="'.$answers[$i].'">'.$answers[$i];
};
?>
</p>
You should put the two rows in one php tag and use foreach instead, also you should let your php print the headers.
<?php
$answers= array("Disagree","Agree");
echo "<p><b>It was well organised</b></p><p>";
foreach ($answers as $value) {
print '<input type="radio" name="org" value="'.$value.'"> '.$value;
};
echo "</p>";
echo "<p><b>Adequate materials?</b></p><p>";
foreach ($answers as $value) {
print '<input type="radio" name="lib" value="'.$value.'"> '.$value;
};
echo "</p>";
?>
Sidenote: You have 4 opening p tags <p> and just 2 closing tags </p> in your own code. I added another two closing tags in my code where I expected them to be.
You could do:
<?php $questions = array(
'org' => 'It was well organized',
'lib' => 'Adequate materials?',
); ?>
<h3>Organisation?</h3>
<?php foreach ($questions as $f => $question): ?>
<p><b><?= $question; ?></b></p>
<?php foreach (array('Disagree', 'Agree') as $answer): ?>
<input type="radio" name="<?= $f ?>" value="<?= $answer ?>"> <?= $answer ?>
<?php endforeach; ?>
<?php endforeach; ?>
I think you are looking for something like this:
<h3>Organisation?</h3>
<?php
$answers = array("Disagree","Agree");
$first = ""; $second = "";
foreach($answers as $answer) {
$first .= '<input type="radio" name="org" value="' . $answer . '">' . $answer;
$second .= '<input type="radio" name="lib" value="' . $answer . '">' . $answer;
}
echo "<p><b>It was well organised</b></p><p>" . $first . "</p>";
echo "<p><b>Adequate materials?</b></p><p>" . $second . "</p>";
?>
Why not just make it a function?
function answers($name, $array)
{
$returnStr="";
for($i=0;$i<count($array);$i++)
{
$returnStr.='<p><input type="radio" name="'.$name.'" value="'.$array[$i].'"/> '.$array[$i].'</p>';
}
return $returnStr;
}
Then just call it
<h3>Organisation?</h3>
<p><b>It was well organised</b></p>
<?php echo answers("org",array("Agree","Disagree"));?>
Related
I am trying to achieve dynamic $row values from an array, and show them as output. It keeps showing nothing while the values are already there.
This is what I have so far, where:
$row["lg_".$val.""]; should return:
$lg_it
'it' is the $val from the array.
foreach($arrMapCookieToLang as $key => $val) {
$shrtKey = $row["lg_".$val.""];
<input type="text" name="lg_$val" value="$shrtKey">
}
Anyone an idea?
What you have should result in a syntax error. Try the following:
<?php
foreach($arrMapCookieToLang as $key => $val) {
$shrtKey = $row['lg_'.$val];
?>
<input type="text" name="lg_<?= $val ?>" value="<?= $shrtKey ?>">
<?php
}
You've missed to echo your input-field:
foreach($arrMapCookieToLang as $key => $val) {
$shrtKey = $row["lg_".$val.""];
echo '<input type="text" name="lg_' . $val .'" value="' . $shrtKey . '">';
}
Further, if you don't use the array key in the foreach-loop, you can omit the $key =>-part and just write
foreach($arrMapCookieToLang as $val) {
// ...
}
Instead, the
<input type="text" name="lg_$val" value="$shrtKey">
Maybe you should use the
echo "<input type=\"text\" name=\"lg_" . "$val\" value=\"$shrtKey\">";
My question is: I want to show all SQL answers from a specific table inside the <select> using php.
I have tried to get it working, but without much success as it only shows one result.
<?php
error_reporting(E_ALL);
include 'connect.php';
include 'header.php';
set_time_limit(10);
$cat = $bdd->query('SELECT cat_id,cat_name,cat_description FROM categories');
$categories_list = $cat->fetch();
While ($categories_list = $cat->fetch()) {
$cat_name = $categories_list['cat_name'];
}
$cat->closeCursor();
echo '<form method="post" action="accès/create_topic_post.php">';
echo '<label for="sujet">Sujet :';
echo '<input type="text" name="sujet" id="sujet" required autofocus>';
echo '</label>';
echo '<label for="cat">Catégories :';
echo '<select name="topic_name">';
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
echo '</select>';
echo '<input type="submit" value="Envoyer">';
echo '</form>';
?>
That's totally not the way to do it. Have a separation between PHP and HTML. And make sure you have the option echoed out inside the loop. Something like this:
<form method="post" action="accès/create_topic_post.php">
<label for="sujet">Sujet :
<input type="text" name="sujet" id="sujet" required autofocus>
</label>
<label for="cat">Catégories :
<select name="topic_name">
<?php
// Loop it here.
while ($categories_list = $cat->fetch()) {
$cat_name = $categories_list['cat_name'];
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
}
?>
</select>
</label><!-- You forgot this -->
<input type="submit" value="Envoyer" />
</form>
There are two approach to achieve your desired output.
Approach One:
Store cat_name in a new array and use it in your HTML or anywhere, where you want to use.
<?php
$cat_name = array();
while($categories_list = $cat->fetch()) {
$cat_name[] = $categories_list['cat_name'];
}
?>
<select name="topic_name">
<?php
foreach ($cat_name as $key => $value) {
?>
<option value="<?=$value?>" ><?=$value?> </option>
}
?>
</select>
Approach 2:
<?php
while ($categories_list = $cat->fetch()) {
?>
<option value="<?=$categories_list['cat_name']?>" ><?=$categories_list['cat_name']?> </option>
<?php
}
?>
Whats wrong with your code:
$cat_name = $categories_list['cat_name']; this will only store the last value of your query, you must need to store the value in an array or use <option> inside the while() loop.
You keep replacing cat_name every time you read data from the SQL server. You need to store it in an array
<?php
error_reporting(E_ALL);
include 'connect.php';
include 'header.php';
set_time_limit(10);
$cat = $bdd->query('SELECT cat_id,cat_name,cat_description FROM categories');
//$categories_list = $cat->fetch(); This line discards a row of data
$cat_names = array(); //array for category names
While ($categories_list = $cat->fetch()) {
//Add newest 'cat_name' to the array
$cat_names[] = $categories_list['cat_name'];
}
$cat->closeCursor();
echo '<form method="post" action="accès/create_topic_post.php">';
echo '<label for="sujet">Sujet :';
echo '<input type="text" name="sujet" id="sujet" required autofocus>';
echo '</label>';
echo '<label for="cat">Catégories :';
echo '<select name="topic_name">';
//Loop and read back each category name
foreach ($cat_names as $cat_name){
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
}
echo '</select>';
echo '<input type="submit" value="Envoyer">';
echo '</form>';
?>
You don't have to loop over results manually, as PDO has a function that can do it for you already, called fetchAll(). You have to use it instead of fetch() if you want to get an array of rows.
However, beside it, you need to learn PHP and programming in general. Because your current code makes little sense. To output an array, you have to use a loop:
$cat = $bdd->query('SELECT cat_name FROM categories');
$categories_list = $cat->fetchAll(PDO::FETCH_COLUMN); // here it is
echo '<form method="post" action="accès/create_topic_post.php">';
echo '<label for="sujet">Sujet :';
echo '<input type="text" name="sujet" id="sujet" required autofocus>';
echo '</label>';
echo '<label for="cat">Catégories :';
echo '<select name="topic_name">';
foreach ($categories_list as $cat_name)
{
echo "<option value='$cat_name'>$cat_name</option>";
}
echo '</select>';
echo '<input type="submit" value="Envoyer">';
echo '</form>';
Move the fetch loop to the output section of your code.
So instead of this:
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
move the loop so it will look like this:
While ($categories_list = $cat->fetch()) {
$cat_name = $categories_list['cat_name'];
echo "<option value=\"".$cat_name."\" >$cat_name </option>";
}
Use while loop while you're outputting the category in select option.
Like this,
While ($categories_list = $cat->fetch()) {
echo "<option value=\"".$categories_list['cat_name']."\" >$categories_list['cat_name'] </option>";
}
I have user titles, which are stored in database in this way. 1,2,6,10 and etc.
I want to check if the user already has this titles and if he does, to check the check box.
<?php
$user_titles = explode(',', $user['titles']);
//foreach($user_titles as $uTitles){
//echo $uTitles;
//}
?>
<input type="checkbox" name="title[]" value="1">Test1<br/>
<input type="checkbox" name="title[]" value="2">Test2<br/>
<input type="checkbox" name="title[]" value="3">Test3<br/>
You need to add the checked attribute to the checked ones.
<input type="checkbox" name="title[]" value="1" <?php if(in_array(1, $user_titles) echo 'checked="checked"'; ?>>Test1<br/>
Move the titles to new array and iterate trough them. Inside the loop, check if the value is in the $user_titles array and add 'checked' to the input tag.
<?php
$titles = [
1 => "Test1",
2 => "Test2",
3 => "Test3",
];
foreach ($titles as $value => $title) {
$checked = in_array($value, $user_titles) ? 'checked' : '';
echo '<input type="checkbox" name="title[]" value="' . $value . '" ' . $checked . '>' . $title . '<br/>';
}
?>
If i understand correctly you have the values stored as a string delimited by a comma.
Use an iteration method, for example:
<?php $checked = ''; ?>
<?php for($i = 1; $i <= count($possible_checkbox); $i++ ) {
if(in_array($i, $user_titles ) ) { $checked = 'checked'; } else {$checked = '' }
?>
<input type="checkbox" value="<?php echo $i; ?>" name="title[]" <?php echo $checked; ?> />
<?php } ?>
Hope it helps.
Im a newbie to this forum and have just started coding in php. Need some help. I have the following code
<?php error_reporting(-1);
require_once('/mysql/sql_connect.php');
$q = "SELECT pty.pty_profile_name AS profile FROM pty, users WHERE users.username = 'testaccount' ";
$r = #mysqli_query ($dbc, $q);
$results_array = array();
while($row = mysqli_fetch_assoc($r)) {
array_push($results_array, $row);
echo "<pre>"; print_r($results_array); echo "</pre>"; }
?>
<p>
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
<input type="submit" name="Submit" />
</form>
<?php
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
The output I get is correct, but it displays the key, eg, 0 or 1 or 2, based on what I select in the form. I need the value output. Eg 0 = Emerton, it outputs "0" instead of Emerton.
If I echo $value['profile'] instead of pty_select, I get the last result of the query all the time. Which in this example would be 2, which is Ambarvale as I believe it just chooses the last row output of the query.
I hope I've made sense. Thanks in advance.
It will obviously echo the key, as you assigned the value of options as $key
if you need the options in the $_POST['pty_select'] use this:
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $value['profile'];?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
You mean you need the value what you have used to display it.
Then,
Change to :
<option value="<?php echo $value['profile']; ?>">
<?php echo $value['profile']; ?>
</option>
And now let's go to ideal world :)
Build data pairs database_id => name for options:
$q = "SELECT pty.id, pty.pty_profile_name AS profile FROM pty, users
WHERE users.username = 'testaccount'";
$r = mysqli_query($dbc, $q);
$values = array();
while($r = mysqli_fetch_row($r)) {
$values[$r[0]] = $r[1];
}
Never use # when working with database, why do you want to suppress errors instead of preventing/handling them?
Now you have real database IDs and respective values (in general, using unique IDs are better... if nothing else they have greater entropy - more efficient search). And sice displaying select box is really common in webs, lets:
function selectbox( $values = array(), $attributes = array(), $selected_value = null)
{
// Header
echo '<select';
foreach( $attributes as $key => $val){
echo ' ' . htmlspecialchars($key) . '="' . htmlspecialchars( $val) . '"';
}
echo '>';
// Values
foreach( $values as $key => $val){
echo '<option value="' . htmlspecialchars( $key) .'"';
if( $key === $selected_value){
echo ' selected="selected"';
}
echo '>' . htmlspecialchars( $val) . '</option>';
}
echo '</select>';
}
And now usage :)
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<?php selectbox( $values, array( 'name' => 'pty_select')); ?>
<input type="submit" name="Submit" />
</form>
And what to do with it then?
$id = (int)(isset( $_POST['pty_select']) ? $_POST['pty_select'] : 0);
$name = null;
if( $id && isset( $values[$id])){
$name = $values[$id];
}
Give
<option value="<?php echo $value['profile']; ?>"><?php echo $value['profile']; ?></option>
instead of
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
Change it to something like
if(isset($_POST['Submit'])) {
echo $results_array[$_POST['pty_select']]['profile'];
}
Or alternatively use profile option value.
I have two array. What I want to do is compare the key ['user_id'] of two arrays, if they are the same, pass the ['user_id'] and ['ref'] in hidden form. I tried to put them into two foreach, but system seems into a dead lock.
<?php foreach($_SESSION['printing_set'] as $data) { ?>
<?php foreach(getProvenaMailableUserlist() as $userlist){ ?>
<input type="hidden" name="reference[<?php echo $data['user_id'] ?>]" value="<? if($userlist['user_id'] == $data['user_id']){echo $userlist['ref'];} ?>" />
<?php } ?>
<?php } ?>
What is the right way to do that?
What you are doing is printing again and again the part of '<input type="hidden" name="...'. here is what you should do
<?php
echo '<input type="hidden" name="reference[' . $data['user_id'] . ']" value="'; //olny one time.
foreach($_SESSION['printing_set'] as $data) {
foreach(getProvenaMailableUserlist() as $userlist){
if($userlist['user_id'] == $data['user_id']){
echo $userlist['ref']; //only if condition is true
}
}
}
echo '" />'; //only one time
?>
You've got some funky formatting going on, so it's hard to tell where the error might be. Try it like this:
<?php
foreach($_SESSION['printing_set'] as $data) {
foreach(getProvenaMailableUserlist() as $userlist){
$value = "";
if($userlist['user_id'] == $data['user_id'])
$value = $userlist['ref'];
echo "<input type='hidden' name='reference$user_id' value='$value' /> \n";
}
}
?>