I try to create an order page on php. I have created a form which stores data into the database. The form number is based on the user and it is created dynamic.
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
echo '<form action="user_order_form.php" method="POST">';
echo '<html>';
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<input type="checkbox" name="yliko[]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
echo '<br>';
}
echo '<br>';
echo '<input type="submit" name="submit" value="ORDER">';
echo '</form>';
}
}
?>
So I have many forms and 1 script to handle them. If I submit 1 form then it applies the data to the database but the other forms dissapear. This is the second php 'handler'.
<?php
if (isset($_POST['submit']))
{
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
$item = $_SESSION['item'];
$temp = $_POST['yliko'];
$temp2 = implode(",", $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
?>
I want to submit all the forms. Should I try to create one submit button for all of the forms or is there a way to handle all of them separately ?
You can have many submit forms, but simply define one big <form> with all of them, then you will not lose any information.
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
echo '<html>';
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<input type="checkbox" name="yliko[]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
echo '<br>';
}
echo '<br>';
echo '<input type="submit" name="submit" value="ORDER">';
}
echo '</form>';
}
?>
now you can also add the ~$i~ identifier to input names, so you can easily distinguish which is which.
Related
$product = '';
$stmt = $verbinding->query("SELECT
product_category, product_id, parent FROM
Productcategory ORDER BY product_category");
$categorien = $stmt->fetchAll();
foreach($categorien as $cats){
if($cats['parent'] === $producten){
echo '<form action="product-list.php" method="post">
<input type="submit" name="cats" value="'. $cats['product_category'] .'"></form>';
echo $producten;
//var_dump($_POST);
if(isset($_POST['cats'])){
echo $_POST['cats'];
echo $cats['product_category'];
echo $cats['product_id'];
if($_POST['cats'] === $cats['product_category']){
$product = $cats['product_id'];
echo $product;
echo "gelukt!!";
}
}
}
}
So to update my question this is code that does partly work but does not get past the if($_POST['cats'] === $cats['product_id']){ statement. The problem is that my $_POST['cats'] just sends NO information. I can't understand why though. I should say though that I use the same "name" value in another form, but if I don't it wont even go through the if(isset($_POST['cats'])){ statement.
From your form the action page is "product-list.php", is it the same page you are handling the form logic in?
If not then your you need to write the code below in the product-list.php you created.
....
if(isset($_POST['categorien'])){
echo "pastcategory?";
if($_POST['categorien'] === $cat['product_category']){
$producten = $cat['product_id'];
echo "pastcategory!!!!";
echo $producten;
}
}
....
I'm using HTML, PHP and Ajax to toggle switch in my website. However, only the top most switch is functional. The reason why I use PHP is to display results from my DB, and Ajax is there to toggle switch without reloading the website. Thanks in advance and comment for any questions!
Photo Here :D I have three rows in the DB. Data retrieve fine. Top button works!
ps : removed all classes for simplicity
About main.php and recipe.inc.php. They are separated because recipe.inc.php is used in many documents.
main.php
<?php
$conn = mysqli_connect(localhost,****,****,loginsystem);
//DB connection
$query="SELECT * FROM `recipe` WHERE creator='$uid'";
//SQL Query
$results = mysqli_query($conn,$query);
$array = array();
//Array to save key column of the result in order
while ($row = mysqli_fetch_assoc($results)) {
for ($i = 0; $i < count($row[recipe_ID]); $i++) {
$array[$i] = $row[recipe_ID];
echo '<input type="hidden" id="recipe_ID" name="recipe_ID" value="';
echo $array[$i];
echo '">';
//might confuse you. this is just to hand over recipe_ID to recipe.inc.php
echo '<li>';
echo '<label>';
if($row[status]==1){
echo '<input type="checkbox" id="checkStatus" name="checkStatus" checked="">';
//In case where row[status] is equal to 1. means it's ON
}else{
echo '<input type="checkbox" id="checkStatus" name="checkStatus">';
//OFF otherwise
}
echo '<span class="switcher-indicator"></span>';
echo '</label>';
echo '</li>';
}
}
?>
recipe.inc.php
<?php
if(isset($_POST['checkStatus'])){
$recipe_ID = $_POST['recipe_ID']);
if($_POST['checkStatus']=='ON'){
$status = 1; //to save in DB as boolean. if ON->1
}else if($_POST['checkStatus']=='OFF'){
$status = 0; //if OFF->0
}
$sql = "UPDATE `recipe` SET `status`=$status WHERE creator=$uid AND recipe_ID=$recipe_ID";
//nev
mysqli_query($conn,$sql);
}
?>
and the Ajax part is saved in another js file.
recipe.js
$(document).ready(function() {
$('#checkStatus').on('click', function() {
var checkStatus = this.checked ? 'ON' : 'OFF';
var recipe_ID = $("#recipe_ID").val();
$.post("loginsystem/includes/recipe.inc.php", {
"checkStatus": checkStatus,
"recipe_ID": recipe_ID
},
function(data) {
$('#checkStatus').html(data);
});
});
});
That sounds like all the switches have the same ID. If that is the case, only the first one will work.
Try changing your code to look like this:
<?php
$conn = mysqli_connect(localhost,****,****,loginsystem);
//DB connection
$query="SELECT * FROM `recipe` WHERE creator='$uid'";
//SQL Query
$results = mysqli_query($conn,$query);
$cnt = 1;
$array = array();
//Array to save key column of the result in order
while ($row = mysqli_fetch_assoc($results)) {
for ($i = 0; $i < count($row[recipe_ID]); $i++) {
$array[$i] = $row[recipe_ID];
echo '<input type="hidden" id="recipe_ID-' .$cnt. '" name="recipe_ID" value="'; <============== HERE
echo $array[$i];
echo '">';
//might confuse you. this is just to hand over recipe_ID to recipe.inc.php
echo '<li>';
echo '<label>';
if($row[status]==1){
echo '<input type="checkbox" id="checkStatus-' .$cnt. '" name="checkStatus" checked="">'; //<============== HERE
//In case where row[status] is equal to 1. means it's ON
}else{
echo '<input type="checkbox" id="checkStatus-' .$cnt. '" name="checkStatus">'; //<================ HERE
//OFF otherwise
}
echo '<span class="switcher-indicator"></span>';
echo '</label>';
echo '</li>';
}
$cnt++; <=========== HERE
}
?>
I use this snippet to get vehicle data from a external database:
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'] ?>" class="vwe-kenteken-widget">
<p><input type="text" name="open_data_rdw_kenteken" value="<?php echo $_POST['open_data_rdw_kenteken'] ?>" maxlength="8"></p>
<p><input name="submit" type="submit" id="submit" value="<?php _e('Kenteken opzoeken', 'open_data_rdw') ?>"></p>
</form>
<?php if($data): ?>
<h3><?php _e('Voertuiggegevens', 'open_data_rdw') ?></h3>
<table>
<?php
$categories = array();
foreach ($data as $d) {
if( !is_array($fields) || in_array($d['name'], $fields) ) {
if( !in_array($d['category'], $categories) ) {
$categories[] = $d['category'];
echo '<tr class="open-rdw-header">';
echo '<td colspan="2" style="font-weight: bold;">';
echo ''.$d['category'].'';
echo '</td>';
echo '</tr>';
}
echo '<tr style="display:none">';
echo '<td>'.$d['label'].'</td>';
echo '<td>'.$d['value'].'</td>';
echo '</tr>';
}
}
?>
</table>
<?php endif; ?>
What i want to accomplish is that the data is loaded without the user have to enter a value and hit the submit button. The input value will get loaded based on the product page the user is viewing.
EDIT:
The data is loaded based on:
public function get_json() {
if ( isset( $_POST['kenteken'] ) ) {
$data = $this->rdw->get_formatted($_POST['kenteken']);
foreach ($data as $row) {
$json['result'][$row['name']] = $row['value'];
}
if ($_POST['kenteken']) {
if ($data[0]['value'] == '') {
$json['errors'] = __( 'No license plates found', 'open_data_rdw' );
}
else {
$json['errors'] = false;
}
}
else {
$json['errors'] = __( 'No license plate entered', 'open_data_rdw' );
}
header('Content-type: application/json');
echo json_encode($json);
die();
}
}
So instead of a $_POST action just get the data based on a pre-declared value that is different on each page.
Hard to answer - but I'll try to use my crystal ball.
$data comes from a database query, right?
I assume further, that the query takes the value from the open_data_rdw_kenteken form field to gather $data.
To have the table rendered, you have to fill $data with the right data. That implies that you must have a kind of default value for open_data_rdw_kenteken to get the data out of the DB. The default can be "all" which should reflect on your SQL Query or as your wrote "defined by product page".
Pseudo Code
$data = getData('BT-VP-41');
function getData($open_data_rdw_kenteken="")
{
$where = "";
if(!empty($open_data_rdw_kenteken)) {
$where = 'WHERE rdw_kenteken = "'.mysqli_real_escape_string($open_data_rdw_kenteken)';
}
$data = myslqi->query("SELECT * FROM dbTbl ".$where)
return $data;
}
As I wrote - this is pseudo code and will not run out of the box. You'll have to adapt that to your environment.
TL;DR: The line
<?php if($data): ?>
keeps you from rendering the table. To render you need $data filled with the right data.
Hope that will get you in the right direction.
I have an array with the names of medication which the user is currently taking. On the webpage, I want to display radio buttons with the name of each of the medications, which are currently being taken, next to them. The code I have for the array is;
//Current Entries Section
$CurrentMedsQuery = "SELECT Name FROM `".$username."medication` WHERE Status='Current';";
$RunMedsQuery = mysql_query($CurrentMedsQuery) or trigger_error(mysql_error().$CurrentMedsQuery);
$Count = mysql_num_rows($RunMedsQuery);
$CurrentMedsArray = array();
while ($CurrentMedEntries = mysql_fetch_array($RunMedsQuery)) {
array_push($CurrentMedsArray,$CurrentMedEntries['Name']);
}
$session =& JFactory::getSession();
$session->set('CurrentMedsArray', $CurrentMedsArray);
while ($Count < 0) {
}
$FirstMedEntry = ($CurrentMedsArray["0"]);
Then on my HTML form, I have the following code which successfully displays the name of the first element in the array as I want it to;
<form method="post" name="currentmeds" action="">
<input type="radio" name="med1" value="med1"><?php echo $FirstMedEntry;?><br>
</form>
But my question is, I will not know how many current medication entries the user has, therefore I cannot continuously use echo $FirstMedEntry, echo $SecondMedEntry and so on..I figure I need some sort of loop, and help would be greatly appreciated!
Thanks in advance!
Changed to the following as suggested;
//Current Entries Section
echo '<form method="post" name="currentmeds" action="">';
$CurrentMedsQuery = "SELECT Name FROM `".$username."medication` WHERE Status='Current';";
$RunMedsQuery = mysql_query($CurrentMedsQuery) or trigger_error(mysql_error().$CurrentMedsQuery);
$Count = mysql_num_rows($RunMedsQuery);
$count = 1;
while ($CurrentMedEntries = mysql_fetch_row($RunMedsQuery)) {
echo '<input type="radio" name="med' . $count . '" value="med' . $count . '">' . $CurrentMedEntries . '<br>';
$count++;
}
echo '</form>';
But now receiving this error;
Notice: Array to string conversion in C:\xampp\htdocs\Joomla-Lifestyle\components\com_jumi\files\medication.php on line 238
Line 238:
echo '<input type="radio" name="med' . $count . '" value="med' . $count . '">' . $CurrentMedEntries . '<br>';
$CurrentMedsArray contains all your data, so you can just loop through it and display the values:
<form method="post" name="currentmeds" action="">
<?php foreach ($CurrentMedsArray as $key => $entry): ?>
<input type="radio" name="med<?=$key+1?>" value="med<?=$key+1?>"><?=$entry;?><br>
<?php endforeach ?>
</form>
If the array isn't needed for this purpose, this could be modified and displayed inside your while loop instead. Also note <?=$var;?> is the short syntax for <?php echo $var; ?>.
You don't need to use an array and I'd suggest you don't. Just do the following:
<?php
echo '<form method="post" name="currentmeds" action="">';
$CurrentMedsQuery = "SELECT Name FROM `".$username."medication` WHERE Status='Current'";
$RunMedsQuery = mysql_query($CurrentMedsQuery) or trigger_error(mysql_error().$CurrentMedsQuery);
$Count = mysql_num_rows($RunMedsQuery);
$count = 1;
while ($CurrentMedEntries = mysql_fetch_row($RunMedsQuery)) {
echo '<input type="radio" name="med' . $count . '" value="med' . $count . '">' . $CurrentMedEntries['name'] . '<br>';
$count++;
}
echo '</form>';
?>
Although I strongly urge you to not use mysql_. Instead, use mysqli_ or PDO.
I have a list of favorite cars which i have added to each favorite car a checkbox for letting the user to remove the favorite car from his favorite car list. The problem is that the checkbox is working in a different way: If I check any car (1st, second.. last or multiple cars) and after hit submit the car that will get removed is the last one added instead of removing the selected one. If I check multiple cars, happens same thing, removes only the last car added.
PHP
public function GetFavoriteCars() {
include("inc/membersite_config.php");
$email = $fgmembersite->UserEmail(); // this is how I take the e-mail of the
global $base_path;
$FavoriteCars = $this->QueryResult("SELECT * FROM favoritecar WHERE email='$email'");
if (count($FavoriteCars)) {
$mystring='http://';
echo '<form action="" class="deletebutton" method="post">';
echo '<input type="submit" name="deletebtn" id="deletebtn" value="Submit">';
echo '<div class="roster_slideri-login">';
foreach ($FavoriteCars as $FavoriteCar) {
$carlink = $FavoriteCar->favoritecarlink;
echo '<div class="car-info-col-login">';
echo '<input type="checkbox" name="checkbox" value="'.$carlink.'" class="checkbox-login">';
$val=strpos($FavoriteCar->favoritecarimg,$mystring);
if ($val !== false) {
if($FavoriteCar->favoritecarimg!='') {
echo '<a href="'.$base_path.'detail-page_'.$FavoriteCar->favoritecarlink.'">';
echo '<img src="'.$FavoriteCar->favoritecarimg.'" alt="'.$FavoriteCar->favoritecartitle.'" width="160" height="120" />';
echo '</a>';
echo '<div class="name">'.substr($FavoriteCar->favoritecartitle,0,20).'</div>';
echo '</div>'; //car-info-col-login
}
} else {
echo '<a href="'.$base_path.'detail-page_'.$FavoriteCar->favoritecarlink.'">';
echo '<img src="'.$base_path.'uploads/no-img.jpg" alt="'.$FavoriteCar->favoritecartitle.'" width="160" height="120" />';
echo '</a>';
echo '<div class="name">'.substr($FavoriteCar->favoritecartitle,0,20).'</div>';
echo '</div>';
}
}
echo '</form>';
if (isset($_POST["checkbox"])) {
$this->QueryResult("DELETE from favoritecar WHERE email='$email' AND favoritecarlink='$carlink'");
echo '<script type="text/javascript">alert("Car had been deleted");</script>';
}
echo '</div>'; // div roster_slideri-login
}
}
Explaning:
$email = $fgmembersite->UserEmail(); - this is how I take the e-mail of the current logged in user. It will echo "email_of_logged_in_user#domain.com"
QueryResult is a custom function that looks like this. I usually use it for SELECTING purposes but it seams that is working for deleting purposes too.
abstract class DBDetails {
protected $link = NULL;
protected function connector() {
global $DBHOSTNAME;
global $DBUSERNAME;
global $DBPASSWORD;
global $DBNAME;
$this->link = mysqli_connect($DBHOSTNAME, $DBUSERNAME, $DBPASSWORD, $DBNAME) or die("Can't connect to MySQL server on localhost");
}
protected function close() {
mysqli_close($this->link);
}
}
abstract class N2 extends DBDetails {
public function QueryResult($strQuery) {
$this->connector();
$query = mysqli_query($this->link, $strQuery);
$arr = array();
if ($query) {
while ($result = mysqli_fetch_object($query)) {
array_push($arr, $result);
}
}
$this->close();
return $arr;
}
}
Expected output
When I check the checkbox of a car, it should delete only that car. If I check the checkboxes of multiple cars, should delete the specific cars that I checked.
Please help, I am quite a noob in checkboxes. I have checked lots of questions from here, but did not find my answer.
In this line :
echo '<input type="checkbox" name="checkbox" value="'.$carlink.'" class="checkbox-login">';
--------------
When using multiple checkboxes with same name , you would need to include [] in the name :
echo '<input type="checkbox" name="checkbox[]" value="'.$carlink.'" class="checkbox-login">';
----------------
Then $_POST["checkbox"] will be an array and you can use foreach on it to get all the checked values .
if( isset( $_POST["checkbox"] ) )
{
foreach( $_POST["checkbox"] as $value )
{
/* $value contains $carlink */
echo $value; // For test purpose
/* Sanitize and use it to identify and delete the corresponding row */
}
}
( Rather than name="checkbox[]" it might be better to choose another name . )