using php 'if - clause' in form attribute inside a php function - php

Im building a simple element to show search results. I'm using a php function, so I can while-loop the results and display them.
The function is named search_results and looks like this:
<?php
function search_results($u_country, $user_name, $business_user, $brand_name, $product_name, $up_condition, $up_commentary, $up_price, $up_shipping, $up_amount, $up_id) {
$element = "
<div>
<form action='search.php' method='post'>
<div class='search_body'>
<span class='country'>$u_country</span>
<span class='username'>$user_name</span>
<span class='business_user'>$business_user</span>
<span class='product_name'>$product_name</span>
<span class='up_condition'>$up_condition</span>
<span class='commentary'>$up_commentary</span>
<span class='price'>$up_price</span>
<span class='amount'>$up_amount</span>
<span>
<input type='number' name='up_amount' min='1' max='$up_amount' placeholder='1'>
</span>
<span>
<input type='hidden' name='product_id' value='$up_id'>
</span>
<span>
<button type='submit' name='add_cart' disabled='".if(!isset($_SESSION['username']))."'>Warenkorb</button>
</span>
</div>
</form>
</div>
";
echo $element;
};
But I want to implement some php in some of the attributes. For example I want to disable the "add_cart" button if the user is not logged in. But if i use some php inside the html form it always crushes.
if I put the form in single quotes and every attribute in double quotes it won't translate the variables.
my understanding is that i have to end a html string with " and use a . to separate it from the php part, but I can't make it work.
Is there something I'm missing? is it not possible to mix in php into a html form while inside a function?
couldn't find a solution for this and looked through the other threads but couldn't find anything relative.
Sorry if this is a dumb question I'm still learning to code.
if I put the form in single quotes and every attribute in double quotes it won't translate the variables.
I want to further use php inside the attributes of the form to make the results more interactive. For example i want the displayed name of the product to be a link to the product page so it will need to use a variable for that.

Break you code up into bits that do works and use $element .= .... to concatenate the working bits into the variable
For example
function search_results($u_country, $user_name, $business_user, $brand_name,
$product_name, $up_condition, $up_commentary, $up_price,
$up_shipping, $up_amount, $up_id)
{
$element = "<div>
<form action='search.php' method='post'>
<div class='search_body'>";
$element .= "<span class='country'>$u_country</span>
<span class='username'>$user_name</span>
<span class='business_user'>$business_user</span>
<span class='product_name'>$product_name</span>
<span class='up_condition'>$up_condition</span>
<span class='commentary'>$up_commentary</span>
<span class='price'>$up_price</span>
<span class='amount'>$up_amount</span>
<span>
<input type='number' name='up_amount' min='1' max='$up_amount' placeholder='1'>
</span>
<span>
<input type='hidden' name='product_id' value='$up_id'>
</span>
<span>";
$t = ''; // default to not disabled
if(!isset($_SESSION['username'])){
$t = " disabled='disabled' ";
}
$element .= "<button type='submit' name='add_cart' $t>Warenkorb</button>
</span>
</div>
</form>
</div>";
echo $element;
}

step 1: run the code (the button will be disabled)
step 2 refresh the page then the button is not anymore disabled(f5 key,..)
step 3 delete cookies so the button will be disabled again and proceed with the step 2
this is an "environment" to prove you the function can work.
if you really need echo $element; part then drop the return ... and replace it ..
good luck
<?php
function search_results($u_country, $user_name, $business_user, $brand_name, $product_name, $up_condition, $up_commentary, $up_price, $up_shipping, $up_amount, $up_id,$onoff) {
$onoffanswer=($onoff?'disabled':'');
return <<<stuff
<div>
<form action='search.php' method='post'>
<div class='search_body'>
<span class='country'>$u_country</span>
<span class='username'>$user_name</span>
<span class='business_user'>$business_user</span>
<span class='product_name'>$product_name</span>
<span class='up_condition'>$up_condition</span>
<span class='commentary'>$up_commentary</span>
<span class='price'>$up_price</span>
<span class='amount'>$up_amount</span>
<span>
<input type='number' name='up_amount' min='1' max='$up_amount' placeholder='1'>
</span>
<span>
<input type='hidden' name='product_id' value='$up_id'>
</span>
<span>
<button type='submit' name='add_cart' {$onoffanswer}>Warenkorb</button>
</span>
</div>
</form>
</div>
stuff;
};
session_start();
echo search_results(
'country'
,'username'
,'businessuser'
,'brandname'
,'productname'
,'upcondition'
,'commentary'
,'upprice'
,'upshipping'
,'upamount'
,'1111'
,!isset($_SESSION['username'])
);
print_r ($_SESSION);//phpinfo();
$_SESSION['username']='eeee';
?>

Related

Can you use forms within PHP echo?

