PHP counting uppercase letters (not working) - php

I am new to PHP and trying to count all the uppercase letters in the text area, thought I am not able get anything when I hit the 'submit' button. Here is my code :
<!DOCTYPE html>
<html>
<body>
<?php
if(isset($_POST['submit'])) {
function caps($s) {
$u = 0;
$d = 0;
$n = strlen($s);
for ($x=0; $x<$n; $x++) {
$d = ord($s[$x]);
if ($d > 64 && $d < 91) {
$u++;
}
}
return $u;
}
$n1=$_POST['n1'];
echo 'caps: ' . caps($n1) . "\n";
}
?>
<form><textarea rows="4" cols="50" name="n1" value="<?php if(isset($_POST['n1'])){echo htmlspecialchars($_POST['n1']);}?>"></textarea>
<br><input type="submit" name="submit" value="Submit"></form>
</body>
</html>

This example will help you.
preg_match_all("/[A-Z]$/", $s, $matches);
$all_upper_cases = count($matches);

Use this function:
function count_capitals($s) {
return strlen(preg_replace('![^A-Z]+!', '', $s));
}
ex.
$n1=$_POST['n1'];
echo 'caps: ' . count_capitals($n1) . "\n";
textbox:
<textarea rows="4" cols="50" name="n1" value="<?php count_capitals($n1) ?>"></textarea>

You forgot to set the form method to post your code should be something like:
<!DOCTYPE html>
<html>
<body>
<?php
if(isset($_POST['submit'])) {
function caps($s) {
$u = 0;
$d = 0;
$n = strlen($s);
for ($x=0; $x<$n; $x++) {
$d = ord($s[$x]);
if ($d > 64 && $d < 91) {
$u++;
}
}
return $u;
}
$n1=$_POST['n1'];
echo 'caps: ' . caps($n1) . "\n";
}
?>
<form method="post"><textarea rows="4" cols="50" name="n1" value="<?php if(isset($_POST['n1'])){echo htmlspecialchars($_POST['n1']);}?>"></textarea>
<br><input type="submit" name="submit" value="Submit"></form>
</body>
</html>
Make sure you set the form method to post.
If you don't provide method the form uses get method instead of post.

Related

"How to have the user add two random integers on a single page using $_POST"

