Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I would like to make a "put words in order" php script from data stored in mysql but I have no clue in how to start. Could someone help me? I just need to separate each word in order to the person could select the word, not type.
Like any of this:
http://a4esl.org/q/j/ck/wo-01.html
http://baladre.info/english/sedaviwebfront/pastSimporder1.htm
Thank you for the attention and help!
#chris85 I'm new in this php programing thing.
I could kind of make this script, sorry maybe for the bad "programming" but it is working:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "questions";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST["topic"])) {
$topic = $_POST["topic"];
$subjectid = $_POST["subjectid"];
} else {
$row['topicid'] = $_GET["id"];
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Questions</title>
</head>
<body>
Question: <br><br>
<form action="questions.php" method="post">
<?
if (isset($_POST["topic"])) {
$sql = "SELECT topicid FROM topic WHERE topic=\"$topic\" AND subjectid=\"$subjectid\"";
$id = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($id);
}
$sql2 = "SELECT * FROM question WHERE topicid=\"$row[topicid]\" ORDER BY rand() LIMIT 1";
$result = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_assoc($result);
echo "<font size=\"6\"><b>".$row2['question']."</b></font>"; ?>
</form>
<?
if ($row2['check'] == "0"){
echo "Level 0: Try to memorize and type the answer according with the text bellow";
} elseif ($row2['check'] == "1"){
echo "Level 1: Try to type the answer by looking the begining of it, if you can't remember go back to level 1 by clicking in \"I got it wrong!\"";
}elseif ($row2['check'] == "2"){
echo "Level 2: Try to type the answer without looking at any part of it, if you forget a simple part you can give a little look";
}elseif ($row2['check'] == "3"){
echo "Level 3: Type the answer without realy looking at any part of it, anyways you still having the color hint";
}elseif ($row2['check'] == "4"){
echo "Level 4: Type the answer without any hint. Now when you will just be able the hit the button \"I got it right!\" when the answer be completely right, if you want you may go back to <b>level 3</b> by presing \"I got ir wrong!\"";
}elseif ($row2['check'] == "5"){
echo "Level 5: Congrats: you got it, fell free to repeat as many times you want! Now you don't need to type exactly as the answer, for it you will have the buttons bellow to check if your answer is right. Just be honest! =D";
}
?>
<!-- start -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<?
echo "<textarea name=\"password\" id=\"password\" hidden='1'>" . $row2['answer']. "</textarea>";
?>
</label>
<br>
<label>Answer: <br />
<textarea name="confirm_password" id="confirm_password" style="width: 80%; height: 100px; font-size:20px" /></textarea> <span id='message'></span>
<? if ($row2['check'] <= "3"){
echo "<script>
$('#confirm_password, #password').on('input', function(e){
changeColor($('#confirm_password').val(), $('#password').val());
});
function changeColor(c, p){
var color;
if(c === p){
color = 'green';
} else if(p.indexOf(c) === 0 && c != ''){
color = 'yellow';
} else {
color = 'red';
}
$('#confirm_password').css('background-color', color);
}
</script>"; }
if ($row2['check'] == "4"){
echo "<script>
$('#confirm_password, #password').on('input', function(e){
changeColor($('#confirm_password').val(), $('#password').val());
});
function changeColor(c, p){
var color;
if(c === p){
color = 'visible';
} else {
color = 'hidden';
}
$('#certo').css('visibility', color);
}
</script>"; }
?>
<!-- end --><br><br>
<table width="80%" border="0">
<tbody>
<tr>
<? echo "<td width=\"33.3%\"><form action=\"right.php\" method=\"post\"><input type=\"hidden\" name=\"topicid\" value=\"" . $row['topicid']. "\"></input><input name=\"questionid\" type=\"hidden\" value=\"" . $row2['questionid']. "\"></input>";
if ($row2['check'] == "5"){ echo "<input type=\"hidden\" name=\"ncomp\" value=\"1\"></input>"; }
echo"<input name=\"certo\" id=\"certo\" type=\"submit\" value=\"I got it Right!\"";
if ($row2['check'] == "4"){ echo "style=\"width:500px; visibility:hidden\""; } else { echo "style=\"width:500px\""; }
echo"></form></td>";
echo "<td align=\"center\" width=\"33.3%\"><a align=\"center\" href='questions.php?id=".$row['topicid']."'>Skip</a></td>";
echo " <td width=\"33.3%\"><form action=\"wrong.php\" method=\"post\"><input type=\"hidden\" name=\"topicid\" value=\"" . $row['topicid']. "\"></input><input name=\"questionid\" type=\"hidden\" value=\"" . $row2['questionid']. "\"></input><input type=\"submit\" value=\"I got it Wrong!\" style=\"width:500px;\"></form></td>"; ?> </div>
</tr>
</tbody>
</table>
<?
echo "<br><br>
<form action=\"aquestion.php\" method=\"post\">";
echo "<input type=\"hidden\" name=\"topicid\" value=\"" . $row['topicid']. "\"></input>"; ?>
<input type="submit" value="New Text Question"></input>
</form>
<br><br><br>
Show answer:
<script type="text/javascript">
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.visibility = 'visible';
}
else document.getElementById('ifYes').style.visibility = 'hidden';
}
</script><? if ($row2['check'] >= "3" && $row2['check'] <= "4"){ echo"<div id=level style=\"visibility:hidden\">"; } ?>
Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck" > No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"><br>
<div id="ifYes" <? if ($row2['check'] >= "2"){ echo "style=\"visibility:hidden\"";} else ?> >
<textarea type='text' id='yes' name='yes' <? if ($row2['check'] == "0"){ echo "style=\"width:80%; height:100px\""; }?> ><?php echo $row2['answer']; ?></textarea><br>
</div><? if ($row2['check'] >= "3" && $row2['check'] <= "4"){ echo "</div>"; } ?>
</body>
</html>
What I would like is, to put the scramble words thing at the "level 1"
Use Javascript to put the selected (clicked) text into a variable and add it to the previous selected text in a div with an ID - for example "answer_div". One textbox given as an example but it could be a div and you would then need to get its innerHTML instead.
You could also have a hidden input with a name and an ID and use getElementById() to put the completed sentence into that in your function so it can be submitted to PHP.
You seem to have managed to get your words displayed in the text boxes so you would need to add an onClick; function and pass this to it:
<html>
<head>
<script language=JavaScript>
var answer_var = '';
var elem = '';
function add_answers(elem){
answer_var = elem.value+" ";
document.getElementById('answer_div').innerHTML = document.getElementById('answer_div').innerHTML + answer_var;
}
</script>
</head>
<body>
<input type ="text" id="answer_var" value="word" onclick="add_answers(this);" />
<div id="answer_div"></div>
</body>
</html>
Related
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 months ago.
This is practice coursework for my Informatics course. We've just started programming in PHP and our task is to program a website that generates tables for the user.
password prompt
ask the user how many rows and columns the table should have
based on the last question; create a form with the same amount of input boxes
generate the table with the input of step 3
I've accomplished everything until step 4. The user can input data in the form, but I the problem is that when I try to generate the table, PHP will show me this error message: "Undefined index: rows on line 70".
As I described earlier I'm just about to learn PHP, so there may be many "not so very nice programming approaches"; therefore I'm open to all kinds of recommendations.
<!DOCTYPE html>
<html>
<body>
<form method="post" target="">
<label for="login">User: </label>
<input name="login">
<br />
<label for="password">Password: </label>
<input name="password" type="password">
<br />
<input type="submit" name="generate" value="Login" />
</form>
<?php
if (isset($_POST['generate'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$hashed_username = sha1($username);
$hashed_password = sha1($password);
$correct_username = '9d6035e25958ec12fca7ec76d68c8daaf4815b9b'; //wims
$correct_password = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'; //test
if ($hashed_username != $correct_username)
die("Wrong user name!");
if ($hashed_password != $correct_password)
die("Wrong password!");
echo "How many rows and columns should the table have? <br />";
echo('
<form method="POST" target="">
Rows: <input type="number" name="rows" min="1" max="100"/><br/>
columns: <input type="number" name="columns" min="2" max="100"/><br/>
<input type="submit" name="generate1" value="Generate Table" />
</form>');
}
if (isset($_POST['generate1'])) {
$rows = $_POST['rows'];
$columns = $_POST['columns'];
global $rows, $columns;
if ($rows > 100 || $rows < 1)
die("Nope!");
if ($columns > 100 || $columns < 2)
die("Nope!");
echo '<form method="POST" target="">';
echo "<table>";
for ($a=1;$a<=$rows;$a++) {
echo "<tr>";
for ($b=0;$b<=$columns;$b++) {
if ($b==0)
echo "<td>$a. Row</td>";
else {
$c = $a . $b;
echo "<td><input type='text' name='$c' /></td>";
}
}
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='generate2' value='Generate' />";
echo "</form>";
}
if (isset($_POST['generate2'])) {
echo "<table>";
for ($a=1;$a<=$GLOBALS['rows'];$a++) {
echo "<tr>";
for ($b=0;$b<=$GLOBALS['columns'];$b++) {
if ($b==0)
echo "<td>$a. row</td>";
else {
$c = $a . $b;
echo "<td>$_POST[$c]</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
?>
</body>
</html>
You need to store your $rows and $columns in $_SESSION variables. With $Globals, I assume you cannot reach to that point, and you get the warning at this point: for ($a=1;$a<=$GLOBALS['rows'];$a++), because $GLOBALS are not declared the second time you reload the page by submitting the second form.
In fact, as W3Schools states, "$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script", while a "session is a way to store information (in variables) to be used across multiple pages." When you submit the pages for the second time, you are in fact refreshing the page, and here Globals are not a pick for you access your rows and columns. Instead you should use sessions to store your $_POST['rows'] and $_POST['columns'].
So, try the following instead. Start Session and then declare new $_Session variables for your $_POST['rows'] and $_POST['columns']. Then voila, the problem is solved.
IMPORTANT: add session_start(); at the top of your page. The very first line.
if (isset($_POST['generate'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$hashed_username = sha1($username);
$hashed_password = sha1($password);
$correct_username = '9d6035e25958ec12fca7ec76d68c8daaf4815b9b'; //wims
$correct_password = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'; //test
if ($hashed_username != $correct_username)
die("Wrong user name!");
if ($hashed_password != $correct_password)
die("Wrong password!");
echo "How many rows and columns should the table have? <br />";
echo('
<form method="POST" target="">
Rows: <input type="number" name="rows" min="1" max="100"/><br/>
columns: <input type="number" name="columns" min="2" max="100"/><br/>
<input type="submit" name="generate1" value="Generate Table" />
</form>');
}
if (isset($_POST['generate1'])) {
$rows = $_POST['rows'] ?? '';
$columns = $_POST['columns'] ?? '';
$_SESSION['rows'] = $rows;
$_SESSION['columns'] = $columns;
global $rows, $columns;
if ($rows > 100 || $rows < 1)
die("Nope!");
if ($columns > 100 || $columns < 2)
die("Nope!");
echo '<form method="POST" target="">';
echo "<table>";
for ($a = 1; $a <= $rows; $a++) {
echo "<tr>";
for ($b = 0; $b <= $columns; $b++) {
if ($b == 0)
echo "<td>$a. Row</td>";
else {
$c = $a . $b;
echo "<td><input type='text' name='$c' /></td>";
}
}
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='generate2' value='Generate' />";
echo "</form>";
}
if (isset($_POST['generate2'])) {
echo "<table>";
$row = $_SESSION['rows'] ?? '';
$columns = $_SESSION['columns'] ?? '';
for ($a = 1; $a <= $row; $a++) {
echo "<tr class='border: 1px solid #BDBDBD'>";
for ($b = 0; $b <= $columns; $b++) {
if ($b == 0)
echo "<td style='border: 1px solid #BDBDBD'>$a. row</td>";
else {
$c = $a . $b;
echo "<td style='border: 1px solid #BDBDBD'>$_POST[$c]</td>";
}
echo "</tr>";
}
echo "</table>";
}
session_destroy();
}
Your code here is the problem
if (!isset($_POST['generate1']))
die('');
Here you are checking if $_POST['generate1] is set, if it is not then die (halt/terminate execution of the script)
php die();
So when you submit your second form (submit has name of generate2) then the above check will fail (it is not set so it will die(); and end execution of your script.
if (isset($_POST['generate1'])) {
// Show the form....
}
Do this for both the generate1 and generate2 and it will only execute that code if the if statements evaluates to true.
instead using "if (!isset($_POST['generate1']))" change it into "if(isset($_POST['generate1']))".When you click generate2 it will be die because that condition is not fulfilled.
<!DOCTYPE html>
<html>
<body>
<form method="post" target="">
<label for="login">User: </label>
<input name="login">
<br />
<label for="password">Password: </label>
<input name="password" type="password">
<br />
<input type="submit" name="generate" value="Login" />
</form>
<?php
if (isset($_POST['generate'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$hashed_username = sha1($username);
$hashed_password = sha1($password);
$correct_username = '9d6035e25958ec12fca7ec76d68c8daaf4815b9b'; //wims
$correct_password = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'; //test
if ($hashed_username != $correct_username)
die("Wrong user name!");
if ($hashed_password != $correct_password)
die("Wrong password!");
echo "How many rows and columns should the table have? <br />";
echo('
<form method="POST" target="">
Rows: <input type="number" name="rows" min="1" max="100"/><br/>
columns: <input type="number" name="columns" min="2" max="100"/><br/>
<input type="submit" name="generate1" value="Generate Table" />
</form>');
}
if (isset($_POST['generate1'])){
$rows = $_POST['rows'];
$columns = $_POST['columns'];
if ($rows > 100 || $rows < 1)
die("Nope!");
if ($columns > 100 || $columns < 2)
die("Nope!");
echo "<form method='POST' target=''>";
echo "<input type='hidden' name='row' value='$rows'/>";
echo "<input type='hidden' name='column' value='$columns'/>";
echo "<table>";
for ($a=1;$a<=$rows;$a++) {
echo "<tr>";
for ($b=0;$b<=$columns;$b++) {
if ($b==0)
echo "<td>$a. Row</td>";
else {
$c = $a . $b;
echo "<td><input type='text' name='$c' /></td>";
}
}
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='a' value='Generate' />";
echo "</form>";
}
if (isset($_POST['a'])) {
$rows = $_POST['row'];
$columns = $_POST['column'];
echo "<table border='1'>";
for ($a=1;$a<=$rows;$a++) {
echo "<tr>";
for ($b=0;$b<=$columns;$b++) {
if ($b==0){
echo "<td>$a. row</td>";
}else {
$c = $a . $b;
echo "<td>$_POST[$c]</td>";
}
}
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
First
Your primary need is to READ THE MANUAL for all the things you're doing, thus you will see that the sha1() Manaul page states:
Warning
It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm.
You REALLY should be fixing this issue.
Anyway, your issue is:
Undefined index: rows on line 70
Which (I guess, because you didn't indicate in your question) is this line:
for ($a=1;$a<=$GLOBALS['rows'];$a++) {
This means that $GLOBALS key rows doesn't exist. Why? All PHP data is generated when a script is executed; before ANY script starts, the PHP knows NOTHING, there is never any incoming data at the start if the PHP script.
Some people here might shout and scream "SESSIONS!!" but even the $_SESSION array is empty at the start of the script, until the PHP code has read the stored session data in the cookie key.
So how do you populate $GLOBALS? What you did was not far off, but you ran the form and submitted the data to $_POST['generate1'] which worked, and this populated the data, but this presented a form to the end user so that user then had to resubmit the form, and by default that reloads the page, therefore restarting the PHP script from zero again, so all data in $GLOBALS is forgotten.
How do you make PHP "remember" data when loading a page? In general there are several ways; all of them have positive and negative sides:
Database. Read and write data to a third party
Sessions. Read and write data to a file/database associated with that specific client only.
Form data, reading data from a submitted form or via URL parameters (GET/POST).
Using (3) is probably easiest for you; so when you run the $_POST['generate1'] you need to add hidden inputs to your form so your "part 2" form can then pass on this data to "part3" form ($_POST['generate2']) .
And that's the data you need to read, not the GLOBALS.
I would like to know what I'm missing in my code.
I have this HTML code:
<html>
<head>
<title>Human gene catalog</title>
</head>
<body>
<h1>Reference sequence and Gene Ontology catalog</h1>
<p>
<b>1.Search for a gene:</b>
<form action=prueba.php method=post>
<select name=organism>
<option value=1>Human</option>
<option value=2>Mouse</option>
<option value=3>Zebrafish</option>
<option value=4>Fruit fly</option>
</select>
<label>Please select a gene:</label>
<br/>
<input type=text name=gene>
<br/><br/>
<input type=submit name=submit value=Submit>
</form>
</p>
</html>
And this PHP code:
<?php
$gene = $_POST["gene"];
$specie = $_POST["organism"];
$enlace = mysqli_connect("localhost","root","******","refGene");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($specie == 1) {
mysqli_select_db($enlace,"refGene_human");
} elseif ($specie == 2) {
mysqli_select_db($enlace,"refGene_mouse");
} elseif ($specie == 3) {
mysqli_select_db($enlace,"refGene_zebrafish");
} elseif ($specie == 4) {
mysqly_select_db($enlace,"refGene_fruitfly");
} else {
echo "The gene is not in database";
}
$result = mysqli_query($enlace,"select * from (here I dont know what to put,if with one specie, here I put the name of the table) where name2 like '%$gene%'");
echo "<h1>Gene Reference Results</h1>";
echo "<table cellspacing=3 cellpadding=4 border=1 bgcolor=#dddddd>";
echo "<tr align='center'><th>Transcript</th><th>Gene</th <th>Chromosome</th><th>Strand</th><th>Gene_Start</th><th>Gene_End</th><th>CDS_Start</th><th>CDS_End</th><th>ExonCount</th>";
while ($extraido = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>".$extraido['name']."<br/>";
echo "<td>".$extraido['name2']."<br/>";
echo "<td align='center'>".$extraido['chrom']."<br/>";
echo "<td align='center'>".$extraido['strand']."<br/>";
echo "<td align='right'>".$extraido['txStart']."<br/>";
echo "<td align='right'>".$extraido['txEnd']."<br/>";
echo "<td align='right'>".$extraido['cdsStart']."<br/>";
echo "<td align='right'>".$extraido['cdsEnd']."<br/>";
echo "<td align='right'>".$extraido['exonCount']."<br/>";
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($enlace);
Basically what I want to achieve is that, selecting a specie and a gene name in the HTML document, it gets you to the PHP, where, depending on the value of specie (1,2,3,4) it selects the corresponding database, and then querying it to find some information.
I have the right code to make it work but just with one specie, without the select list in the HTML and the if statements in the PHP, but I would like to make it work in more than one.
I think I should declare some variable before the if statement in the PHP and then querying over this variable which should tell the query function what table to choose.
But I don't know what could be the right syntax.
if ($specie == 1) {
mysqli_select_db($enlace,"refGene_human");
$database = 'refGene_human';
}
elseif ($specie == 2) {
mysqli_select_db($enlace,"refGene_mouse");
$database = 'refGene_mouse';
}
elseif ($specie == 3) {
mysqli_select_db($enlace,"refGene_zebrafish");
$database = 'refGene_zebrafish';
}
elseif ($specie == 4) {
mysqly_select_db($enlace,"refGene_fruitfly");
$database = 'refGene_fruitfly';
}
else {
echo "The gene is not in database";
}
$result = mysqli_query($enlace,"select * from '$database' where name2 like '%$gene%'");
I am using checkboxes to query the database and I am struggling with this one, I am new to MySQL and PHP so sorry if this is simple!
Here is my code that I have...
<input type="checkbox" name="season2005" value="2005" <?php if(isset($_POST['season2005'])) echo "checked='checked'"; ?> > 2005-06
<input type="checkbox" name="season2006" value="2006" <?php if(isset($_POST['season2006'])) echo "checked='checked'"; ?> > 2006-07
<input type="checkbox" name="season2007" value="2007" <?php if(isset($_POST['season2007'])) echo "checked='checked'"; ?> > 2007-08
<input type="checkbox" name="season2008" value="2008" <?php if(isset($_POST['season2008'])) echo "checked='checked'"; ?> > 2008-09
<input type="checkbox" name="season2009" value="2009" <?php if(isset($_POST['season2009'])) echo "checked='checked'"; ?> > 2009-10
<input type="checkbox" name="season2010" value="2010" <?php if(isset($_POST['season2010'])) echo "checked='checked'"; ?> > 2010-11
<input type="checkbox" name="season2011" value="2011" <?php if(isset($_POST['season2011'])) echo "checked='checked'"; ?> > 2011-12
<input type="checkbox" name="season2012" value="2012" <?php if(isset($_POST['season2012'])) echo "checked='checked'"; ?> > 2012-13
<input type="checkbox" name="season2013" value="2013" <?php if(isset($_POST['season2013'])) echo "checked='checked'"; ?> > 2013-14
if (#$_POST['season2005'] == ""){ $season2005 = "0000"; } else { $season2005 = "2005"; }
if (#$_POST['season2006'] == ""){ $season2006 = "0000"; } else { $season2006 = "2006"; }
if (#$_POST['season2007'] == ""){ $season2007 = "0000"; } else { $season2007 = "2007"; }
if (#$_POST['season2008'] == ""){ $season2008 = "0000"; } else { $season2008 = "2008"; }
if (#$_POST['season2009'] == ""){ $season2009 = "0000"; } else { $season2009 = "2009"; }
if (#$_POST['season2010'] == ""){ $season2010 = "0000"; } else { $season2010 = "2010"; }
if (#$_POST['season2011'] == ""){ $season2011 = "0000"; } else { $season2011 = "2011"; }
if (#$_POST['season2012'] == ""){ $season2012 = "0000"; } else { $season2012 = "2012"; }
if (#$_POST['season2013'] == ""){ $season2013 = "0000"; } else { $season2013 = "2013"; }
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
$seasonpick = implode(",",$seasons);;
$matcharrays = array("AND season in ($seasonpick)");
At the moment all of the data is being queried to the database, so if nothing is selected them then part of query from this is "AND season in (0000,0000,0000,0000) etc
How would I go about only getting those selected into the array and if none are selected then the array would be blank.
Hope you understand what I mean!
Here is a working form with some checkboxes that will allow you to test and get the sql you intended.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
echo "<input type=\"checkbox\" name=\"season[]\" value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Output when 2009, 2010 and 2011 selected:
.... and season in (2009,2010,2011)
Okay, so how it works:
Checkboxes are best used when they all have the same name ending in a []. This makes it a nice array on it's own.
If post data is set, we then quickly throw an array unique over it (good habit for the most part in these types of queries) so that there are no duplicate values.
Then simply implode it into a string and pop it into the SQL query.
Edit: Added functionality to re-check checkboxes when submitted.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array($i+2005, $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Edit 2: Just add quotes in the right places :)
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode("', '", $dateArr);
$sql=".... and season in ('".$dateSearch."')";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array(($i+2005)."i", $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".(($i+2005)."i")."\"> ".($i+2005)."i";
}
?>
<input type="submit">
</form>
Edit 3: I feel like this is starting to really answer much more than one question :)
You can simply check the textbox to make sure it isn't empty and then append to a SQL string:
$sql="";
if(!empty($_POST['text1']))
{
$sql.=" and ftgf>= ".$_POST['text1']." ";
}
Having said that, I would strongly suggest that you NEVER allow the user to enter in parts of the actual SQL you will run - unless it is a closed/secure environment, which means NOT an ope website.
Insert the below code
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
//start
$seasons2 = array();
foreach ($seasons as $season)
{
if($season!=="0000")
{
array_push($seasons2,$season);
}
}
$seasonpick = implode(",",$seasons2);
//end
i have a website where the admin can choose to add a certain number of bbcode tags and the corresponding html tags.
First he chooses how many tags he wants to add from a drop down select form in a for Each loop.
Depending on how many tags he chose when he clicked the submit button, the corresponding number of input tags appear in a second form, also in a for Each loop. He fills in the bbcode and html input and clicks the submit button. Normally the tags should be added to my database but in this case when he clicks submit the form disappears and nothing is added..
Here is the code :
//FIRST FORM WHERE HE DECIDES HOW MANY TAGS TO ADD
<form id='nbbalises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>How many tags ?</legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
echo '<select name="number">';
$range = range(1,50,1);
foreach ($range as $nb) {
echo "<option value='$nb'>$nb</option>";
}
echo "</select>";
?>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form><br /> <br />
<?php
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
//SECOND FORM WHERE I GENERATE THE INPUT DEPENDING ON THE NUMBER CHOSEN FROM FIRST FORM
<form id='balises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>Balises bbc : </legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
foreach ($range2 as $nb2) {
echo "<label>bbcode tag $nb2 :</label>
<input type='text' size='40' name='bbc$nb2' id='bbc$nb2' maxlength='40' />
<label>html tag $nb2 :</label>
<input type='text' size='40' name='html$nb2' id='html$nb2' maxlength='40' />
<br />";
}
}
?>
<input type='submit' name='Submit2' value='Submit2' />
</fieldset>
</form>
<?php
//PROBLEM STARTS HERE, NOTHING WORKS UNDER HERE
if (isset($_POST['Submit2'])){
//CONNECT TO MY DATABASE
connectDB();
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
}
mysql_close();
}
}
//MY FUNCTIONS TO ADD THE BBCODE AND HTML TO DATABASE
function connectDB(){
//connexion DB
$link = mysql_connect('127.0.0.1', 'USERNAME', 'PASSWORD');
if (!$link) {
die('Erreur de connexion: ' . mysql_error());
}
$db = mysql_select_db('1213he200967',$link) or die("N'a pu selectionner
1213he200967");
mysql_query("SET NAMES 'utf8'");
}
function addBbc($bbc, $html){
$b = mysql_real_escape_string($bbc);
$h = mysql_real_escape_string($html);
$query="INSERT INTO bbcode (BBC,HTML) VALUES ('$b','$h')";
$result = mysql_query($query) or die("error");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
return false;
}
else return true;
}
Thank you very much, and sorry if my code is amateur-ish, i'm only starting in php.
EDIT
Found part of my problem
$number = $_POST['number'];
$range2 = range(1,$number,1);
This goes from 1 to the number chosen by the user in the first form.
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
This goes from 0 to $number - 1
So i changed my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
if (!(empty($_POST["bbc$nb"])) && (empty($_POST["html$nb"]))) {
addBbc($_POST["bbc$nb"], $_POST["html$nb"]);
}
else echo "$nb tags empty ";
This works a bit better but now it goes to the else just here above and displays "2 tags empty", so it still doesn't quite work.
Ok to solve it I finally decided to post the data from the second form to another page and i modified my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
$varBbc = 'bbc'.$nb;
$varHtml = 'html'.$nb;
if ((isset($_POST[$varBbc])) && (isset($_POST[$varHtml]))) {
addBbc($varBbc, $varHtml);
}
else echo "$nb tags empty ";
}
Apparently using !empty instead of isset doesn't work in this case, maybe because of the html tags.
$nb should be in double quotes.
so echo "<option value='$nb'>$nb</option>"
change to echo "<option value='".$nb."'>$nb</option>";
and also
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
change to:
if (isset($_POST['submit'])) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
I've been at this the whole day. First I tried to validate my form in php but finally gave up. Now I'm trying to validate the form with JavaScript. It works but since I don't know JavaScript at all and have limited knowledge of PHP I really need help please. It is a test and I want to validate that each question has been answered. The field name in the form = php variable/array, can't get this to work in the javascirpt
var x=document.forms["myForm"]["question_{$q_nr}"].value;
. If I just use a text field name it works fine.
The form
<html>
<head>
<?php
session_start();
?>
<script type="text/javascript" src="counter.js"></script>
<script language="JavaScript">
<!--
function validateForm()
{
var x=document.forms["myForm"]["question_{$q_nr}"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
//-->
</script>
</head>
<body>
<?php
if ($_SESSION['auth']) {
$tid = $_GET['tid'];
echo "<span id='counter'></span>";
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' ORDER BY q_nr";
$result1=mysql_query($sql1);
echo "<form name='myForm' action='http://localhost/index.php?option=com_content&view=article&id=51' onsubmit='return validateForm()' method='post'>";
while($row1 = mysql_fetch_array($result1))
{
$q_nr=$row1['q_nr'];
$q_type=$row1['q_type'];
$question=$row1['question'];
$option1=$row1['option1'];
$option2=$row1['option2'];
echo "<P><strong>$q_nr $question</strong><BR>";
echo "<img src='images/tests/$pic'>";
echo "<BR>";
echo "<BR>";
echo "</p>";
if ($q_type != 'mr') {
if($option1!="") {
echo "<input type='radio' name='question_{$q_nr}' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='radio' name='question_{$q_nr}' value='B'>$option2<BR>";
} else {
echo ''; }
} else { // else if not <> mr
if($option1!="") {
echo "<input type='checkbox' name='question_{$q_nr}[]' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='checkbox' name='question_{$q_nr}[]' value='B'>$option2<BR>";
} else {
echo ''; }
} //if q_type <> mr
} //while row1
echo "First name: <input type='text' name='fname'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
} //else if now > testend
} //if ses auth
?>
why do you think so complicated ?
just use unique ID's for each label, input field, etc ... and check for the innerHTML or value stored; and also you can change the values whenever you want;
btw, your code is messy;
write your code like this:
zone 1: all the js goes here
zone 2: all the html goes here
zone 1:
<script language="text/JavaScript">
//alljs code here
function validate()
{
if( document.getElementById('unique_2').value == null ) document.getElementById('unique_3').innerHTML = 'error1';
if(document.getElementById('unique_4').value == null ) document.getElementById('unique_6').innerHTML = 'error 2';
}
</script>
zone 2:
<form onsubmit="validate()">
all html label and fields go here, like:
<label id="unique_1">label text</label>
<input type="text" id="unique_2" value="" />
<label id="unique_3"></label> this is for the error message
<label id="unique_4">label text</label>
<input type="text" id="unique_5" value="" />
<label id="unique_6"></label> this is for the error message
</form>
This is simple JQuery validation.
I think you must have both validation if you want to be secured...
p.s. Just add 'required' in class of input if you want to be required...
Well for one thing -- validating on the server side is the way to go.
If you just validate on the client side, it can be futzed with (a lot)