I need help figuring out how to move a array item up one place using PHP. The PHP so far is as follows:
<?php
$task_list = array();
$task_list[] = 'Write chapter';
$task_list[] = 'Edit chapter';
$task_list[] = 'Proofread chapter';
switch( $_POST['action'] ) {
case 'Promote Task':
//This is where I'm stuck.
?>
and the HTML:
<?php if (count($task_list) > 0 && empty($task_to_modify)) : ?>
<h2>Select Task:</h2>
<form action="." method="post" >
<?php foreach( $task_list as $task ) : ?>
<input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/>
<?php endforeach; ?>
<label>Task:</label>
<select name="taskid">
<?php foreach( $task_list as $id => $task ) : ?>
<option value="<?php echo $id; ?>">
<?php echo $task; ?>
</option>
<?php endforeach; ?>
</select>
<br />
<label> </label>
<input type="submit" name="action" value="Modify Task"/>
<input type="submit" name="action" value="Promote Task"/>
<input type="submit" name="action" value="Delete Task"/>
Any help would be much appreciated!
You only need to swap two rows (the selected task, and the task above). So if your indexes always are 0, 1, 2, 3, .., n:
$selectedRow = $_POST['taskid'];
if ($selectedRow === 0) {
echo 'Already top-priority';
} else {
$rowAbove = $taks_list[$selectedRow - 1];
$task_list[$selectedRow - 1] = $taks_list[$selectedRow];
$task_list[$selectedRow] = $rowAbove;
// Or without help-variable, but less readable
list($task_list[$selectedRow - 1], $task_list[$selectedRow])
= array($task_list[$selectedRow], $task_list[$selectedRow - 1]);
}
Related
I've search the forum for the same situation that I have but still couldn't find the solution. It's probably a piece of cake but I can't figure it out why my $_GET[] doesn't work.
I've created a product page and when I add something to the cart I want to display a message. I've made it work with the url in the form action but then my cart counter in the header stops working properly.
If it's possible I don't want to add any extra in the url like a "?success" because then it just keeps adding ?success to the url if I add more to the cart, that works in action but not with header() ?
Here is my code for the product page:
<?php include_once '../header.php';
$message = "";
$product = New Product;
$cart_data = [];
// if the variables are set - run the following statement
if(isset($_POST["addtocart"])) {
if(isset($_COOKIE["cart"])) {
// Removes backlashes and dont replace previous item, gives every item a new row.
$cookie_data = stripslashes($_COOKIE['cart']);
$cart_data = json_decode($cookie_data, true);
}
// Returns the productid and Size in the array
$item_list = array_column($cart_data, 'ProductsId');
$size_list = array_column($cart_data, 'Size');
// Returns the value if the statement is true
if(in_array($_POST["ProductsId"], $item_list) && in_array($_POST['selectedSize'], $size_list)) {
// A foreachloop that repeats the array value of the selected key variable.
foreach($cart_data as $keys => $values) {
if($cart_data[$keys]["ProductsId"] == $_POST["ProductsId"] && $cart_data[$keys]["Size"] == $_POST["selectedSize"]) {
$cart_data[$keys]["quantity"] = $cart_data[$keys]["quantity"] + $_POST["quantity"];
}
}
}
else {
$item_array = array(
'Img' => $Img = filter_var($_POST["Img"], FILTER_SANITIZE_STRING),
'ProductName' => $ProductName = filter_var($_POST["ProductName"], FILTER_SANITIZE_STRING),
'Size' => $Size = filter_var($_POST['selectedSize'], FILTER_SANITIZE_STRING),
'ProductsId' => $ProductsId = filter_var($_POST["ProductsId"], FILTER_SANITIZE_NUMBER_INT),
'Price' => $Price = filter_var($_POST["Price"], FILTER_SANITIZE_NUMBER_INT),
'quantity' => $quantity = filter_var($_POST["quantity"], FILTER_SANITIZE_NUMBER_INT),
);
$cart_data[] = $item_array;
}
$item_data = json_encode($cart_data);
setcookie('cart', $item_data, time() +(3600),'/');
header("location: product-detail.php?product=".$_GET['product']."?success");
}
if(isset($_GET['success'])) {
$message = "Varan lades till i varukorgen";
};
var_dump($message);
?>
<main id="product-content">
<section>
<form method="post" name="cartCount" action="">
<!-- product-detail.php?product=<?php echo $_GET['product']; ?> -->
<?php if(isset($_GET['product'])) {
$product->ProductsId = $_GET['product'];
$product->ProductId = $_GET['product'];
$product->ProductsId = $_GET['product'];
} else {
$product->ProductsId = $_POST['ProductsId'];
}
$result = $product->get_product();
$test = $product->get_productvariation();
while ($row = $result->fetch()) { ?>
<div class="product-card-detail">
<div class="product-image-wrapper">
<img class="product-image" src="../<?php echo $row['Img'];?>" >
<input type ="hidden" name="Img" value="<?php echo $row['Img'] ?>">
<?php $results = $product->get_images();
$Images = $results->fetch();
if(isset($Images['Image'])) { ?>
<img class="product-image" src="../<?php echo $Images['Image'];?>">
<?php } ?>
</div>
<div class="product-details-text">
<h2 class="title"><?php echo $row['ProductName']; ?></h2>
<input type ="hidden" name="ProductName" value="<?php echo $row['ProductName'] ?>">
<span class="price"><?php echo $row['Price'];?> SEK</span>
<input type ="hidden" name="Price" value="<?php echo $row['Price'] ?>">
<span class="select-title">Storlek</span>
<select class="size" name="selectedSize">
<?php while ($sizeRow = $test->fetch()) { ?>
<option>
<?php echo $sizeRow['Size']; ?>
</option>
<?php } ?>
</select>
<input type="hidden" name="quantity" value="1" />
<input type="submit" class="addtocart-btn" name="addtocart" value="Lägg i varukorgen"/>
<div><?php echo $message ?></div>
<input type ="hidden" name="ProductsId" value="<?php echo $row['ProductsId'] ?>">
<span class="title-description">Beskrivning</span>
<p class="description"><?php echo $row['Description']; ?></p>
</div>
</div>
<?php } ?>
</form>
</section>
</main>
<?php include_once "../footer.php";?>
I've made a test page that works exactly as expected so I can only think that is has to be something about the url?
Test code:
<?php
$message ="";
if(isset($_POST['submit'])) {
header("location: index.php?success");
}
if(isset($_GET['success'])) {
$message = "hello";
}
var_dump($message);
?>
<form method="post" action="">
<input text name="name" value="">
<input type="submit" name="submit" value="submit">
<?php echo $message ?>
</form>
Glad if anyone can see why it doesn't work!
You have made a mistake:
header("location: product-detail.php?product=".$_GET['product']."?success");
See the above line and notice that you are appending param success with ?.
Make it & as:
header("location: product-detail.php?product=".$_GET['product']."&success");
I am trying to update a database record using a submit button, however the form that information is being taken from has itself been populated by another submit button.
The PHP is below:
if (isset($_POST['edit']))
{
$editUser = User::locate($_POST['userSelect']);
$setCompany = Company::findCompany();
$exCompanyId = $editUser->user_company_id;
$isAdmin = $editUser->user_admin;
$eUserFirstname = $editUser->user_firstname;
$eUserLastname = $editUser->user_lastname;
$eUserUsername = $editUser->user_username;
$eUserEmail = $editUser->user_email;
$eUserCompany = $editUser->user_company;
$adminArray = array("Yes","No");
if ($exCompanyId > NULL)
{
$exCompany = Company::locateId($exCompanyId);
$companyValue = $exCompany->company_name;
}
else
{
$companyValue = "";
}
if ($isAdmin > 0)
{
$userAdmin = $adminArray[0];
}
else
{
$userAdmin = $adminArray[1];
}
}
if (isset($_POST['confirm']))
{
$updateUserRecord = User::locate($eUserUsername);
$newCompanyValue = $_POST['setCompany'];
$isAdmin = $_POST['userAdmin'];
$newCompany = Company::locate($newCompanyValue);
$companyId = $newCompany->company_id;
$updateUserRecord->user_company_id = $companyId;
$updateUserRecord->user_admin = $isAdmin;
$editUser->updateUserAdmin();
$message = "You have successfully updated the user account";
echo "<script type='text/javascript'>alert('$message');</script>";
}
The HTML code is below:
<form action="" method="post">
<p>
<label>First Name:</label>
<label><?php echo $eUserFirstname ?></label>
</p>
<p>
<label>Last Name:</label>
<label><?php echo $eUserLastname ?></label>
</p>
<p>
<label>Username:</label>
<label><?php echo $eUserUsername ?></label>
</p>
<p>
<label>Email Address:</label>
<label><?php echo $eUserEmail ?></label>
</p>
<p>
<label>User Company:</label>
<label><?php echo $eUserCompany ?></label>
</p>
<p>
<label>Set Company:</label>
<select name="setCompany">
<option><?php echo $companyValue ?></option>
<?php
foreach ($setCompany as $srow)
{
?>
<option id="<?=
$srow->company_id
?>">
<?=
$srow->company_name
?>
</option>
<?php
}
?>
</select>
</p>
<p>
<label>Administrator:</label>
<select name="userAdmin">
<option><?php echo $userAdmin ?></option>
<?php
foreach ($adminArray as $arow)
{
?>
<option>
<?=
$arow
?>
</option>
<?php
}
?>
</select>
</p>
<input type="submit" name="cancel" value="Cancel">
<input type="submit" name="confirm" value="Confirm">
</br>
</form>
From my investigations so far the variables aren't transferring to the 2nd if statement, and I'm not sure how to make them available to it.
Store the first form's submission in hidden input fields alongside your echo statements. For example: <input type="hidden" name="field_name" value="<?php echo htmlspecialchars($field); ?>">
Or, alternatively, update the DB after first form posts.
hello please help me i have a problem outputting all the values of checkbox it outputs only one i need to show all the checked checkbox and output them please help me here is the code it only shows one whenever i checked them all i need this
<html>
<head>
<title>Cake Form</title>
<link rel="stylesheet" href="cakeform.css">
</head>
<body>
<?php
$nameErr = $addErr = $phoneErr = $scake = $flavorcake = $fill = "";
$name = $address = $phone = $rcake = $fillr = $cakeflavor = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addErr = "Email is required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "Gender is required";
} else {
$phone = test_input($_POST["phone"]);
}
if(isset($_POST['SelectedCake'])){
$x=$_POST['SelectedCake'];
}
if(isset($_POST['CakeFlavor'])){
$y=$_POST['CakeFlavor'];
}
if(isset($_POST['Filling'])){
$z=$_POST['Filling'];
}
if(empty($x)){
$scake='Select one Cake';
}else{
$rcake= $x;
}
if(empty($y) OR $y == 'Flavor'){
$flavorcake='Select one flavor';
}else{
$cakeflavor= $y;
}
if(empty($z)){
$fill='Select at least one Fillings';
}else{
foreach($z as $item){
$fillr=$item;
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrap">
<div class="cont_order">
<fieldset>
<legend>Make your own Cake</legend>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<h4>Select size for the Cake:</h4>
<input type="radio" name="SelectedCake" value="Round6">Round cake 6" - serves 8 people</br>
<input type="radio" name="SelectedCake" value="Round8">Round cake 8" - serves 12 people</br>
<input type="radio" name="SelectedCake" value="Round10">Round cake 10" - serves 16 people</br>
<input type="radio" name="SelectedCake" value="Round12">Round cake 12" - serves 30 people</br>
<span class="error">*<?php echo $scake;?></span>
<h4>Select a Cake Flavor: </h4>
<select name="CakeFlavor">
<option value="Flavor" selected="selected">Select Flavor</option>
<option value="Carrot" >Carrot</option>
<option value="Chocolate" >Chocolate</option>
<option value="Banana" >Banana</option>
<option value="Red Velvet" >Red Velvet</option>
<option value="Strawberry" >Strawberry</option>
<option value="Vanilla" >Vanilla</option>
<option value="Combo" >Combo</option>
</select>
<span class="error">*<?php echo $flavorcake;?></span>
<h4>Select Fillings:</h4>
<label><input type="checkbox" name="Filling[]" value="Cream"/>Cream</label><br>
<label><input type="checkbox" name="Filling[]" value="Fudge"/>Fudge</label><br>
<label><input type="checkbox" name="Filling[]" value="Ganache"/>Ganache</label><br>
<label><input type="checkbox" name="Filling[]" value="Hazelnut"/>Hazelnut</label><br>
<label><input type="checkbox" name="Filling[]" value="Mousse"/>Mousse</label><br>
<label><input type="checkbox" name="Filling[]" value="Pudding"/>Pudding</label><br>
<span class="error">*<?php echo $fill;?></span>
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<legend>Contact Details</legend>
<label for="name">Name</label><br>
<input type="text" name="name" id="name"><span class="error">*<?php echo $nameErr;?></span>
<br>
<label for="address">Address</label><br>
<input type="text" name="address" id="address"><span class="error">*<?php echo $addErr;?></span>
<br>
<label for="phonenumber">Phone Number</label><br>
<input type="text" name="phone" id="phone"><span class="error">*<?php echo $phoneErr;?></span><br>
</fieldset>
<input type="submit" name="submitted" id="submit" value="Submit"/>
</div>
</form>
<div class="cont_order">
<?php
echo $name.'<br>';
echo $address.'<br>';
echo $phone.'<br>';
echo $rcake.'<br>';
echo $cakeflavor.'<br>';
echo $fillr.'<br>';
?>
</div>
</div>
</body>
</html>
You can do this:
var_dump($_POST['Filling']);
Or just this:
<?php
if(!empty($_POST['Filling'])) {
foreach($_POST['Filling'] as $check) {
echo $check;
}
}
?>
Tell me if it works =)
Fact is, you accept a list for filling.
In your code you do this :
foreach($z as $item){
$fillr=$item;
}
Replace it by :
$fillr = '';
foreach($z as $item){
$fillr .= '- ' . $item . '<br/>';
}
It should work better.
For comment :
#so let's say $z is an array :
$z = [1,2,3,4];
#then you say, for each element of the array as you will call $item, I do something
foreach($z as $item){
$fillr=$item; #here you say : for each element of $z (1,2,3,4), I put this value into $fillr.
}
#so let's do the loop together.
# First pass, $item == 1, so $fillr == 1.
# Second pass, $item == 2, so $fillr == 2.
# ...
# Last pass, $item == 4, so $fillr == 4.
# so then when you show $fillr it's the last item of the list (here 4).
# using PHP, .= means concatenate.
# for instance :
$a = "hello ";
$a .= "world";
echo $a;
> hello world
So basically, what I'm doing is :
Having an empty string I'll call $fillr.
For every element of the list,
Append "the_element plus a <br/>" to $fillr
so then when you output $fillr it looks sexy.
Do you get it bud?
Why is my Captcha returning False when it should be true?
When I first submit the form, with the correct answer, it says 'captcha not fine'. When I submit it a second time, again, with the correct answer, it says 'captcha fine'. Any ideas?
<?php
if ($_POST['submitted']==1) {
$submitted = 1;
$captchas = Array();
# Create a single entry
$captchas[] = array(
"question" => "What colour is the sky?",
"answer" => "Blue",
"options" => array("Blue", "Red", "Orange")
);
$tabindex = 5;
$captcha_index = rand(0, count($captchas) - 1);
$comment_captcha_idx = trim($_POST['captcha_index']);
$comment_captcha = trim($_POST['captcha']);
if ( !is_numeric($comment_captcha_idx) || !$comment_captcha || $captchas[$comment_captcha_idx]["answer"] != $comment_captcha)
{
$errormsg[] = "CAPTCHA";
}
if ($errormsg == '') {
echo 'captcha fine';
} else {
echo 'captcha not fine';
}
}
?>
<div>
<form action="test.php" method="post">
<input type="hidden" name="captcha_index" value="<?php echo $captcha_index; ?>" />
<hr />
<h2>Captcha</h2>
<?php
$captchas = Array();
# Create a single entry
$captchas[] = array(
"question" => "What colour is the sky?",
"answer" => "Blue",
"options" => array("Blue", "Red", "Orange")
);
$tabindex = 5;
$captcha_index = rand(0, count($captchas) - 1);
$comment_captcha_idx = trim($_POST['captcha_index']);
$comment_captcha = trim($_POST['captcha']);
echo $captchas[$captcha_index]["question"];
?>
<?php
foreach ($captchas[$captcha_index]["options"] as $captcha_answer) {
?>
<br /><label for="captcha_<?php echo $captcha_answer; ?>">
<input tabindex="<?php echo $tabindex++; ?>"
id="captcha_<?php echo $captcha_answer; ?>" type="radio"
name="captcha" value="<?php echo htmlspecialchars($captcha_answer); ?>"
/><?php echo $captcha_answer; ?></label>
<?php
}
?>
</p>
<p>
<input type="submit" value="Send my order" name="Submit" />
<input type="hidden" name="submitted" value="1" />
</p>
<p> </p>
</form>
</div>
For the below example everything works as expected when ALL the checkboxes are checked. The problem occurs when one or more (but NOT all of them) are checked.
<form action="someaction" method="post">
<?php foreach ($fields as $field) { ?>
<input type="checkbox" name="checkpid[]" value="<?php echo $field['pid']; ?>">
<input type="hidden" name="checkprice[]" value="<?php echo $field['price']; ?>">
<input type="submit" name="submit" value="Submit">
<?php } ?>
</form>
<?php if (isset($_POST['checkpid'])) { ?>
<?php
$checkpid = $_POST['checkpid'];
$checkprice = $_POST['checkprice'];
?>
<?php foreach ($checkpid as $key => $checkpid) { ?>
<?php
$eachpid[] = $checkpid.",".$checkprice[$key];
?>
<?php } ?>
<?php print_r($eachpid), ?> // the $checkpid is always as expected, but the $checkprice does not match its row.
<?php } ?>
With my little knowledge I suspect it is something wrong in the declaration of the $key, but I am overwhelmed.
this is all i can suggest.
instead of adding two input how about adding the two data in value of a checkbox input separated with |. then when submitted just explode the value and receive array 1 for id and 1 for price.
<?php
if (isset($_POST['checkp'])) {
$checkp = $_POST['checkp'];
foreach ($checkp as $check) {
$c = explode("|", $check);
$eachpid[] = $c[0].",".$c[1];
}
print_r($eachpid);
}
?>
<form action="" method="post">
<?php foreach ($fields as $field) { ?>
<input type="checkbox" name="checkp[]" value="<?php echo $field['pid']; ?>|<?php echo $field['price']; ?>">
<?php } ?>
<input type="submit" name="submit" value="Submit">
</form>