I am trying to create an adding game PHP and HTML, where the user guesses the sum of two random integers. However, when the user submits the answer, the integers randomize again, changing the sum and making the user's guess incorrect.
<?php
$x = (rand(1,10));
$y = (rand(1,10));
$sum = $x + $y;
if (isset($_POST['submit']))
{
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
echo "<br>What is " . $x . " + " . $y . "? <br>";?>
<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>
I am expecting the output to be "nice, you got it right" when the $guess==$sum, but $sum changes when the form is submitted, making the 2 variables unequal.
Try to use session and store the two random number. PHP Session
just like this.
<?php
session_start();
if (isset($_POST['submit']))
{
$sum = $_SESSION['y'] + $_SESSION['x'];
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
$_SESSION['x']= (rand(1,10));
$_SESSION['y']= (rand(1,10));
echo "<br>What is " . $_SESSION['x'] . " + " . $_SESSION['y'] . "? <br>";
?>
<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>
I hope I answer your problem. just read the PHP session it helps you a lot.
You can create a hidden input field to post the sum value. Then compare that value with the guessed value.
<?php
$x = (rand(1,10));
$y = (rand(1,10));
$sum = $x + $y;
if (isset($_POST['submit'])) {
$guess = $_POST['guess'];
$value = $_POST['sum'];
if ($value == $guess) {
echo "nice, you got it right.";
} else {
echo "aw, too bad. <br>";
}
}
echo "<br>What is " . $x . " + " . $y . "? <br>";
?>
<form action="" method="post">
<input name="guess" type="text" />
<input type="hidden" name="sum" value="<?=$sum?>" />
<input name="submit" type="submit" />
</form>
You should store your $x and $y in a hidden input.
Calculate the sum by using the post value instead of generating new value.

How to do 3*3 matrix multiplication in php?

How can i do 3*3 or 3*1 matrix multiplication in php with following code. where should i have to change the logic ?????
this code completely work for only 2*2 matrix multiplication
Here is my code:
$a = Array( Array(1,2),Array(4,5));
$b = Array( Array(7,5), Array(3,2));
$sumArray = array();
$c = array();
for($i=0;$i<2;$i++)
{
for($j=0;$j<2;$j++)
{
$c[$i][$j]=0;
for($k=0;$k<2;$k++)
{
$c[$i][$j]=$c[$i][$j]+($a[$i][$k]*$b[$k][$j]);
}
}
}
echo "<pre/>";
print_r($c);
?>
Matrix Multiplication
Rules :
First matrix's column and Second matrix's row must be same
Result matrix's size will be First matrix's Row and Second matrix's Column
$a = Array( Array(1,2),Array(4,5));
$b = Array( Array(7,5), Array(3,2));
$r=count($a);
$c=count($b[0]);
$p=count($b);
if(count($a[0]) != $p){
echo "Incompatible matrices";
exit(0);
}
$result=array();
for ($i=0; $i < $r; $i++){
for($j=0; $j < $c; $j++){
$result[$i][$j] = 0;
for($k=0; $k < $p; $k++){
$result[$i][$j] += $a[$i][$k] * $b[$k][$j];
}
}
}
print_r($result);
Matrix computation is achieved by multiplying any column or row elements by their own cofactors.
Codes according to your request;
<?php
if ($_POST['hsp']) {
$de3t11=$_POST['m11']; $de3t12=$_POST['m12']; $de3t13=$_POST['m13'];
$de3t21=$_POST['m21']; $de3t22=$_POST['m22']; $de3t23=$_POST['m14'];
$de3t31=$_POST['m31']; $de3t32=$_POST['m23']; $de3t33=$_POST['m15'];
//show on screen
echo $de3t11 ." ". $de3t12. " ". $de3t13;
echo "<br>";
echo $de3t21 ." ". $de3t22. " ". $de3t23;
echo "<br>";
echo $de3t31 ." ". $de3t32. " ". $de3t33;
echo "<br>";
//calculate matrix
$m3m11=(($de3t22*$de3t33)-($de3t23*$de3t32))*(1);
$m3m12=(($de3t21*$de3t33)-($de3t23*$de3t31))*(-1);
$m3m13=(($de3t21*$de3t32)-($de3t22*$de3t31))*(1);
//Determinant
$det3t3=(($de3t11*$m3m11)+($de3t12*$m3m12)+($de3t13*$m3m13));
echo $det3t3;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST">
<input type="number" name="m11">
<input type="number" name="m12">
<input type="number" name="m13">
<br><br>
<input type="number" name="m21">
<input type="number" name="m22">
<input type="number" name="m23">
<br><br>
<input type="number" name="m31">
<input type="number" name="m32">
<input type="number" name="m33">
<input type="submit" name="hsp">
</form>
</body>
</html>

PHP Displaying a number of asterisks depending on the number given in the input field

What I want to accomplish is to display an asterisk or asterisks () depending on the number I input. For example if I input 2, the form will display 2 asterisks (*). In my code, I don't think string concatenation is not the right way to do it as I didn't get the result I wanted. I use a for loop. I'd appreciate if you can tell me how to code it the right way or if the for loop is wrong in this situation. Here's the code so far.
<?php
$number = $star = '';
if (isset($_POST['submit'])) {
$number = (int)$_POST['number'];
$star = '*';
for ($i = 0; $i < $number; $i++) {
$star .= $star;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Star</title>
</head>
<body>
<!--Form-->
<form id="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<label for="number">Enter number</label>
<input id="number" type="number" name="number" size="3" maxlength="3" required>
<input type="text" readonly="readonly" value="<?php echo $star; ?>">
<input type="submit" name="submit" value="Display">
</form>
</body>
</html>
How about str_repeat()
$star = str_repeat("*", $number);
With your current code you will always get more asterixes (as mentioned in the comments by #AeJey) because you are starting with one *, you join it with itself getting **, then again join with itself getting ****...
#Unamata Sanatarai str_repeat() works nice in this situation, so use that instead.
Don't forget some error checking:
<?php
if (isset($_POST['submit'])) {
$number = (int) $_POST['number'];
if ($number > 0) {
$star = str_repeat("*", $number);
} else {
$star = "Enter number greater than zero!";
}
}
?>
Hope this helps..
`
Don't concatenate $star on $star ($star .= $star;). Choose another variable - $out .= $start and output that instead.
Or you could use the string padding function to repeat the wanted number of times.
$number = (int) $_POST["number"];
$out = str_pad("", $number, "*");
Your printed asterisks are doubleing in string length each iteration because you are concatenating the whole cached string onto itself.
Instead only add a single character to the cached string on each iteration.
Code: (Demo)
$number = 5;
$star = '*';
$stars = $star;
for ($i = 0;
$i < $number;
++$i, $stars .= $star
) {
echo "$stars\n";
}
Output:
*
**
***
****
*****

Creating PHP multiplication table with user input

I am creating form where the user can input a integer and get the multiplications (1-10) of that number. Here is my web form for user input:
<html>
<head>
<title>Assignment 9.1</title>
</head>
<body bgcolor="black" text="white">
<form method="post" action="table.php"
<strong>Enter No:</strong>
<input type="text" name="num" size="10">
<input type="submit" value="Get Table">
</form>
</body>
</html>
The table I have created is this:
<?php
$num = $_POST['num'];
if($num)
(
for ($i=1; $i<=10; $i++)
(
$mul = $num * $i;
echo "$num * $i = $mul<br>";
)
)
else
(
echo "Invalid Entry!";
)
?>
I am getting an error for the table. The error is for line 5 (FOR). I have no idea why I am getting this error. Can anyone Help?
Blocks of code are marked with curly brackets { ... }, you are currently using parentheses ( ... )
As far as I can tell, that's pretty much the only thing wrong with it. You might want to add a bit of validation:
$num = isset($_POST['num']) ? intval($_POST['num']) : 0;
But that'd just a touch-up. The brackets are your actual problem.
You need to use {} instead () in the for and if.
Like this:
<?php
$num = $_POST['num'];
if($num)
{
for ($i=1; $i<=10; $i++)
{
$mul = $num * $i;
echo "$num * $i = $mul<br>";
}
}
else
{
echo "Invalid Entry!";
}
?>
Hope it helps you!
You are using parentheses when you should be using braces. Try this...
<?php
$num = $_POST['num'];
if($num)
{
for ($i=1; $i<=10; $i++)
{
$mul = $num * $i;
echo "$num * $i = $mul<br>";
}
}
else
{
echo "Invalid Entry!";
}
?>
save the file as table.php and run working 100%
<html>
<head><title>Table</title></head>
<body>
<form action="" method="POST">
<center><input type="text" name="number" size="20" > </center> <br>
<center><input type="submit" name="table" value="get table"> </center>
</form>
</body>
</html>
<?php
$num=$_POST['number'];
if($num<=20)
{
for ($i=1; $i<=10; $i++)
{
$mul=$num*$i;
echo "<center>$mul </center><br>";
}
}
else
{
echo "<center>envalid entry</center>";
}
?>
<html>
<head><title>Table</title></head>
<body>
<form action="" method="POST">
<center><input type="text" name="number" size="20" > </center> <br>
<center><input type="submit" name="table" value="get table"> </center>
</form>
</body>
</html>
<?php
$num=$_POST['number'];
if($num<=20)
{
for ($i=1; $i<=10; $i++)
{
$mul=$num*$i;
echo "<center>$mul <br></center>";
}
}
else
{
echo "<center>envalid entry</center>";
}
?>

PHP Multiple form in same page

I'm doing form in php but I have some problem.
First I will have 3 different form in the same page.
What I want is only 1 form appear and then with the answer a second form will appear and so on.
The answer of the form will be display on the same page.
For now my first form work and after get the answer go to the 2nd form but I want to submit the 2nd form the problem appear.
It delete the answer of my first form and don't do anything (everything start like I am in my first form).
I try to find the problem but can't have idea about how to solve it.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1?
<input type="number" name="nbtemplate" min="1" max="30">
<input type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php
if(!isset($submitbutton1)) {
if (!empty($_POST['nbtemplate']) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for ($i = 1; $i <= $Nnbtemplate; $i++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
if(isset($submitbutton1) && !isset($submitbutton2)) {
if (!empty($_POST['nbtime']) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST['nbtime'];
for ($j = 1; $j <= $nbtime; $j++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time" name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
}
}
?>
That is some gnarly code you got there, brother. This is a really simple task when handled with some javascript. Then you can have a single post to your php. I like using the jQuery framework so here's a couple links I found quickly: this one and this one
Example code in response to comment about building form elements dynamically:
<html>
<head>
<!-- load jquery library -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<form action="toyourpage.php">
How Many?:
<input type="text" name="number" id="number">
<div id="add"></div>
</form>
<!-- javascript go -->
<script type="text/javascript">
$(document).ready(function()
{
$('input#number').keyup(function()
{
var num = $(this).val(); // get num
if(!isNaN(num)) // check if number
{
$('div#add').html(''); // empty
for(i = 1; i <= num; i++) // add
{
$('div#add').append('New Field ' + i + ': <input type="text" name="next_' + i + '" id="next' + i + '"><br>');
}
}
else
{
alert('Valid number required');
}
});
});
</script>
</body>
</html>
I did some changes on Your code, and have tested, it works.
You had any mistakes in your {} brackets and if conditions. Also as I commented I added extract($_POST).
<?php
extract ( $_POST );
if (! isset ( $submitbutton1 ) && !isset($submitbutton2)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1? <input type="number" name="nbtemplate" min="1" max="30"> <input
type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php ;
}
if (isset ( $submitbutton1 )) {
if (! empty ( $_POST ['nbtemplate'] ) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST ['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or
die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for($i = 1; $i <= $Nnbtemplate; $i ++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
}
}
if ( isset ( $submitbutton2 )) {
if (! empty ( $_POST ['nbtime'] ) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST ['nbtime'];
for($j = 1; $j <= $nbtime; $j ++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time"
name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
?>

Categories