How to use if statement in php? - php

I have a problem with php if statement. I want to display propere status user. If user is friend, it should display friend. If user is wainting, should display wainting. And if user not friend and wainting, should display add. This code below, display always only Friend. I don't know why. If someone help me I will gratefull.
<input type="submit" name="addFriend" id="button_color" value="<?php if ($this->status == 'Friend'): ?> Friend <?php elseif ($this->status == 'Wainting'): ?> Wainting <?php else: ?> Add <?php endif; ?>">

You can try this
<input type="submit" name="addFriend" id="button_color" value="<?php if ($this->status == 'Friend'){ echo 'Friend'; } elseif ($this->status == 'Wainting'){ echo 'Wainting';} else{echo 'Add'; ?>">

Related

Is it possible to store variable in input box in HTML or PHP

I would like to create an input box that is only readable and have the title of the book, is it possible that the input box can store a variable?
P.S The one I want to change is the id, now I successfully disabled the input box, but the output is $id instead of the variable that I use the $_GET method.
My code is as follow
<?php
include_once 'header.php';
$id = mysqli_real_escape_string($conn, $_GET['bookid']);
$title = mysqli_real_escape_string($conn, $_GET['title']);
?>
<section class="signup-form">
<h2>Pre-order</h2>
<div class="signup-form-form">
<form action="preorder.inc.php" method="post">
<input type="text" disabled="disabled" name="id" value= $id >
<input type="text" name="uid" placeholder="Username...">
<input type="text" name="BRO" placeholder="BookRegistrationCode...">
<button type="submit" name="submit">Pre-order</button>
</form>
</div>
<?php
// Error messages
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyinput") {
echo "<p>Fill in all fields!</p>";
}
else if ($_GET["error"] == "wronginfo") {
echo "<p>Wrong information!</p>";
}
else if ($_GET["error"] == "stmtfailed") {
echo "<p>Something went wrong!</p>";
}
else if ($_GET["error"] == "none") {
echo "<p>Success!</p>";
}
}
?>
</section>
Put <?php echo $var; ?> inside the value attribute.
<input type="text" value="<?php echo $var; ?>" />
EDIT
As per #arkascha's comment, you can use alternative php short tags:
<input type="text" value="<?= $var; ?>" />
As per the docs: https://www.php.net/manual/en/language.basic-syntax.phptags.php

After clicking Submit button for a quiz in php on wordpress, results of POST doesn't get displayed

