Please help me. Thanks
I have a form which contains function's javascript and in function's javascript contains html code.
My question is : how to send in database my form ?
This is my form :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Créer une facture</title>
<link rel="stylesheet" href="style.css" media="all" />
</head>
<body>
<form action="affiche.php" method="post">
<fieldset>
<legend>Contenu de la facture formation</legend>
<div id="ID_container">
<textarea name="prestation[]" rows="4"
placeholder="Prestation" required></textarea>
<input type="number" placeholder="Nombre de jours" name="nbjours[]" required>
<input type="number" placeholder="Tarif journalier" name="tarifjour[]" required>
</div>
<button onclick="ajout(this);">+ Ajouter une prestation</button>
<br/><br/>
<input type="submit" name="envoyer" value="Envoyer"/>
</fieldset>
</form>
<script src="js/fonct.js"></script>
</body>
</html>
This is function JS:
function ajout(element){
var container = document.getElementById('ID_container');
var str ='<span><textarea name="prestation[]" rows="4" type="text" placeholder="Prestation"></textarea> </span><span><input name="nbjours[]" type="number" placeholder="Nombre de jour"> </span><span><input name="tarifjour[]" type="number" placeholder="Tarif journalier"> </span><span><input type="button" onclick="suppression(this)"; value="x"></span><br/>';
var divNewExp = document.createElement("div");
divNewExp.innerHTML = str ;
container.appendChild(divNewExp);
}
function suppression(element){
var container = document.getElementById('ID_container');
container.removeChild(element.parentNode.parentNode);
}
Here i want send these data in database and displays data, but it is not work, data are not send in database :
<?php
require_once 'connexion.php';
// On vérifie si la variable existe et sinon elle vaut NULL
$prestation = isset($_POST['prestation']) ? $_POST['prestation'] : NULL;
$nbjours = isset($_POST['nbjours']) ? $_POST['nbjours'] : NULL;
$tarifjour = isset($_POST['tarifjour']) ? $_POST['tarifjour'] : NULL;
//On récupère les différentes valeurs sous forme d'une chaine de caractères séparées par une virgule
$prestation=implode(",", $_POST['prestation']);
$nbjours=implode(",", $_POST['nbjours']);
$tarifjour=implode(",", $_POST['tarifjour']);
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour)
VALUES ("'.$prestation.'", "'.$nbjours.'", "'.$tarifjour.'")');
$req->execute(array( 'prestation'=> $prestation,
'nbjours'=> $nbjours,
'tarifjour'=> $tarifjour));
echo "les données ont bien étés insérées dans la base de données";
$base = null;
?>
<tr>
<?= foreach((array)$req as $presta) ?>
<td class="desc"><?php echo $presta['prestation'] ?></td>
<td class="qty"><?php echo $presta['nbjours'] ?></td>
<td class="unit"><?php echo $presta['tarifjour'] ?></td>
<td class="total"><?php echo $presta['tarifjour'] * $presta['nbjours'] ?></td>
</tr>
You're trying to get data from INSERT request, and you're not using prepare/execute properly. It just can't work the way you made it.
As aynber said, you should read PDO documentation
Here is some tips that can help you out :
1. Fix your prepare statement / execute
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour) VALUES (:prestation, :nbjours, :tarifjour)');
$req->execute(array(
':prestation' => $prestation,
':nbjours' => $nbjours,
':tarifjour' => $tarifjour
));
I guess you need to add one row for each of your prestation, not saving every added prestation in one row, so you have to update your query to reflect that
// generate request params
$params = [];
$values = '';
foreach ($_POST['prestation'] as $key => $prestation) {
$params[':prestation' . $key] = $prestation;
$params[':nbjours' . $key] = $_POST['nbjours'][$key];
$params[':tarifjour' . $key] = $_POST['tarifjour'][$key];
$values .= '(:prestation' . $key . ', :nbjours' . $key . ', :tarifjour' . $key . '),';
}
// remove trailing ","
$values = rtrim($values, ',');
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour) VALUES ' . $values);
// insert every rows in DB
$req->execute($params);
2. Generate rows from posted data or fetch them from database
In this example, I'll only show you the first option
// prepare facturation data
$facturation[] = [
'prestation' => $prestation,
'nbjours' => $_POST['nbjours'][$key],
'tarifjour' => $_POST['tarifjour'][$key],
];
<?php foreach ($facturation as $presta) : ?>
<tr>
<td class="desc"><?= $presta['prestation'] ?></td>
<td class="qty"><?= $presta['nbjours'] ?></td>
<td class="unit"><?= $presta['tarifjour'] ?></td>
<td class="total"><?= $presta['tarifjour'] * $presta['nbjours'] ?></td>
</tr>
<?php endforeach; ?>
3. Fix your buttons to prevent submitting form when using + or x buttons
As Magnus Eriksson said, you need to add type="button" in your button elements.
In your index file, use
<button type="button" onclick="ajout(this);">+ Ajouter une prestation</button>
Instead of
<button onclick="ajout(this);">+ Ajouter une prestation</button>
In fonct.js, use
<button type="button" onclick="suppression(this)">x</button>
Instead of
<input type="button" onclick="suppression(this)"; value="x">
4. Check if every needed data exists before executing every other steps to prevent errors
Here's my full working affiche.php file (without variables check) :
<?php
require_once 'connexion.php';
// On vérifie si la variable existe et sinon elle vaut null
$prestation = isset($_POST['prestation']) ? $_POST['prestation'] : null;
$nbjours = isset($_POST['nbjours']) ? $_POST['nbjours'] : null;
$tarifjour = isset($_POST['tarifjour']) ? $_POST['tarifjour'] : null;
//On récupère les différentes valeurs sous forme d'une chaine de caractères séparées par une virgule
$prestation=implode(",", $_POST['prestation']);
$nbjours=implode(",", $_POST['nbjours']);
$tarifjour=implode(",", $_POST['tarifjour']);
// generate request params
$params = [];
$values = '';
$facturation = [];
foreach ($_POST['prestation'] as $key => $prestation) {
$params[':prestation' . $key] = $prestation;
$params[':nbjours' . $key] = $_POST['nbjours'][$key];
$params[':tarifjour' . $key] = $_POST['tarifjour'][$key];
$values .= '(:prestation' . $key . ', :nbjours' . $key . ', :tarifjour' . $key . '),';
// prepare facturation data
$facturation[] = [
'prestation' => $prestation,
'nbjours' => $_POST['nbjours'][$key],
'tarifjour' => $_POST['tarifjour'][$key],
];
}
// remove trailing ","
$values = rtrim($values, ',');
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour) VALUES ' . $values);
$req->execute($params);
echo "les données ont bien étés insérées dans la base de données";
$base = null;
?>
<table>
<thead>
<tr>
<th>Prestation</th>
<th>Nb jours</th>
<th>Tarif /jour</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php foreach ($facturation as $presta) : ?>
<tr>
<td class="desc"><?= $presta['prestation'] ?></td>
<td class="qty"><?= $presta['nbjours'] ?></td>
<td class="unit"><?= $presta['tarifjour'] ?></td>
<td class="total"><?= $presta['tarifjour'] * $presta['nbjours'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I hope it helps !
Related
Currently creating a site for a client during my internship end of study.
I am looking to create a button that will allow to add existing sections of my form.
I try to add it thanks to a function in Javascript however when I click on the button nothing happens, however when I do a console.log ('test') in the console hello
function dog_func ($atts) {
$list=array(
'Affenpinscher' => 'Affenpinscher',
'Airedale Terrier' => 'Airedale Terrier',
'Ariégeois' => 'Ariégeois',
'Barbet' => 'Barbet',
'Barbu Tchèque' => 'Barbu Tchèque' ,
'Berger de Russie' => 'Berger de Russie',
'Berger des Pyrénées' => 'Berger des Pyrénées',
'Berger des Shetland' => 'Berger des Shetland',
'Berger du Caucase' => 'Berger du Caucase',
'Berger du massif du Karst' => 'Berger du massif du Karst',
'Berger finnois de Laponie' => 'Berger finnois de Laponie',
'Berger Hollandais' => 'Berger Hollandais',
'Berger Islandais' => 'Berger Islandais',
'Bouvier de l\'Entlebuch' => 'Bouvier de l\'Entlebuch',
'Bouvier des Ardennes' => 'Bouvier des Ardennes',
'Bouvier des Flandres' => 'Bouvier des Flandres',
'Boxer' => 'Boxer',
'Autre' => 'Autre');
echo '<div id="divFields">';
echo '<label for="chien" class="breed">Race du chien:
</label>';
echo '<input id="chien" type="text" list="chiendata">';
echo '<datalist id="chiendata" name="chiendata" >';
echo '<label for="adresse">ou sélectionner dans la
liste</label>';
echo '<select name="adresse" class="selected" id="adresse"
onChange="AjoutOptionAuSelect(this)" style="width: -webkit-
fill-available;" size="1">';
foreach($list as $p => $row){
echo "<option value='".$p."'>" . $row ."</option>" ;
}
echo '</select>';
echo '</datalist>';
echo '<div>';
echo '<label for="name" class="breed">Si autre préciser :
</label>';
echo '</div>';
echo '<div>';
echo '<input type="text" name="dog">';
echo '</div>';
echo '</div>';
}
add_shortcode ('dog_api', 'dog_func');
function dog_shortcode(){
echo '<input type="button" class="add" value="Ajouter un chien" id="test" onClick="addField();">';
}
add_shortcode( 'dog_breed' , 'dog_shortcode');
function addField() {
var field = "<input type='text' name='' value=''/>";
document.getElementById('divFields').innerHtml += field;
console.log('test');
}
I explain I must create a form to add dogs for races, so I try to add with a button my select as much as needed to add the breed of 2 dogs, 3, 5 any matter,
My select is a shortcode to insert it in Elementor that the client wanted
In order to append html within a div.
function addField() {
var field = "<input type='text' name='' value=''/>";
// WITH JQuery
$("#divFields").append(field);
// WITH JS
document.getElementById('divFields').appendChild(field );
}
Life is a lot easier with jQuery, you may use JQuery
I'm trying to make a regular old registration form for a website; and I'm trying to display the name of the logged-in user(if any) at the top of the page. However, the function that is supposed to update that field doesn't seem o be called at all, and I can't make heads or tails of it, nor of the error messages my console displays:
"Uncaught SyntaxError: Unexpected token < -- pagina_registrazione.php:36"
"Uncaught ReferenceError: update_name is not defined
onload -- pagina_registrazione.php:10"
here is the code:
<?php
require './config_db.php';
?>
<!DOCTYPE HTML>
<html lang = "it" >
<head>
<meta charset="utf-8">
<meta name = "keywords" content = "catcher, profilo, registrazione, utente">
<meta name="author" content="Luca Ballarati">
<link rel="stylesheet" href="./../stile/sottopagine.css" type="text/css" media="screen">
<title>pagina di registrazione</title>
</head>
<body onload=update_name>
<section>
<p id="spia_connessione">NOMEUTENTEQUI</p>
<p>Se hai già un'account <strong>clicca qui</strong> per accedere.</p>
<p>Altrimenti <strong>registrati</strong> compilando i campi qui sotto</p>
</section>
<div id="login_form">
<form name="registra" action="./pagina_registrazione.php" method="post">
<div>
<label><p>Nome Utente</p></label>
<input type="text" placeholder="nome_utente" name="username" required autofocus>
</div>
<div>
<label><p>Password</p></label>
<input type="password" placeholder="password" name="password" required>
</div>
<div>
<label><p>Conferma Password</p></label>
<input type="password" placeholder="conferma_password" name="passwordconfirm" required>
</div>
<input name="pulsante_invio" type="submit" value="Invia">
<?php
if(isset($_POST['pulsante_invio'])) {
$nomeutente = $_POST['username'];
$password = $_POST['password'];
$cpassword = $_POST['passwordconfirm'];
if ($password==$cpassword) {
$query = "SELECT * FROM utenti WHERE NomeUtente='$nomeutente'";
$esegui_query = mysqli_query($con,$query);
if(mysqli_num_rows($esegui_query)>0) {
echo '<script type="text/javascript">
window.alert("Nome Utente già usato: registrarsi con un diverso Nome Utente");
</script>';
}
else {
$query = "INSERT INTO utenti (NomeUtente,Password,Record,Partite)
VALUES('$nomeutente','$password',0,0)";
$esegui_query = mysqli_query($con,$query);
if ($esegui_query) {
$nome = $_SESSION['username'];
//porta l'utente alla pagina di login
echo '<script type="text/javascript">
window.alert("Utente registrato correttamente");
</script>';
//echo '<script type="text/javascript">
//document.getElementById("spia_connessione").innerHTML = "'$nome'";
//</script>';
}
else {
echo '<script type="text/javascript">
window.alert("Errore durante la registrazione");
</script>';
}
}
}
else {
echo '<script type="text/javascript">
window.alert("Password e Password di conferma devono essere uguali");
</script>';
}
}
?>
</form>
</div>
<script type="text/javascript">
function update_name() {
window.alert("nome utente aggiornato");
var nm = <?php echo $_SESSION['username']; ?>;
document.getElementById("spia_connessione").innerHTML = nm;
}
</script>
</body>
Please write this code on the top of your php file.
<?php
ob_start();
session_start();
?>
I am building a database of different devices which is displayed in a page which sells medical devices. When a user adds a quantity of the device to the cart, I want the database to be updated with (stock - quantity in cart) I am trying to do this on PHP but am having no luck. My attempt and code is below.
Here is a snippet of my attempt. I'm not sure where to place this in the code below.
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
if(isset($_POST['incqty'])){
$value += 1;
$query = "UPDATE products SET stock= (stock-$product_qty) WHERE product_name=$product_name";
mysql_select_db('products');
$retval = mysql_query($query,$mysqli);
}
?>
This is code for index.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 align="center">Products </h1>
<!-- View Cart Box Start -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<div class="cart-view-table-front" id="view-cart">';
echo '<h3>Your Shopping Cart</h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="100%" cellpadding="6" cellspacing="0">';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /> Remove</td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>Checkout';
echo '</td>';
echo '</tbody>';
echo '</table>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<!-- View Cart Box End -->
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price, stock FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content"><h3>{$obj->product_name}</h3>
<div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
Price {$currency}{$obj->price}
<fieldset>
<label>
<span>Color</span>
<select name="product_color">
<option value="Black">Black</option>
<option value="Silver">Silver</option>
</select>
</label>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button type="submit" id="updateb" class="add_to_cart">Add</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
<!-- Products List End -->
</body>
</html>
This is code for cart_update.php
<?php
session_start();
include_once("config.php");
//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
foreach($_POST as $key => $value){ //add all post vars to new_product array
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
//remove unecessary vars
unset($new_product['type']);
unset($new_product['return_url']);
//we need to get product name and price from database.
$statement = $mysqli->prepare("SELECT product_name, price, stock FROM products WHERE product_code=? LIMIT 1");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $price, $stock);
while($statement->fetch()){
//fetch product name, price from db and add to new_product array
$new_product["product_name"] = $product_name;
$new_product["product_price"] = $price;
$new_product["product_stock"] = $stock;
if(isset($_SESSION["cart_products"])){ //if session var already exist
if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
}
}
$_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item
}
}
//update or remove items
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
//update item quantity in product session
if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
foreach($_POST["product_qty"] as $key => $value){
if(is_numeric($value)){
$_SESSION["cart_products"][$key]["product_qty"] = $value; //change
}
}
}
//remove an item from product session
if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
foreach($_POST["remove_code"] as $key){
unset($_SESSION["cart_products"][$key]);
}
}
}
//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
header('Location:'.$return_url);
?>
This is code for view_cart.php
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<h1 align="center">View Cart</h1>
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%" cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION["cart_products"])) //check session var
{
$total = 0; //set initial total value
$b = 0; //var for zebra stripe table
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$subtotal = ($product_price * $product_qty); //calculate Price x Qty
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$currency.$product_price.'</td>';
echo '<td>'.$currency.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}
$grand_total = $total + $shipping_cost; //grand total including shipping cost
foreach($taxes as $key => $value){ //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount; //add tax val to grand total
}
$list_tax = '';
foreach($tax_item as $key => $value){ //List all taxes
$list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
}
?>
<tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
<tr><td colspan="5">Add More Items<button type="submit">Update</button></td></tr>
</tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>
</body>
</html>
your variables $product_qty and $product_name are not defined and in the query pass the product name in the quotes as your query is in double quotes so pass name in the single quotes.
Also it will be better if you update using primary id not by name.
I have a html webpage which has a table that gets data from a table in my database. Each row has a button that when clicked gets added into another table on the webpage dynamically using javascript. The dynamic table has a submit button which when clicked, the data in the table should get added into a table in my database. What my problem is that the contents in the table do not get added to the database but each time I press the submit button a new row with a unique id gets added. Also theres a input text box which also gets added correctly to my database. This makes me believe that my database connection is working but for some reason the data in the table does not get added. How can I make the data in the dynamic table get submited into the database? Here is my code. Code has been updated with suggestions.
<?php
$sql = "SELECT *
FROM inventoryCars";
$result = mysqli_query($connection, $sql);
?>
<div class="inventory">
<div class ="cars">
<table>
<?php
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$RegNo = $row["regNo"];
$CarMake = $row["carMake"];
$CarModel = $row["carModel"];
?>
<tr>
<input type="hidden" name="regNo" value="<?php echo $row['regNo'] ?>">
<input type="hidden" name="carMake" value="<?php echo $row['carMake'] ?>">
<input type="hidden" name="carModel" value="<?php echo $row['carModel'] ?>">
<td><?php echo $row["regNo"] ?></td>
<td><?php echo $row["carMake"] ?></td>
<td><?php echo $row["carModel"] ?></td>
<td><button onclick="addRowToTable('<?php echo $RegNo ?>','<?php echo $CarMake ?>','<?php echo $CarModel ?>')">+</button></td>
</tr>
<script type ="text/javascript">
function addRowToTable(regNo, carMake, carModel) {
var table = document.getElementById("newhireTBL");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = regNo;
cell2.innerHTML = carMake;
cell3.innterHTML = carModel;
}
</script>
<?php
}
}
?>
</table>
</div>
</div>
<div class="order">
<div class ="newhire">
<table id="newhireTBL">
</table>
<form action = "addNewHire.php" method = "post">
<input type="hidden" name="regNo" value="<?php echo $row['regNo'] ?>">
<input type="hidden" name="carMake" value="<?php echo $row['carMake'] ?>">
<input type="hidden" name="carModel" value="<?php echo $row['carModel'] ?>">
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</div>
</div>
addNewHire.php
<?php session_start(); ?>
<?php require_once("connectToSQL.php"); ?>
<?php
echo "<pre>";var_dump($_POST);echo "</pre>";die;
if (isset($_POST['submit'])){
$RegNo = $_POST['regNo'];
$CarMake = $_POST['carMake'];
$CarModel = $_POST['carModel'];
$_SESSION["regNo"] = $RegNo;
$_SESSION["carMake"] = $CarMake;
$_SESSION["carModel"] = $CarModel;
$sql = "INSERT INTO newHire(regNo, carMake, carModel)
VALUES('$RegNo', '$CarMake', '$CarModel')";
if (mysqli_query($connection, $sql)) {
header("location:order_success.php");
echo "Order has been made";
} else {
header("location:order_fail");
echo "Order fail";
}
}
?>
}
?>
testing shows this
array(4) {
["regNo"]=>
string(0) ""
["carMake"]=>
string(0) ""
["carModel"]=>
string(0) ""
["submit"]=>
string(6) "Submit"
}
The form and table tag have an invalid nesting, and this may prevent the form data being submitted. Try moving end tag for the "newhireTBL" table immediately below the table's starting tag (outside the form), so the table and form tags don't overlap.
Eg:
<table...>
</table>
<form...>
</form>
EDIT: here's a basic example with some dummy data that may help you solve your problem. Good luck!
<?php
$rows = array(
array(
"regNo" => "abc123",
"carMake" => "toyota",
"carModel" => "camry",
),
array(
"regNo" => "def456",
"carMake" => "ford",
"carModel" => "laser",
),
);
?>
<?php foreach ($rows as $row): ?>
<?php echo $row["regNo"] ?>
<?php echo $row["carMake"] ?>
<?php echo $row["carModel"] ?>
<button onclick="addRow('<?php echo $row["regNo"] ?>','<?php echo $row["carMake"] ?>','<?php echo $row["carModel"] ?>')">+</button>
<br/>
<?php endforeach ?>
<form action = "addNewHire.php" method = "post">
<input id=regNo type="text" name="regNo" value="">
<input id=carMake type="text" name="carMake" value="">
<input id=carModel type="text" name="carModel" value="">
<input id="submit" type="submit" name="submit" value="Submit">
</form>
<script type ="text/javascript">
function addRow(regNo, carMake, carModel) {
document.getElementById('regNo').value = regNo;
document.getElementById('carMake').value = carMake;
document.getElementById('carModel').value = carModel;
}
</script>
I really don't have any idea with this problem. I create new plug-in. Structure is easy:
div FreeQuotation_wrap2 (display the table), div FreeQuotation_wrap3 (insert new data). But after write new data and click submit page is refresh with old data.
When I click refresh I see information that it will resend data to database. It's ok- I prevent it with unique. Now I see new table with new record. How can I make it automatically?
I try 3 methods: onSubmit="" (doesn't work) and javascript (window.location = "...") and trick with session (i get error - headers already sent by...).
<?php
global $FreeQuotation_version;
global $wpdb;
echo $table_name;
global $today_date;
$table_name = $wpdb->prefix . 'free_quotation_kic';
?>
<div class="FreeQuotation_wrap">
<h2><div class="FreeQuotation_header"></div> FreeQuotation <?php echo $FreeQuotation_version; ?></h2><br>
</div>
<div class="FreeQuotation_wrap2">
<table class="widefat">
<?php
$FreeQuotation_table = $wpdb->get_results(
"
SELECT *
FROM $table_name
ORDER BY adding_date DESC
LIMIT 0 , 10
"
);
//nagłówek
echo '<thead><tr><th> ID </th><th> Quotation </th><th> Author </th><th> Display Date </th><th> Delete </th></tr></thead>';
//treść
foreach ( $FreeQuotation_table as $ogresults )
{
echo '<tr><td>';
echo $ogresults->id;
echo '</td><td>';
echo $ogresults->quotation;
echo '</td><td>';
echo $ogresults->author;
echo '</td><td>';
echo $ogresults->display_date;
echo '</td></tr>';
}
echo '<tfoot><tr><th> ID </td><th> Quotation </td><th> Author </td><th> Display Date </th><th> Delete </td></tr></tfoot>';
?>
</table>
</div>
<div class= "FreeQuotation_wrap3">
<form method="post" action="options.php">
<?php settings_fields('FreeQuotation_settings_filed'); ?>
<?php $options = get_option('FreeQuotation_options'); ?>
</form>
<?php
global $current_user;
$ufUserID = $current_user->ID;
$quotation = $_POST["quotation_textarea"];
$author = $_POST["autor_text"];
$display_date = $_POST["display_date"];
$url = $_SERVER['PHP_SELF'];
$adding_date = $today_date;
echo $url;
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'updateFeedback' ) {
$FreeQuotation = $wpdb->insert( 'wp_free_quotation_kic', array( 'quotation' => $quotation, 'author' => $author, 'display_date' => $display_date, 'adding_date' => $adding_date,) );
}?>
TUTAJ
<h3 class="widget-title">Add quotation</h3>
<form id='reloader' method='post' onSubmit="<?php echo $url;?>">
<table class="widefat" >
<thead>
<tr><th>Quotation</th><th>Author</th><th>Display Date</th></tr>
</thead>
<tbody>
<tr><td>
<textarea rows="1" cols="100" name="quotation_textarea" required></textarea>
</td>
<td>
<input type="text" name="autor_text" required></input>
</td>
<td>
<input type="text" name="display_date" required></input>
</td></th>
</tbody>
<tfoot>
<tr><th>
<input class="button button-primary" type="submit" name="submit" value="submit"/>
<?php wp_nonce_field( 'updateFeedback' ); ?>
<input name="action" type="hidden" id="action" value="updateFeedback"/>
</th></td>
</tfoot>
</table>
</form><br>
</div>
<div class="FreeQuotation_wrap4">
<h3>Zmiany:</h3>
</div>
<?php
?>
Can you help me? It's my first question hire (and I believe that the last...). Usually when I try to write a question I find the answer quickly :) Now I spend few hours with this problem and I doesn't see any solution...
I find simple solution - it's very easy and it's work. Maybe it's not professional but I don't have any other idea...
I change the order on the page. First is the form to add new position, the second is now the table with output. It means that I change two order:
<div class= "FreeQuotation_wrap3">
...
</div>
<div class="FreeQuotation_wrap2">
...
</div>
And this is my first answer on stackoverflow.com ;-)