I randomized a set of questions using the following code:
for($i=0; $i < count($nwi); $i++)
$itemorder[$i] = $i;
shuffle($itemorder);
$_SESSION["itemorder"] = $itemorder;
A few pages later, a portion of the questions are presented:
for ($i=0; $i<40; $i++) {
if ($i % 10 ==0) echo $header;
echo '<tr class="';
if(in_array($itemlabel[$_SESSION["itemorder"][$i]], $errors)) echo 'skip';
elseif ($i % 2 == 0) echo 'even';
else echo 'odd';
echo '">';
echo '<td>' . ($i + 1) . ".</td><td>" . $itemtext[$_SESSION["itemorder"][$i]] . '</td>';
for ($j = 1; $j <= 6; $j++) {
echo "\n" . '<td';
if ($j == 6) echo ' style="background-color:#999;"';
echo '><input type="radio" name="';
echo $itemlabel[$_SESSION["itemorder"][$i]];
echo '" value="';
echo $j; //value of the input
echo '"';
if ($_POST[$itemlabel[$_SESSION["itemorder"][$i]]] == $j) echo " checked";
echo '></td>';
}
At the end of the survey, I am trying to put the answers to the questions (which should range in value from 1-8) into my SQL database:
"INSERT INTO surveydata
(id, agree_pppg_01,agree_pppg_02,agree_pppg_03,....
VALUES
('$_SESSION[id]', '$_SESSION[itemorder][0]',
'$_SESSION[itemorder][1]', '$_SESSION[itemorder][2]',
'$_SESSION[itemorder][3]',...
I am getting only zeros in my SQL database regardless of how I answer the questions. Any suggestions?
Well, first I don't see anything assigning anything to the session values, but the issue with your code is in this pattern: '$_SESSION[itemorder][1]'. First, I would make sure that MySQL is expecting a varchar there and not an int. If it is an int, good form would be to make sure it isn't quoted.
More importantly, though, when you have an associative array in PHP, you need to make sure PHP expects that.
This
$a = array("hi"=>array("world"=>0)); echo "$a[hi][world]";
Outputs
Array[world]
Put braces around the lookup to make sure it knows to treat it as an array, and then put quotes around all string indexes:
// note the braces and quotes
$a = array("hi"=>array("world"=>"here")); echo "{$a["hi"]["world"]}";
Outputs
"here"
But, I wonder if you wouldn't be better off just using implode:
$columns = implode(',', $_SESSION['itemorder']);
$query = "INSERT INTO surveydata
(id, agree_pppg_01,agree_pppg_02,agree_pppg_03,....
VALUES ('{$_SESSION["id"]}', $columns )";
I do feel obliged to point out that that system does not seem scaleable, and column names like agree_pppg_02 are not descriptive. You may want to go to the codereview stackexchange site to see if they can't offer tips on database design.
Related
I am learning PHP form book and I have found one thing in this part of the code
EDIT:
$count_per_column = ceil($num_powers/$num_columns);
$num_columns = min($max_columns, ceil($num_powers/$threshold));
echo '<table><tr><td>';
while ($row = mysql_fetch_assoc($result)) {
if(($i > 0) && ($i % $count_per_column == 0)) {
echo '</td><td>';
}
echo '<input type="checkbox" name="powers[]" value= "' . $row['power_id'] . '" />';
echo $row['power'] . '<br/>';
$i++;
}
echo '</td></tr></table>';
Is it correct? Isnt there a problem with $i++ ? because the code should make multiple columns with 5 lines. And it making only columns with power and error
Division by zero in / Notice: Undefined variable: count_per_column
In the line where is the Ifis. When I put away $i++ It isn't showing errors. But making only one column.
I'm working with a multi-language site, and there is an HTML select element with 100 choices. The code looks like this:
<option value="1"><? echo $lang['CARGOTYPE_1']; ?></option>
So system insert into mysql table "type" number "1", or number "2" pr...
But when I select number from mysql, I need to change number to word.
With if, else I can change its meanings:
If($type == 1) { echo $lang['CARGOTYPE_1']; } elseif($type == 2){ echo $lang...
But the problem is, that code will be very long...
Any smart solutions for my problem?
If you know number of choices, use for cycle for that.
for ($i = 1; $i <= 30; $i++) {
echo '<option value="' . $i . '">' . $lang['CARGOTYPE_' . $i] . '</option>';
}
I am not sure what you want... If you want to "echo" something with arguments, you can do something like :
echo $lang['CARGOTYPE_'.$type];
But, is that you need ?
I have a loop that has a dynamic variable in it, eg:
while(i < 10){
echo ${"dynamic" . $i . "var"};
$i++;
};
I want to only echo the variable if the original var (say $dynamic3var) is set so I add:
while(i < 10){
if(isset(${"dynamic" . $i . "var"})){
echo ${"dynamic" . $i . "var"};
$i++;
};
};
However this wont work as its still picking up $i.
Does anyone know a correct way of doing this?
Since global variables are bad ideas you should rethink your code. A plain refactoring would be to use an associative array (even if it remains a global variable at the first step). Then you could work with
if( isset($dynamic[$i]) ) ...
Why are Globals evil? Read this: http://tomnomnom.com/posts/why-global-state-is-the-devil-and-how-to-avoid-using-it
Try this:
while($i < 10){
$label = "dynamic".$i."var";
if(isset($$label))
echo $$label;
$i ++;
};
I have a table and each row contains, among other things, 5 columns which may or may not contain an image file name. Let's say I've retrieved that row and put it into an assoc array. I want to loop through and echo those image file names (cols may or may not all be populated) into html tags, but only if that column has an image file name in it. Is there a better way to do it than this?
for ($i = 1; $i < 6; $i++){
if($item_array['image_' . {$i}]{
echo "<li><img src=\"images/work-items/$item_array['image_' . {$i} . '.jpg'\"/></li>"
}
Your syntax was all over the place:
for ($i = 1; $i < 6; $i++){
if(isset($item_array['image_' . $i])){
echo '<li><img src="images/work-items/'. $item_array['image_' . $i] . '.jpg"/></li>';
}
}
I have this code and it should print labels with text boxes for people to fill in information. It takes a text like : $tokens = "*noun *noun *verb" and should print to the user a table that has :
Noun: (text box to be filled)
Noun: (text box to be filled)
verb: (text box to be filled) etc.
but it is not working
echo "<form action=\"storygenerated.php\" method=\"post\">
<input name=\"fields\" type=\"hidden\" value=\"$tokens\" />
<input name=\"story\" type=\"hidden\" value=\"$story\" />
<table>";
for ($i = 0; $i < count($tokenArray); $i++) {
$fieldWords = split('_',$tokensArray[$i]);
echo "<tr><td>";
echo $fieldWords[0];
for ($j = 1; $j < count($fieldWords); $j++) {
echo " ".$fieldWords[$j];
}
echo ":";
echo "</td><td><input name=\"$tokensArray[$i]\" type=\"text\" /></td></tr>";
}
which is from this code that is generating the text $tokens
$storyArray = split(' ', $story);
$tokens = ""; // space-delimited list of fields
$tokensArray=array();
for ($i = 0; $i < count($storyArray); $i++) {
if ($storyArray[$i][0] == '*') {
$tokens .= $storyArray[$i] . " ";
$tokensArray[] = $storyArray[$i];
}
}
There is a few things wrong in your code. I'll start with the first segment.
In your for condition, you are using $tokenArray instead of $tokensArray (missing s) in your count().
In your last echo, since you are using a compound variable name ($tokensArray[$i]), you should enclose it in braces as such: {$tokensArray[$i]}
The corrected code for the first part is the following:
echo "<form action=\"storygenerated.php\" method=\"post\">
<input name=\"fields\" type=\"hidden\" value=\"$tokens\" />
<input name=\"story\" type=\"hidden\" value=\"$story\" />
<table>";
for ($i = 0; $i < count($tokensArray); $i++) {
$fieldWords = split('_',$tokensArray[$i]);
echo "<tr><td>";
echo $fieldWords[0];
for ($j = 1; $j < count($fieldWords); $j++) {
echo " ".$fieldWords[$j];
}
echo ":";
echo "</td><td><input name=\"{$tokensArray[$i]}\" type=\"text\" /></td></tr>";
}
There is also a few performance improvements that could be done which would increase readability and simplify your code.
Since you are using characters to split your string, use explode() instead of split(). split() uses a regular expression to split the string versus explode() which simply uses plain characters.
The whole $fieldWords split and loop could be replaced by a one liner:
echo str_replace('_', ' ', $tokensArray[$i]);
You are separating your $story string manually when using a regular expression would be so much simpler:
preg_match_all('/\*\w+/m', $story, $tokensArray);
$tokensArray = $tokensArray[0];
$tokens = implode(' ', $tokensArray); // Space delimited list of tokens
Two things I was not doing. The first one is that I was dealing with story like an array even though it is not, it is a string. The second is that I was not actually replacing the variables with the value I wanted to be published. I solved the problem with the help of the people who posted some information here. Thank you all.
In the line
if ($storyArray[$i][0] == '*') {
you check just if the string is a string with 1 character equal to an asterisk so I suppose your $tokensArray[] is always empty.
I hope you'll modify the lines
echo $fieldWords[0];
for ($j = 1; $j < count($fieldWords); $j++) {
echo " ".$fieldWords[$j];
}
with
foreach ($fieldWords as $word) {
echo " ".$word;
}