I created a quiz in php with questions, I have added the php code shortcode on wordpress page. User should be able to answer the quiz which is in the form of picking a radio button. AFter user has answered all the questions, user clicks SUBMIT button, now the user should be displayed his score. The issue is user is not getting displayed the code.
The same php code when I execute on local php server that I set up, it works fine and provides the score. What am I missing here?
if (isset($_POST['answers']) && !empty($_POST['answers'])){
$Answers = $_POST['answers']; // Get submitted answers.;
header('location: ' . $_SERVER['PHP_SELF']);
if ($Answers == 'NULL'){
echo "please select all the answers";
}
else
{
foreach ($Questions as $QuestionNo => $Value){`enter code here`
if (!isset($Answers[$QuestionNo])) {
echo "answer all questions";
break;
?>
<form action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<?php foreach ($Questions as $QuestionNo => $Value){ ?>
<h3><?php echo $Value['Question']; ?></h3>
<?php
foreach ($Value['Answers'] as $Letter => $Answer){
$Label = 'question-'.$QuestionNo.'-answers-'.$Letter;
?>
<div>
<input type="radio" name="answers[<?php echo
$QuestionNo; ?>]" id="<?php echo $Label; ?>" value="<?php echo
$Answer; ?>" />
<label for="<?php echo $Label; ?>"><?php echo $Letter; ?
>) <?php echo $Answer; ?> </label>
</div>
<?php } ?>
<?php } ?>
<br />
<div>
<input style="font-size:25px;color:white;background-
color:orange;border:2px solid #336600;padding:3px;" type="submit"
value="Submit Quiz" />
</div>
</form>
<?php
expected resulted is that after user answers all the quiz questions and clicks SUBMIT, the output of score should be displayed. The output doesn't get displayed instead the page is directed to home page of website.
I'm not sure why it's in there but I would try removing the below code. You want to show the answers but instead, you are redirecting the user to the page.
header('location: ' . $_SERVER['PHP_SELF']);

Button function for all fetch row

I am doing project for my university. I create a page where user can send friend request. Here I fetch data from another table and put button for each row data.
My problem is that when one button click other row button also was change to friend request. I need a solution for it.
How to make one add friend request button is equal to one row id and how to avoid other button affected whenever click particular row.
My code is included below. I hope you guys will help me. Thanks in advance.
<?php
session_start();
$_SESSION['myid'];
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID ORDER BY
tutor_register.register_ID='".$_SESSION['myid']."'desc";
$result= mysqli_query($mysqli,$sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$register_ID=$row["register_ID"];
$username = $row['username'];
$profile = $row['profile'];
$email = $row['email'];
$address=$row['address'];
$gender=$row['gender'];
$main_subject=$row["main_subject"];
$subject_add=$row["subject_add"];
$rate_main=$row["rate_main"];
$rate_add=$row["rate_add"];
$qualification=$row["qualification"];
?>
<table><form method="post">
<tr class="border_bottom">
<td height="230"><img src='<?php echo $profile;?>'width="200" height="200"/> </td><td><td></td></td>
<?php
if($register_ID == $_SESSION['myid']){
?>
<td><label>Your Profile</label></td>
<?php
} else {
?>
<form method="post">
<td><button class='friendBtn unfriend' name="" data-type="unfriend">Unfriend</button>
<input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/></td> </form>
<?php
}
}
?>
</tr>
</div>
</table>
</form>
<?php
if(isset($_POST['id']) ) {
$user_id = $_SESSION['myid'];
$friend_id = $_POST['id'];
$sql="INSERT INTO friends(user_id,status,friend_id)" ."VALUES('$user_id','yes','$friend_id') ";
if($mysqli->query($sql)=== true) {
$_SESSION['status']="yes";
$_SESSION['id']=$row['id'];
} else {}
}
}
?>
</body>
</html>
You need to replace the following block in your code:
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>
With the one mentioned below. This will solve your problem.
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes' && $row['register_ID']==$_SESSION['id']){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>

Switch statement in a PHP based HTML template - parse error always on second case [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 4 years ago.
I'm trying to implement a simple templates engine with PHP. Everything works pretty nice except my form generator. I'm trying to render different form inputs based on the field type I get from backend. This is what I have got so far. It crashes with message
Parse error: syntax error, unexpected 'case' (T_CASE) in /var/www/cap/App/Template/form.php on line 34.case 'text': ?>` is my line 34.
It crashes no matter how I arrange the order of case statements - always at the begining of second case.
<table class="showTable">
<?php foreach ($vars['fields'] as $name => $f) { ?>
<tr>
<td class="label"><?php echo $f['fancy']; ?></td>
<td>
<?php if(isset($f['readonly']) && $f['readonly'] === true) { ?>
<?php echo $vars['entity']->$name; ?>
<?php } else {
switch($f['type']) {
case 'string': ?>
<input type="text"
name="entity[<?php echo $name; ?>]"
<?php if(isset($f['required']) && $f['required'] === true) {?> required<?php} ?>
value="<?php echo $vars['entity']->$name; ?>" />
<?php break;
case 'text': ?>
<textarea name="entity[<?php echo $name; ?>]"
<?php if(isset($f['required']) && $f['required'] === true) {?> required<?php} ?>>
<?php echo $vars['entity']->$name; ?>
</textarea>
<?php break;
case 'float': ?>
<input type="number" step="0.01"
name="entity[<?php echo $name; ?>]"
<?php if(isset($f['required']) && $f['required'] === true) {?> required<?php} ?>
value="<?php echo $vars['entity']->$name; ?>" />
<?php break;
case 'integer': ?>
<input type="number" step="1"
name="entity[<?php echo $name; ?>]"
<?php if(isset($f['required']) && $f['required'] === true) {?> required<?php} ?>
value="<?php echo $vars['entity']->$name; ?>" />
<?php break;
}
} ?>
</td>
</tr>
<?php } ?>
</table>
I can appreciate keeping a template as primarily HTML. I couldn't spot the error, because your code unfortunately is hard to follow from all the in-and-out of PHP, plus some verbosity in the code. So my advice is to simplify your code, and keep it DRY (don't repeat yourself)
There's also a few conventions that make it easier (IMHO) to read when you are writing primarily in HTML:
Braces are hard to follow. Use the more verbose <?php if(condition): ?> ... markup ... <? endif; ?>
Keep open and closing php tags on the same line
Simplify your printing out of PHP variables: <?= $variable ?> is a more concise way than to write out the visually noisy <?php echo $variable; ?>
I tried my hand at writing the template, and I found that switch case just didn't lend itself to making the template easy to read; it's probably because switch is more a logic flow thing than a simple "show/don't show" decision.
Perhaps this will be useful to you. It doesn't answer your question per se, but it might help you get past it.
<table class="showTable">
<?php foreach ($vars['fields'] as $name => $f): ?>
<tr>
<td class="label"><?= $f['fancy'] ?></td>
<?php
// switch between read only, string,text, float, and integer
// 'case' statement makes great sense in PHP script,
// but is not so intuitive in a template
// reduce complicated, repeated terms to a simple variable
$type = isset($f['readonly']) && $f['readonly'] === true) ? 'readonly' : $f['type'];
$required = isset($f['required']) && $f['required'] === true) ? 'required' : '';
$value = $vars['entity']->$name;
// present alternate html for each presentation choice
?>
<td>
<?php if($type=='readonly'): ?>
<?= $value ?>
<?php elseif($type=='string'): ?>
<input type="text" name="entity[<?= $name ?>]" <?= $required ?> value="<?= $value ?>">
<?php elseif($type=='text'): ?>
<textarea name="entity[<?= $name ?>]" <?= $required ?>>
<?= $value ?>
</textarea>
<?php elseif($type='float'): ?>
<input type="number" step="0.01" name="entity[<?= $name ?>]" $required value="<?= $value ?>" />
<?php elseif($type='integer'): ?>
<input type="number" step="1" name="entity[<?= $name ?>]" $required value="<?= $value ?>" />
<?php endif; ?>
</td>
</tr>
</table>

PHP session echo checkbox and radio buttons

I am trying to echo checkbox names, however I am unable to echo the name of the checkbox as all that appears is a '1' if the checkbox or radio button has been checked.
Does anyone know how I can change my code so that if the user selects that they are a vegetarian and allergic to peanut, "Vegetarian, Peanut Allergy" is displayed on my page instead of the number "1" for each checked item.
I would also prefer the cost of sitting in the VIP area to be echoed as apposed to "Yes" or "No".
Here is my the relevant code for the checkboxes and radio buttons on my reservations page:
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['vege'] = isset($_POST['vege']);
}
if (isset($_POST['submit'])) {
$_SESSION['vegan'] = isset($_POST['vegan']);
}
if (isset($_POST['submit'])) {
$_SESSION['peanut'] = isset($_POST['peanut']);
}
if (isset($_POST['submit'])) {
$_SESSION['gluten'] = isset($_POST['gluten']);
}
if (isset($_POST['submit'])) {
$_SESSION['vip'] = isset($_POST['vip']);
}
?>
...
<strong>Dietary Requirements:</strong>
Vegetarian <input type="checkbox" name="vege" value="Vegetarian" <?php if(isset($_POST['vege'])) echo "checked='checked'"; ?>>
Vegan <input type="checkbox" name="vegan" value="Vegan" <?php if(isset($_POST['vegan'])) echo "checked='checked'"; ?>>
Peanut Allergy <input type="checkbox" name="peanut" value="Peanut Allergy" <?php if(isset($_POST['peanut'])) echo "checked='checked'"; ?>>
Gluten Allergy <input type="checkbox" name="gluten" value="Gluten Allergy" <?php if(isset($_POST['gluten'])) echo "checked='checked'"; ?>>
<strong> VIP area* : </strong> <br><br>
Yes (+£5) <input type="radio" name="vip" <?php if (isset($vip) && $vip=="Yes") echo "checked";?> value="Yes">
<br><span id="vip" class="error"><?php echo $vipErr;?></span><br>
No <input type="radio" name="vip" <?php if (isset($vip) && $vip=="No") echo "checked";?> value="No">
Here is the php I am currently using which echos "1" when the user makes a selection on my thank you page:
<b>Dietary Requirements: </b><?php echo $_SESSION['vege'];?><?php echo $_SESSION['vegan'];?><?php echo $_SESSION['peanut'];?><?php echo $_SESSION['gluten'];?>
<b>VIP Area Costs: </b>£<?php echo $_SESSION['vip'];?>
You assigned not the value to the session array! Because you used isset() as a assignment! And then you assigned 1 because isset returned 1, because they are set!
So try this:
<?php
session_start();
if ( !empty($_POST['vege']) )
$_SESSION['vege'] = $_POST['vege'];
if ( !empty($_POST['vegan']))
$_SESSION['vegan'] = $_POST['vegan'];
if ( !empty($_POST['peanut']))
$_SESSION['peanut'] = $_POST['peanut'];
if ( !empty($_POST['gluten']))
$_SESSION['gluten'] = $_POST['gluten'];
if ( !empty($_POST['vip']))
$_SESSION['vip'] = $_POST['vip'];
?>
Edit:
If you echo session index check if they are set like this:
<b>Dietary Requirements: </b>
<?php
if(isset($_SESSION['vege']))
echo $_SESSION['vege'];
if(isset($_SESSION['vegan']))
echo $_SESSION['vegan'];
if(isset($_SESSION['peanut']))
echo $_SESSION['peanut'];
if(isset($_SESSION['gluten']))
echo $_SESSION['gluten'];
?>
<b>VIP Area Costs: </b>£<?php if(isset($_SESSION['vip'])) echo $_SESSION['vip'];?>
Basically your error is displaying boolean from isset() function.
if you want to echo value just use
$_SESSION['vegan'] = isset($_POST['vegan']) ? $_POST['vegan']:"";
what does the code mean?
$x = $trueOrFalse ? $valueIfTrue : $valueIfFalse;
of course perform some sanitizing:
$_SESSION['vegan'] = htmlspecialchars($_POST['vegan']);
NEVER EVER ECHO PURE USER INPUT! Always sanitize! By not sanitizing user input you allow custom external scripts to easily be run as any HTML tag can be injected into the page such as <script>
Why are you checking your POST['submit'] variable 5 times?
You only need to check it once.
if (isset($_POST['submit'])) {
$_SESSION['vege'] = isset($_POST['vege']) ? $_POST['vege'];
$_SESSION['vegan'] = isset($_POST['vegan']) ? $_POST['vegan'];
$_SESSION['peanut'] = isset($_POST['peanut']) ? $_POST['peanut'];
$_SESSION['gluten'] = isset($_POST['gluten']) ? $_POST['gluten'];
$_SESSION['vip'] = isset($_POST['vip']) ? $_POST['vip'];
}

Categories