I'm trying to echo a form from within an echo statement in my PHP code, everything works except for the submit button, when I click it, it just takes me to the same page I'm in instead of purchase.php
It works when I copy the form out of PHP and use paste it in plain html but that doesn't serve what I need, why would the action of a form not work in a PHP echo?
I tried using escape characters for the quotations, starting a completely fresh echo statement, seperated it from the others, nothing worked, I keep getting redirected to the same page like it's an empty submit button
if($_POST['SELECTION'] == "sony"){
$data=mysqli_query($conn,"SELECT * FROM products where prod_type = 'sony' ");
while($row=mysqli_fetch_assoc($data)){
echo"
<div class='w3-quarter'>
<img src='".$row['img_link']."' width='200px' height='300px' alt='iphone12' style='width:100%'>
<h3>".$row['prod_name']."</h3>
<p>".$row['prod_desc']."</p>
<p>".$row['prod_price']."</p>
<p>". "<form method='POST' action='purchase.php'> <div id = 'hidden' > <input type ='text' name='ninjaid' value='".$row['prod_id']."' > </div> <input type='submit' name='buy' value='Buy'> </form>"." </p>
";
}
use single quote on the outside and double quotes inside working
fine
echo '
<div class="w3-quarter">
<img src="'.$row['img_link'].'" width="200px" height="300px" alt="iphone12" style="width:100%">
<h3>"'.$row['prod_name'].'"</h3>
<p>"'.$row['prod_desc'].'"</p>
<p>"'.$row['prod_price'].'"</p>
<p><form method="POST" action="purchase.php"> <div id = "hidden" > <input type ="text" name="ninjaid" value="'.$row['prod_id'].'" > </div> <input type="submit" name="buy" value="Buy"> </form></p>';
Use curly braces to enclose variables {$var} instead ."$var". to avoid problems with arrays
if($_POST['SELECTION'] == "sony"){
$data=mysqli_query($conn,"SELECT * FROM products where prod_type = 'sony' ");
while($row=mysqli_fetch_assoc($data)){
echo"
<div class='w3-quarter'>
<img src='{$row['img_link']}' width='200px' height='300px' alt='iphone12' style='width:100%'>
<h3>{$row['prod_name']}</h3>
<p>{$row['prod_desc']}</p>
<p>{$row['prod_price']}</p>
<p><form method='POST' action='purchase.php'> <div id = 'hidden' > <input type ='text' name='ninjaid' value='{$row['prod_id']}' > </div> <input type='submit' name='buy' value='Buy'> </form>"." </p>
";
}

extract the datas from a array using php

i searched previous sample questions but those are not helpful my question..
My task is i have several types of rooms in my hotel. when i select the rooms, after submit the form the room numbers and price details should be store into redirected page.
i use this command
here I modified my code like below
<?php while($row24 = mysql_fetch_array($result24)):;?>
<div class="item-gallery isotope-item bo-rad-10 hov-img-zoom triple">
<?php echo "<img src='images/$row24[pic]' alt='IMG-GALLERY'>"?>
<div class="overlay-item-gallery trans-0-4 flex-c-m">
<?php echo "<a class='btn-show-gallery flex-c-m fa fa-search' href='images/$row24[pic]' data-lightbox='gallery'></a>"?>&nbsp &nbsp
<?php echo "<label class='container1 txt17'>Select Room
<input type='checkbox' name = 'check_list[]' value='$row24[roomno] ,$row24[price]'>
<span class='checkmark'></span>
</label>"?>
</div>
<div class="line-item-mainmenu text-blo3 size21 flex-col-l-m">
<?php echo "<span class='txt20 m-b-3'>" .'Room No : '
.$row24['roomno'].
"</span>"?>
<?php echo "<input type='text' class=' txt16 m-b-3'>".'Price &nbsp &nbsp &nbsp : '
.$row24['price']."&nbsp &nbsp<i class='fa fa-rupee'></i>"."&nbsp &nbsp(One Night )" ?>
</div>
</div>
<?php endwhile;?>
by using this code i get he results which i expect. but my problem is how to extract price from that array
When including object/array elements in strings, you need to wrap them with {} so they will be parsed properly.
For example
<?php echo "<img src='images/$row24[pic]' alt='IMG-GALLERY'>"?>
should be
<?php echo "<img src='images/{$row24[pic]}' alt='IMG-GALLERY'>"?>
Aside from that, it does not matter what room is selected, all these form fields (minus those unchecked input boxes) are going to be submitted and you'll have a tough time trying to parse the data out.
If, at the very least, assign roomno as an associative key for each of your fields, for example:
<input type='checkbox' name = 'check_list[]' value='{$row24[roomno]}'>
<input type='text' name='price[]' value='{$row24[roomno][price]}' />
That way, at least you can iterate through the $_POST, price field(s) based on the roomno key selection(s).

Multiple dynamic contact forms

I have built a inquiry form on my website, the idea is instead of mailing me each time a user submits a query it is added to my database which I can then go and view via my backend system
Each query will be listed one by one with a text-area contact form below it allowing me to reply to each query individually
So far I have this (sorry it's a bit messy)
foreach ($listings as $row){
$loop.= "<h3 class='text-center'>".$row['question']."</h3>";
$loop.= "<p>".$row['message']."</p>";
$loop.= "Name: <b>".$row['name']."</b>";
$loop.= "<span class='pull-right'>Email: <b>".$row['email']."</b><br></span>";
$loop.= "<div class='clearfix'></div>";
if(isset($row['website'])){ $loop.="Website: <b>".$row['website']."</b>"; }
$loop.= "<span class='pull-right'>Date: <b>".$row['date']."</b></span>";
$loop.= "<form name='submit-response' method='POST'><fieldset>";
$loop.= "<div class='form-group'> <label for='Message".$counter."'>Your Message</label> <textarea id='Message".$counter."' name='Message".$counter."' class='form-control' rows='5'></textarea> </div>";
$loop.= "<button type='submit' name='submit".$counter."' class='btn btn-default btn-block'>Reply</button>";
$loop.= "</fieldset></form>";
}
Before that is a foreach loop and the start of the oh and $counter is set to nill
What I want is for each contact form to be unique so when I click send on one of the queries it will be sent and removed so I can send another, the only issue I am having is working out how I will work out if a submit has been hit, and which submit has been hit
The code will need to workout which button has been hit and depending on which button it will then mail() to the recipient
I'm quite stuck on this one and I'm not sure of the best course of action so any advice is really appreciated
Luke
If you click a submit button inside a <form> tag, then only that form will be submitted.
You could include a hidden field with the ID of the row in it. That way you could get rid of the $counter variables altogether.
Also if you plan on just echoing out the $loop html, I wouldn't recommend storing the HTML in a PHP variable.
<?php
foreach ($listings as $row)
{
?>
<h3 class="text-center"><?php echo $row['question']; ?></h3>
<p><?php echo $row['message']; ?></p>
Name: <b><?php echo $row['name']; ?></b>
<span class="pull-right">Email: <b><?php echo $row['email']; ?></b><br></span>
<div class="clearfix"></div>
<?php
if(isset($row['website']))
{
?>
Website: <b><?php echo $row['website']; ?></b>
<?php
}
?>
<span class="pull-right">Date: <b><?php echo $row['date']; ?></b></span>
<form action="" name="submit-response" method="POST">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
<fieldset>
<div class="form-group">
<label>Your Message</label>
<textarea name="Message" class="form-control" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-default btn-block">Reply</button>
</fieldset>
</form>
<?php
}
?>
add a unique id to your database table, and put it in a hidden input.
Give each form a id, and possibly each submit button a unique name. This way you can easily determine which submit button was hit, or which form was submitted, and remove it or process it via javascript.
$('form').each(function() {
$(this).submit(function(event) {
event.preventDefault();
// Add AJAX code here
$(this).remove();
});
});
Of course that was pseudo-code.

Only one value from an hidden input is being displayed

<?php
foreach($_color_swatch as $_inner_option_id){
preg_match_all('/((#?[A-Za-z0-9]+))/', $_option_vals[$_inner_option_id]['internal_label'], $matches);
if ( count($matches[0]) > 0 ) {
$color_value = $matches[1][count($matches[0])-1];
?>
<li>
<input type="hidden" id="fakecolor" value="<?php echo $color_value;?>"/>
<div onclick="alert(document.getElementById('fakecolor').value);">
<img src="<?php echo $color_value;?>.png" /></div>
</li>
<?php
}
}
?>
This works for displaying the images, using the $color_value but i need to pass the value from hidden input to another javascript function.
And when i click on div it displays only one value no matter how many are inside the foreach.
Can anyone give me a little help? Thanks.
This is the output:
<li>
<input type="hidden" id="fakecolor" value="red"/>
<div onclick="alert(document.getElementById('fakecolor').value);"><img src="red.png"/></div>
</li>
<li>
<input type="hidden" id="fakecolor" value="blue"/>
<div onclick="alert(document.getElementById('fakecolor').value);"><img src="blue.png"/></div>
</li>
<li>
<input type="hidden" id="fakecolor" value="white"/>
<div onclick="alert(document.getElementById('fakecolor').value);"><img src="white.png"/></div>
</li>
<li>
<input type="hidden" id="fakecolor" value="green"/>
<div onclick="alert(document.getElementById('fakecolorx').value);"><img src="green.png"/></div>
</li>
But when i click on each of the divs, it displays only the value of the second, blue.
Try something like this:
<?php
$cont = 0;
foreach($_color_swatch as $_inner_option_id){
preg_match_all('/((#?[A-Za-z0-9]+))/', $_option_vals[$_inner_option_id]['internal_label'], $matches);
if ( count($matches[0]) > 0 ) {
$color_value = $matches[1][count($matches[0])-1];
?>
<li>
<input type="hidden" id="fakecolor<?php echo $cont; ?>" value="<?php echo $color_value;?>"/>
<div onclick="alert(document.getElementById('fakecolor<?php echo $cont; ?>').value);">
<img src="<?php echo $color_value;?>.png" /></div>
</li>
<?php
}
$cont = $cont + 1;
}
?>
In this way every input hidden have a different id, the same whit the onclick function.
Saludos ;)
I dont quite understand what you're trying to do, still:
<input type="hidden" id="fakecolor" value="<?php echo $color_value;?>"/>
<div onclick="alert(document.getElementById('fakevalue').value);">
First line: you're using an unique id while looping so you'll get several elements with the same id and you'll always end up with the first one with document.getElementById.
Second line: aren't you supposed to get the value of the hidden field ? (ie #fakecolor and not #fakevalue as you're getting).
You have multiple IDs on the same page which will cause getElementById to fail. Why don't you loop and construct your JavaScript like so:
<div onclick="alert("<?php echo $color_value; ?>");">
If you ever move from just alert you can have whatever JavaScript function with a string parameter to accept the color value.

How to get ID from another file in php?

I'm going to make edit menu in my web. so I direct the page from product into edit page. What I'm confused is how to get the productID from product's page to use in edit page?
Here is my code in product
<?php $query= "SELECT * FROM game";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<div class="gameBox">
<div style="margin:5px;">
<?php echo "<image src=\"images/".$data['gameId'].".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <?php echo $data['gameName'];?></div>
<div class="myLabel">Developer</div><div>: <?php echo $data['gameDeveloper']; ?></div>
<div class="myLabel">Price</div><div>: $ <?php echo $data['gamePrice']; ?></div>
<br />
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
<input type="button" value="Delete"/>
</div>
</div>
<?php } ?>
and it's my code in edit page
<?php include("connect.php");
$id[0] = $_REQUEST['id'];
$query = "SELECT * FROM game WHERE gameId=".$id."";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<form action="doUpdate.php" method="post">
<?php echo "<image src=\"images/".$id.".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <input type="text" value="<?php echo $data['gameName'];?>" id="gameName" name="gameName"/></div>
<div class="myLabel">Developer</div><div>: <input type="text" value="<?php echo $data['gameDeveloper'];?>" id="gameDeveloper" name="gameDeveloper"/></div>
<div class="myLabel">Price</div><div>: <input type="text" value="<?php echo $data['gamePrice'];?>" id="gamePrice" name="gamePrice"/></div>
<br/>
<div id="txtError">
<!--error message here-->
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/></span>
<?php } ?>
When I try to access edit page, there's an error it said
"Undefined index:$id[0] = $_REQUEST['id'];"
in edit page.
Could anyone help me?
It looks like you're confusing two methods of passing data between pages, forms and query strings in <a href...>s.
Forms:
Data is in <input>-type elements (or friends) and inside a <form...> tag.
For example
<form action="handler.php">
<input type="text" name="var1" />
<input type="text" name="var2" />
<input type="submit">
</form>
Usually passed via POST and accessed in PHP via $_POST.
For example, the values in the text boxes referenced above would be accessed with something like:
<?php
echo $_POST['var1']; // First text box
echo $_POST['var2']; // Second text box
Links:
Passed as query strings in <a href...>, for example:
Click Me
Usually passed via GET and accessed in PHP via $_GET.
For example, the values in the query string provided above would be accessed with something like
<?php
echo $_GET['var1']; // "foo"
echo $_GET['var2']; // "bar"
So in this case it looks like you're hyperlinking an input button -- which is not the usual way to do things, but you would fix it by changing this:
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
To, this
<input type="button" value="Edit"/>
And then reference the variable in edit.php as $_GET['id'].
But since you know it's going to be an integer and nothing else, something like:
$id = (int)$_GET['id'];
Is good enough sanitation (at least for that variable).
Lastly, I notice you assign a variable to $id[0] but then reference $id. Assigning a variable to $id[0] is not the same as assigning it to $id, as $id is an array in the former and an integer in the latter. It seems to me that you can just drop the [0] w.r.t. $id in your edit.php
You can pass through the query string
<a href="edit.php?<?php $id=$data['gameId'];?>>
In this case your PHP code will get change to
$id[0] = $_SERVER['QUERY_STRING'];
Add the id as a parameter to your edit url:
<input type="button" value="Edit"/>
also at the top of your edit.php:
$id = $_REQUEST['id'];

Categories