I'm making a form to allow numbers only. I'm trying to figure out the logic for the input to restrict numbers starting with 1,2,3,4,5.
This is my php code
<?php
$boton=#$_POST['btnParticipar'];
if (isset($boton)) {
$nombre=#$_POST['txtNumero'];
$simbolos=array('<','>','#','?','php','*','[a-zA-Z]');
foreach ($simbolos as $sim) {
$nombre=str_replace($sim,' ',$nombre);
}
echo $nombre;
}
?>
You could do it this way aswell. I do not know if it's a good solution, but it should work. The first section in the if-statement checks if the input is an integer, and the second section checks if the first number is 6, 7 or 8.
<?php
if(filter_var($_POST['txtNumero'], FILTER_VALIDATE_INT) AND in_array(substr($_POST['txtNumero'], 0, 1), array(6, 7, 8))) {
echo "Correct";
} else {
echo "Incorrect";
}
?>
I would suggest this regex:
if(isset($_POST['value']) AND preg_match('/^[6-8]/', $_POST['value'])){
// do whatever you want
}
As i only know from you that the input needs to start with 6,7,8, this may be the best solution.
Related
I have some arrays, holding the numbers for a multiplication quiz. Here are some examples:
if($level==8){
$first=array(13,14,16,17,18,19);
$second=array(9,10,11,12,13,14,15,16,17,18,19);}
if($level==9){
$first=array(23,19,46,87,98,39);
$second=array(19,10,111,112,139,178,145,166,167,185,192);}
if($level>9){
$first=array(2.3,1.9,4.6,8.7,9.8,3.9);
$second=array(1.9,10,11.1,11.2,13.9,17.8,14.5,16.6,16.7,18.5,19.2);}
These numbers are used to calculate some answers that are placed on a button and the user has to click on the correct answer.
// the correct answer
$b=rand(0,5);
$c=rand(0,10);
$f=$first[$b];
$s=$second[$c];
$d=$f*$s;
// wrong answer no. 1
$w1a=rand(0,5);
$w1b=rand(0,10);
$w1c=$first[$w1a];
$w1d=$second[$w1b];
$w1e=$w1c*$w1d;
if ($w1e==$d){
wronganswer1();
}
// wrong answer no. 2
$w2a=rand(0,5);
$w2b=rand(0,10);
$w2c=$first[$w2a];
$w2d=$second[$w2b];
$w2e=$w2c*$w2d;
if ($w2e==$d){
wronganswer2();
}
There is a check on the receiving page of the POSTing to see if the user has indeed got the correct answer:
$b=$_POST["b"];
$c=$_POST["c"];
$subby=$_POST["sub"];
$d=$c * $b;
$score=$_SESSION["score"];
?>
</head>
<body>
<?php
if ($subby==$d){
echo "<script>correct.play()</script>";}
else{
echo "<script>wrong.play()</script>";
}
?>
<?php
if ($subby==$d) {
echo "Well done!";
$_SESSION["score"]=$_SESSION["score"]+1;
echo "<h3>The button you pressed said: ".$subby;
echo "</h3><br><h2>";
echo $b."x".$c."=".$subby;
echo "</h2><br>";
echo "<h3>Your streak is worth ".$_SESSION["score"];
}
else {
echo "<h1>No!<br>";
$_SESSION["score"]=0;
echo $b."x".$c."=".$d;
echo "<br>";
echo "Your streak has been reset to 0!</h1>";
}
Now, when I have whole numbers: no problem. But the decimals are causing a problem. My code is telling the player that a correct calculation is wrong!
I've spent some time echoing out simple decimal multiplications and the output is correct (so no truncating of decimals or anything like that)...
Why the inaccuracy?
I'm guessing that you are comparing floating point numbers in the same way as integers.
It can't possibly work because of the nature of floating point numbers.
You can't check equality of floating point values, but you can ask if their absolute difference is within a tolerance that you specify. Here's pseudo code to show what I mean:
float x = 1.1;
float y = 1.2;
float tolerance = 1.0e-3;
if (abs(x-y) <= tolerance) { // abs() is an absolute value function
print "within tolerance"
} else {
print "not within tolerance"
}
In the end I managed to get the desired result by casting my 'comparator' to a string (see top line of code):
if ($subby==(string)$d) {
echo "Well done!";
$_SESSION["score"]=$_SESSION["score"]+1;
echo "<h3>The button you pressed said: ".$subby;
echo "</h3><br><h2>";
echo $b."x".$c."=".$subby;
echo "</h2><br>";
echo "<h3>Your streak is worth ".$_SESSION["score"];
Thanks for the help of all who led me to the conclusion/knowledge that 'you can't compare floating values'.
I try show all the hours of the day in order 8, 9, 10 ... but to distinguish the hours that are in the database from the hours that are not. For instance, to give a different color. Can anyone help? (I am not a programmer and I am just learning php alone, so any I would appreciate any help, but explain it in a simple way, please)
This gives me the hours that I have in the database in blue. But I cannot to get hours that are not in the database and I cannot give them another color and the right position: 8, 9,10, 11...
$result = mysqli_query($con, 'SELECT * FROM consulta
WHERE professional=1
AND client=0');
while ($row = mysqli_fetch_array($result)) {
if ($row['hour']=='09:00:00') { echo '<p style="color:blue;">9</p>'; }
elseif ($row['hour']=='10:00:00') { echo '<p style="color:blue;">10</p>'; }
elseif ($row['hour']=='11:00:00') { echo '<p style="color:blue;">11</p>'; }
elseif ($row['hour']=='12:00:00') { echo '<p style="color:blue;">12</p>'; }
}
Here's some sudo code for you. Make an array with all the hours in it. Then iterate that array instead of the result from the database.
for ($i = 0; $i < 24; $i++) {
if(in_array("$i:00:00", $row)) {
// hour was found in the database
echo '<p style="color:blue;">'.$i.'</p>';
} else {
// hour was not found
echo '<p style="color:red;">'.$i.'</p>';
}
}
This way you're iterating over hours that are in the database. Just them. So if 11 is not in the database, if simply won't show. You need a different logic.
You need to iterate over all 24 hours and for each hour check if it is in the database, if so, apply styling, if not, render normally. And a hint, it might be easier to defince CSS classes instead of using inline styling (<p class="db">9</p> instead of <p style="color:blue;">9</p>, and of course, having the db class defined properly; that way you only need to change one rule instead of styling of each element in case you want to change something).
I have a website where i need to use a while statement, but when i use it, it repeats the echo infinitely. Although it looks like i could make it work without while, that isnt so, this is a simplified version of a final product that will need while.
<?php
$passlevel = '0';
while ($passlevel == '0')
{
if(isset($_GET['box_1_color']))
{
$color=$_GET['box_1_color'];
if($color == "#800080")
{
echo "you have passed step one.";
$passlevel == '1';
}
else
{
echo "you didn't select purple.";
}
}
else echo "contact webmaster";
}
?>
Why is it echoing either contact webmaster or you didnt select purple an infinite number of times?
First, you probably need to change:
$passlevel == '1';
to
$passlevel = '1';
The first is a comparison equals, not an assignment equals.
Second, if $color is not #800080, then the loop does not terminate and thus repeats forever as nothing in the loop causes the value to change.
I'm not entirely sure of the point of this loop in the first place. It should work perfectly fine without the loop, however you've stated that your code is a simplified version of something more complicated that indeed needs a loop. Perhaps you can elaborate.
You're not providing any way out of the loop. If $_GET['box_1_color'] isn't purple the first time through the loop, it can't possibly become anything else the second time through the loop, so it'll keep being the wrong color each and every time.
I'm not certain what you intended for this loop to accomplish. If you're trying to have the user enter a new value each time, you won't be able to do that with a loop in PHP. You'll have to regenerate the entire page (with an error message, presumably) and ask the visitor to submit the form again.
In the case of "contact webmaster", you need to break out of the loop, either with the break expression or by setting your $passlevel to anything other than zero. A more serious real problem is revealed in #Mike Christensen's answer, though
If $_GET['box_1_color'] is not set, the variable $passlevel will never be changed.
<?php
$passlevel = 0;
while ($passlevel == 0 || $passlevel == 2)
{
if(isset($_GET['box_1_color']))
{
$color=$_GET['box_1_color'];
if($color == "#800080")
{
echo "you have passed step one.";
$passlevel = 1;
}
else
{
echo "you didn't select purple.".'try again.';
}
}
else
{
echo "contact webmaster";
$passlevel = 2;
}
}
?>
You need to define another passlevel for failure, to stop the while loop. Also, don't put any quotes around integers.
I'm new to PHP, and just creating a simple website.
At the moment, I have a header with some links (i.e. blog, faq, home, gaming etc). I'm trying to use GET functions to show new content in a container on the webpage. I've tried having them link to the index and to a specific page, like
Home
and then having some PHP in the html body...
<?php
if ($_GET[page] == "faq") {
$result === 'FAQ';
} else {
$result === 'Non-FAQ';
}
echo $result;
?>
just to see if it would work, and lo and behold, it doesn't.
So, that's basically the gist of what's happening. It's baffled me for the past few hours, and would really appreciate some help
Thanks
You aren't using the assignment operator to assign a value to $result. Use a single equals sign, ie
<?php
if ($_GET['page'] == "faq") {
$result = 'FAQ';
} else {
$result = 'Non-FAQ';
}
echo $result;
?>
<?php
if ($_GET[page] === "faq") {
$result = 'FAQ';
} else {
$result = 'Non-FAQ';
}
echo $result;
?>
If you want to DEFINE a string you use one "=", if you want to compare it you use "===" (or ==) :)
[Disclaimer: I am new to PHP, and I am just learning, so please no flamers, it really hinders the learning process when one is trying to learn, thank you.]
The code below runs, the only problem is that it does not tell the user when the number is too high or too low, I am doing something wrong, but I can't see the error?
<?php
//Starts our php document
if (!$number)
//if we have already defined number and started the game, this does not run
{
Echo"Please Choose a Number 1-100 <p>";
//gives the user instructions
$number = rand (1,100) ;
//creates number
}
else {
//this runs if the game is already in progress
if ($Num >$number)
{
Echo "Your number, $Num, is too high. Please try again<p>";
}
//if the number they guessed is bigger than number, lets user know, guess was high
elseif ($Num == $number)
{
Echo "Congratulations you have won!<p>";
//if the number they guessed was correct it lets them know they won
Echo "To play again, please Choose a Number 1-100 <p>";
$number = rand (1,100) ;
//it then starts the game again by choosing a new value for $number that they can guess
}
else
{
Echo "Your number, $Num, is too low. Please try again<p>";
}
//if the answer is neither correct or to high, it tells them it is too low
}
?>
<form action = "<?php Echo $_SERVER[’PHP_SELF’]; ?>" method = "post"> <p>
<!--this sends the form back to the same page we are on-->
Your Guess:<input name="Num" />
<input type = "submit" name = "Guess"/> <p>
<!--Allows the user to input their guess-->
<input type = "hidden" name = "number" value=<?php Echo $number ?>>
<!--keeps passing along the number value to keep it consistent till it is guessed-->
</form>
</body>
</html>
I am assuming $Num is undefined and I am assuming you are assuming it will be defined be cause it is defined in the form.
Try this at the start of your script:
if(!empty($_POST)) {
$Num = (int) $_POST['Num'];
}
$number is not automatically set to the value the <input> field has. (It was in early versions of PHP). You now have to use $_POST['number'] and $_POST['Num'] for this.
register_globals in your php.ini is probably Off (and that's a good thing) and therefore you can only access those variables through $_POST['Num'] and $_POST['number'] (you can just assign $number=$_POST['number'] at the beggining of your script)
also, sending the secret $number through form is not nice, you might want to read about php sessions
Suggestions:
1) use echo, not Echo
2) do not forget to close the p tag