I want to insert all values with just a function and I don't want to rewrite the same code many times but I have the problem that this function just inserts the first values (I checked the input name and it's set correctly).
$name = htmlspecialchars($_POST["name"]);
$prix = htmlspecialchars($_POST["prixing"]);
$prixn = htmlspecialchars($_POST["quantite"]);
$uniteing = $_POST['unite'];
$date = date('Y-m-d');
<?php
$servername = "localhost";
$username = "root";
$password = "test";
$dbname = "test";
// Create connection $conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } //
variable $date = date('Y-m-d');
$name = htmlspecialchars($_POST["name"]);
$name1 = htmlspecialchars($_POST["name1"]);
$prix = htmlspecialchars($_POST["prixing"]);
$prix1 = htmlspecialchars($_POST["prixing1"]);
$prixn = htmlspecialchars($_POST["quantite"]);
$prixn1 = htmlspecialchars($_POST["quantite1"]);
$uniteing = $_POST['unite'];
$uniteing1 = $_POST['unite1'];
$name2 = htmlspecialchars($_POST["name2"]);
$name3 = htmlspecialchars($_POST["name3"]);
$prix2 = htmlspecialchars($_POST["prixing2"]);
$prix3 = htmlspecialchars($_POST["prixing3"]);
$prixn2 = htmlspecialchars($_POST["quantite2"]);
$prixn3 = htmlspecialchars($_POST["quantite3"]);
$uniteing2= $_POST['unite2'];
$uniteing3 = $_POST['unite3'];
$name4 = htmlspecialchars($_POST["name4"]);
$name5 = htmlspecialchars($_POST["name5"]);
$prix4 = htmlspecialchars($_POST["prixing4"]);
$prix5 = htmlspecialchars($_POST["prixing5"]);
$prixn4 = htmlspecialchars($_POST["quantite4"]);
$prixn5 = htmlspecialchars($_POST["quantite5"]);
$uniteing4 = $_POST['unite4'];
$uniteing5 = $_POST['unite5'];
$name6 = htmlspecialchars($_POST["name6"]);
$name7 = htmlspecialchars($_POST["name7"]);
$prix6 = htmlspecialchars($_POST["prixing6"]);
$prix7 = htmlspecialchars($_POST["prixing7"]);
$prixn6 = htmlspecialchars($_POST["quantite6"]);
$prixn7 = htmlspecialchars($_POST["quantite7"]);
$uniteing6 = $_POST['unite6'];
$uniteing7 = $_POST['unite7'];
$name8 = htmlspecialchars($_POST["name8"]);
$name9 = htmlspecialchars($_POST["name9"]);
$prix8 = htmlspecialchars($_POST["prixing8"]);
$prix9 = htmlspecialchars($_POST["prixing9"]);
$prixn8 = htmlspecialchars($_POST["quantite8"]);
$prixn9 = htmlspecialchars($_POST["quantite9"]);
$uniteing8 = $_POST['unite8'];
$uniteing9 = $_POST['unite9'];
$name10 = htmlspecialchars($_POST["name10"]);
$prix10 = htmlspecialchars($_POST["prixing10"]);
$prixn10 = htmlspecialchars($_POST["quantite10"]);
$uniteing10 = $_POST['unite10'];
//end variable 2
function insert($namex, $prixx,$prixnx, $datex, $uniteingx,$conn)
{
$sql = "INSERT INTO ingredient
VALUES ('$namex','$prixx','$prixnx','$datex','$uniteingx')";
$res = mysqli_query($conn, $sql);
if ($res) {
echo "New record created successfully";
mysqli_error($conn);
} else {
echo "_error_: " . $sql . "<br>" . mysqli_error($conn);
}
}
insert($name, $prix,$prixn, $date, $uniteing,$conn);
insert($name1, $prix1,$prixn1, $date1, $uniteing1,$conn);
insert($name2, $prix2,$prixn2, $date2, $uniteing2,$conn);
insert($name3, $prix3,$prixn3, $date3, $uniteing3,$conn);
insert($name4, $prix4,$prixn4, $date4, $uniteing4,$conn);
insert($name5, $prix5,$prixn5, $date5, $uniteing5,$conn);
insert($name6, $prix6,$prixn6, $date6, $uniteing6,$conn);
insert($name7, $prix7,$prixn7, $date7, $uniteing7,$conn);
insert($name8, $prix8,$prixn8, $date8, $uniteing8,$conn);
insert($name9, $prix9,$prixn9, $date9, $uniteing9,$conn);
insert($name10, $prix10,$prixn10, $date10, $uniteing10,$conn);
header('Location: ../index.html'); ?>
Here is my form:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
</head>
<body>
<form action="php/insert-multi-ing.php" method="POST">
<table>
<tr>
<th>Nom Ingrédient</th>
<th>Prix Ingrédient</th>
<th>Quantite Ingrédient</th>
<th>Unite</th>
</tr>
<tr>
<td><input type="text" name="name"></td>
<td><input type="text" name="prixing"></td>
<td><input type="text" name="quantite"></td>
<td>
<select name="unite" id="unites">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name1"></td>
<td><input type="text" name="prixing1"></td>
<td><input type="text" name="quantite1"></td>
<td>
<select name="unite1" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name2"></td>
<td><input type="text" name="prixing2"></td>
<td><input type="text" name="quantite2"></td>
<td>
<select name="unite2" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name3"></td>
<td><input type="text" name="prixing3"></td>
<td><input type="text" name="quantite3"></td>
<td>
<select name="unite3" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name4"></td>
<td><input type="text" name="prixing4"></td>
<td><input type="text" name="quantite4"></td>
<td>
<select name="unite4" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name5"></td>
<td><input type="text" name="prixing5"></td>
<td><input type="text" name="quantite5"></td>
<td>
<select name="unite5" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name6"></td>
<td><input type="text" name="prixing6"></td>
<td><input type="text" name="quantite6"></td>
<td>
<select name="unite6" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name7"></td>
<td><input type="text" name="prixing7"></td>
<td><input type="text" name="quantite7"></td>
<td>
<select name="unite7" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name8"></td>
<td><input type="text" name="prixing8"></td>
<td><input type="text" name="quantite8"></td>
<td>
<select name="unite8" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name9"></td>
<td><input type="text" name="prixing9"></td>
<td><input type="text" name="quantite9"></td>
<td>
<select name="unite9" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name10"></td>
<td><input type="text" name="prixing10"></td>
<td><input type="text" name="quantite10"></td>
<td>
<select name="unite10" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
</table>
<button>Ajouter ingrédient</button>
</form>
</body>
</html>
You shouldn't repeat your form fields as a list name0, name1 .. name99 instead you need to send them as an array like: data[0][name] .. data[99][name]
Also better generate your HTML with PHP for not violating DRY rule, you'll apreciate that when will need to edit the form with reperating fields in the future:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
</head>
<body>
<form action="php/insert-multi-ing.php" method="POST">
<table>
<tr>
<th>Nom Ingrédient</th>
<th>Prix</th>
<th>Prix Ingrédient</th>
<th>Quantite Ingrédient</th>
<th>Unite</th>
</tr>
<?php
for ($i = 0; $i < 10; $i++) {
echo "
<tr>
<td><input type='text' name='data[{$i}][name]'></td>
<td><input type='text' name='data[{$i}][prix]'></td>
<td><input type='text' name='data[{$i}][prixn]'></td>
<td><input type='text' name='data[{$i}][quantite]'></td>
<td>
<select name='data[{$i}][unite]' id='unite_{$i}'>
<option>kg</option>
<option>G</option>
<option>L</option>
<option>Ml</option>
<option>Cl</option>
<option>Piece</option>
</select>
</td>
</tr>
";
}
?>
</table>
<button>Ajouter ingrédient</button>
</form>
</body>
</html>
Here's the sample for accessing it as a multidimensional array in PHP and inserting to DB with prepared statement. Keep in mind that I use PDO instead of mysqli here which I advice you to:
<?php
$data = $_POST['data'] ?? null;
if (!is_null($data)) {
$pdo = new PDO("mysql:host=127.0.0.1;dbname=test;charset=utf8", "yourusername", "yourpassword");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("
INSERT
INTO ingredient (name, prix, prixn, unite, quantite, date)
VALUES (:name, :prix, :prixn, :unite, :quantite, NOW())
");
$stmt->bindParam('name', $name);
$stmt->bindParam('prix', $prix);
$stmt->bindParam('prixn', $prixn);
$stmt->bindParam('quantite', $quantite);
$stmt->bindParam('unite', $unite);
foreach ($data as $item) {
// Adds some data validation to make sure you won't save million empty rows,
// also add custom validation for other fields (if any)
$name = checkValue($item['name']);
$prix = checkValue($item['prix']);
$prixn = checkValue($item['prixn']);
$quantite = floatval($item['quantite']);
$unite = checkValue($item['unite']);
if (!is_null($name) && !is_null($prix) && !is_null($prixn) && $quantite > 0) {
$stmt->execute();
}
}
}
/**
* check if the string value is not null and not empty
*
* #param $value
*
* #return string|null
*/
function checkValue($value)
{
return (is_null($value) || trim($value) == '') ? null : $value;
}
Note your code is messy and it's quite possible that I used wrong column names or field names in form, just fix it. In general that works.
Your code is subject to SQL injection. It's better to use parameterized queries. They take care of quoting, fixing data that might include SQL injection, etc.
They also execute faster when executing the same statement repeatedly.
Note: Code not tested, may require some syntax checking and other corrections
<?php
// Create PDO connection
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Create list of base column names
$colList = array(
'name',
'prix',
'prixn',
'uniteing'
);
// Create array to hold column values from $_POST
$val = Array(null,null,null,null);
// Prepare SQL statement with place holders, be sure to explicitly list the table column names. Substitute the actual column names for those below.
$stmt = $dbh->prepare("INSERT INTO ingredient (`namex`,`prixx`,`prixnx`,`uniteingx`) VALUES (:namex,:prixx,:prixnx,:uniteingx)");
// Bind each array value to a place holder
$stmt->bindParam(':namex',$val[1]);
$stmt->bindParam(':prixx',$val[2]);
$stmt->bindParam(':prinx',$val[3]);
$stmt->bindParam(':uniteingx',$val[4]);
// Step through the column name suffix values from the form
for($i=0;$i<=10;$i++) {
// Special case for the first (0) value (i.e. no suffix)
$suffix = $i > 0 ? $i : '';
// Load the 5 column values from the post variables into the $val array
foreach($colList as $colNum, $colName) {
$val[$colNum] = $_POST[$colName . $suffix];
}
// Execute the SQL statement above with the current values in $val
$stmt->execute();
}
?>
To begin, craft your html form so that it is fit for purpose and doesn't violate html document standards.
You should be generating the rows of input fields inside of a loop.
You should declare the name attributes of each field using array syntax so that row data is submitted in grouped subarrays -- this will make subsequent processes much easier. By simply trailing the field name with [], you can avoid cluttering your file with unnecessary php syntax.
You must not have duplicated id attributes in a single document. You could append a counter to the end of the id strings, but there is a high probability that you don't need the id declarations at all -- I'll omit them.
There is zero benefit in duplicating an <option>'s text as its value value. Simply omit that attribute declaration as well.
Use a whitelist of measurement units so that you don't need to write out each <option> tag over and over. This will improve the maintainability of your script.
For improved UX, use field attributes such as: title, placeholder, pattern, minlength, maxlength, required, etc. as well as potentially type="number" to guide the users about how to form valid entries. These simple touches will not only help to prevent user frustration, they will spare your application from making fruitless trips to the database and/or only storing partial submissions.
<table>
<tr>
<th>Nom Ingrédient</th>
<th>Prix Ingrédient</th>
<th>Quantite Ingrédient</th>
<th>Unite</th>
</tr>
<?php
$numberOfRows = 10;
$units = ['kg', 'G', 'L', 'ml', 'Cl', 'Piece'];
for ($i = 0; $i < $numberOfRows; ++$i) {
?>
<tr>
<td><input type="text" name="name[]"></td>
<td><input type="text" name="price[]"></td>
<td><input type="text" name="quantity[]"></td>
<td>
<select name="unit[]">
<option><?php echo implode('</option><option>', $units); ?></option>
</select>
</td>
</tr>
<?php
}
?>
</table>
As for your database table setup, here are some tips:
Avoid vague column naming like date. Rename the column as insert_date or created_on or something similar so that the value is more informative to future readers of your scripts/project.
Modify the schema of your ingredients table to set the DEFAULT value of insert_date as CURRENT_DATE. In doing so, you will never need to write this column into your INSERT queries -- the database will use the current date automatically when you do not pass a value for that column.
If this table doesn't have an AUTOINCREMENTing id column, you should add one and make it the PRIMARY KEY. This is a very basic technique to improve future interactions with the table and will eliminate possible confusion when you find that someone has submitted a duplicate name into the table.
As for processing your submitted data, there are only a few simple steps to follow:
Iterate the $_POST array and isolate each row of data to be inserted into the database.
Once isolated, you need to validate and optionally sanitize each row BEFORE executing the query so that you never store "bad data" in your table.
You are using mysqli and that is just fine -- you don't need to switch to pdo to write secure/stable code.
4 You will only need to generate a prepared statement once and bind variables to placeholders once. Only the (conditional) execution of the statement needs to be inside the loop. (some other examples: 1, 2, 3)
I will recommend, however, that you switch from mysqli's procedural syntax to its object-oriented syntax. It is more concise and I find it simpler to read.
// create a mysqli connection object e.g. $mysqli = new mysqli(...$credentials);
$sql = "INSERT INTO ingredients (`id`, `name`, `price`, `quantity`, `unit`)
VALUES (NULL, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('sdds', $name, $price, $quantity, $unit); // Assumes price and quantity are float values
$failures = [];
$affectedRows = 0;
$units = ['kg', 'G', 'L', 'ml', 'Cl', 'Piece'];
foreach ($_POST['name'] as $index => $name) {
// adjust the validation/sanitization processes as you wish
$name = trim($name);
$price = trim($_POST['price'][$index]);
$quantity = trim($_POST['quantity'][$index]);
$unit = trim($_POST['unit'][$index]);
$rowNo = $index + 1;
if (!strlen($name) || !strlen($price) || !strlen($quantity) || !in_array($unit, $units)) {
$failures[] = "Missing/Invalid value on row $rowNo";
} elseif (!$stmt->execute());
$failures[] = "A syntax error has occurred"; // check your error logs
} else {
++$affectedRows;
}
}
echo "Affected Rows: $affectedRows";
if ($failures) {
echo "<ul><li>" , implode('</li><li>', $failures) , "</li></ul>";
}
Some overall advice:
avoid mixing your French and your English. If you are going to use French variable names, then use ALL French variables. That said, I have read advice from native English speakers and English-as-a-Second-Language developers who state that you should always use ALL English in your code -- this is a a debate, I will not weigh in on this right now.
When to use htmlspecialchars() function? You will notice that at no point did I call this function in my answer. This is because at no point are we printing any of the user's input to screen. Validate? Yes. Sanitize? Sure. HTML Encode? Nope; not here, not now.
If these rows of ingredients are meant to relate to specific recipe table rows, then you will need to establish a FOREIGN KEY relationship. The recipes table will need an id column and the ingredients table will need a column like recipe_id which stores that respective recipe id. Assuming your html form will already know which recipe is being referred to, you should include a <input type="hidden" name="recipe" value="<?php echo $recipeId; ?>"> field on the line under your <form> tag. Then when saving data, you must save the $_POST['recipe'] value with each ingredients row. Then you are making better use a of "relational database".
How to get the value from a drop-down menu list to insert value in db?
My system has 18 holes, users can update the hole value data according to their needs. So how to detect select which hole and update the data in my db?
This is the code
<?php
$result = '';
$doUpdate = isset($_POST['updateButton_x']);
if ($doUpdate) {
$stmtSetParams = $stmtInParams = array();
$validationOptions = array('options' => array('min_range' => 1, 'max_range' => 5));
//Define statement and parameters (Assuming dB field 'item' is the primary key).
$set = '`Hole1` = CASE `Item` ';
foreach ($_POST['Evaluate'] as $Item => $Hole1) {
//Get input value of each table row
if (filter_var($Hole1, FILTER_VALIDATE_INT, $validationOptions) !== false) {
//Field is not blank
$set .= 'WHEN ? THEN ? ';
$stmtSetParams[] = $stmtInParams[] = $Item;
$stmtSetParams[] = $Hole1;
} else {
//Field is not an integer from 1 to 5
$result .= "Field \'Evaluate\' of item \'$Item\' with a value of \'$Hole1\' is not from 1 to 5 and skipped while saving!\\n";
}
}
$set .= 'END';
//Define query placeholders
$placeHolders = implode(', ', array_fill(0, count($stmtInParams), '?'));
$query = <<<SQL
UPDATE `details` SET $set WHERE `Item` IN ($placeHolders)
SQL;
}
//Query the dB.
try {
$dbh = new PDO('mysql:host=localhost;dbname=gcmes', 'root');
if ($doUpdate) {
//Update requested. Prepare and execute update query
$stmt = $dbh->prepare($query);
$stmt->execute(array_merge($stmtSetParams, $stmtInParams));
$result .= 'Update Completed!';
}
//Query for en fetch (updated) table data
$stmt = $dbh->query("SELECT * FROM `details`");
$tableData = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
//A PDO exception is raised
$result = 'Error: ' . addslashes($e->getMessage());
}
//Alert results of database operations
if ($result != '') {
echo "<script>alert('$result')</script>";
}
?>
<form id="form1" name="chooseFormNameIfNeeded" method="post" action="Job.php">
<!-- attribute align is deprecated, define and use a class instead -->
<table class="info" align="center">
<tr>
<!-- use th instead of td for table header -->
<!-- using <b> tag is discouraged -->
<th width="10"><b>Item</b></th>
<th width="100"><b>Category</b></th>
<th width="100"><b>Job</b></th>
<th width="30"><b>Frequency</b></th>
<th width="10"><b>Hole</b></th>
<th width="30"><b>Evaluate</b></th>
</tr>
<?php
foreach ($tableData as $rowData) {
//Print a table row for each of the fetched records
echo <<<HTML
echo <<<HTML
<tr>
<td>{$rowData['Item']}</td>
<td>{$rowData['Category']}</td>
<td>{$rowData['Job']}</td>
<td>{$rowData['Frequency']}</td>
<td><select name="hole">
<option value="Hole1">1</option>
<option value="Hole2">2</option>
<option value="Hole3">3</option>
<option value="Hole4">4</option>
<option value="Hole5">5</option>
<option value="Hole6">6</option>
<option value="Hole7">7</option>
<option value="Hole8">8</option>
<option value="Hole9">9</option>
<option value="Hole10">10</option>
<option value="Hole11">11</option>
<option value="Hole12">12</option>
<option value="Hole13">13</option>
<option value="Hole14">14</option>
<option value="Hole15">15</option>
<option value="Hole16">16</option>
<option value="Hole17">17</option>
<option value="Hole18">18</option>
</select>
<td>
<!-- Assuming dB field 'item' is the primary key. -->
<input type="number" name="Evaluate[{$rowData['Item']}]" id="Evaluate" value="{$rowData['Hole1']}"
min=1 max=5>
</td>
</tr>
HTML;
}
?>
</table>
User can choose any hole to insert the marks
Hole is one of the column in my db
Anyone please help, thank you!
I have listed all the data(Item, Category, Job, Hole(Hole is evaluating marks)) and I display the Hole(mark) in textbox filed.
I want to update the Hole(marks) after user change.
I list all the data using php
<?php
try{
$con = new PDO("mysql:host=localhost;dbname=gcmes", "root", "");
$sql = $con->query("SELECT * FROM details");
echo"<table class='info' align='center'>";
echo"<tr><td width='10'><b>No</b></td>
<td width='30'><b>Category</b></td>
<td width='50'><b>Job</b></td>
<td width='40'><b>Evaluate</b></td><tr>";
foreach($sql as $row) {
$Item = $row["Item"];
$Category = $row["Category"];
$Job = $row["Job"];
$Evaluate = $row["Hole 1"];
echo'
<tr>
<td>' . $Item . '</td>
<td>' . $Category . '</td>
<td>' . $Job . '</td>
<td><input type="input" name="Evaluate" id="Evaluate" value="' . $Evaluate . '">
</td>
</tr>
';
}
echo"</table></form>";
if(isset($_POST['Update_btn'])){
$Evaluate = $_POST["Hole 1"];
if(empty(Evaluate)){
echo "<script type='text/javascript'>alert('Please fill in the required fields to update!')</script>";
}
else{
$insert=$con->prepare("UPDATE details SET Evaluate=:Hole 1 WHERE Item=:Item");
$insert->bindParam(':Hole1',$Evaluate);
$insert->bindParam(":Item",$Item);
$insert->execute();
echo "<script type='text/javascript'>alert('Successful Updated ! ');
window.location.href = 'Hole 1.php';
</script>";
}//else
}//if add button
}//try
catch(PDOException $e)
{
echo "error".$e->getMessage();
}
?>
The html code i just use to display button
<form id="form1" name="Hole 1" method="post" action="Hole 1.php">
<input name="Update_btn" type="image" id="Update_btn" onmouseover="this.src='UpdateO.png'" onmouseout="this.src='UpdateD.png'" value="submit" src="UpdateD.png" alt="submit Button" align="right">
</form>
The problem is will alert message successful updated BUT the value not update in my db. Why? what is the problem?
this is my interface
i want update the marks in textbox filed
I need to change the hole as a selection give the user choose which hole that need to update only, i set the hole have a drop-down menu list. How to dectect which hole?
i just add the code after <td>{$rowData['Frequency']}</td> (dn Fer answer)
<td><select name="hole">
<option value="Hole1">1</option>
<option value="Hole2">2</option>
<option value="Hole3">3</option>
<option value="Hole4">4</option>
<option value="Hole5">5</option>
<option value="Hole6">6</option>
<option value="Hole7">7</option>
<option value="Hole8">8</option>
<option value="Hole9">9</option>
<option value="Hole10">10</option>
<option value="Hole11">11</option>
<option value="Hole12">12</option>
<option value="Hole13">13</option>
<option value="Hole14">14</option>
<option value="Hole15">15</option>
<option value="Hole16">16</option>
<option value="Hole17">17</option>
<option value="Hole18">18</option>
</select>
Keep the following in mind:
I don't have the same environment as yours, so it might not work one
on one.
Spaces in database fieldNames and arrayKeys, etc. are discouraged. I
prefer to use lowerCamelCase, check if dB fieldNames match the code
below!
Read the comments I've placed in the code.
I didn't take psr coding, value validation or safety (sql injection), etc. in consideration. The code is to guide you, you should take these things in consideration yourself.
Hopefully getting you closer to your goals...
Update: The values of the Evaluate field of each row is now validated to be an integer in the range from 1 to 5.
<?php
//Initialize variables
$result = '';
$doUpdate = isset($_POST['updateButton_x']);
//Because button type is 'image', we get parameters buttonName_x and buttonName_y
//from the browsers POST request when the form is sent.
if ($doUpdate) {
//Update button pressed.
//Initialize variables
$stmtSetParams = $stmtInParams = array();
$validationOptions = array('options' => array('min_range' => 1, 'max_range' => 5));
//Define statement and parameters (Assuming dB field 'item' is the primary key).
$set = '`hole1` = CASE `item` ';
foreach ($_POST['evaluate'] as $item => $hole1) {
//Get input value of each table row
if (filter_var($hole1, FILTER_VALIDATE_INT, $validationOptions) !== false) {
//Field is not blank
$set .= 'WHEN ? THEN ? ';
$stmtSetParams[] = $stmtInParams[] = $item;
$stmtSetParams[] = $hole1;
} else {
//Field is not an integer from 1 to 5
$result .= "Field \'Evaluate\' of item \'$item\' with a value of \'$hole1\' is not from 1 to 5 and skipped while saving!\\n";
}
}
$set .= 'END';
//Define query placeholders
$placeHolders = implode(', ', array_fill(0, count($stmtInParams), '?'));
$query = <<<SQL
UPDATE `details` SET $set WHERE `item` IN ($placeHolders)
SQL;
}
//Query the dB.
try {
$dbh = new PDO('mysql:host=localhost;dbname=gcmes', 'root');
if ($doUpdate) {
//Update requested. Prepare and execute update query
$stmt = $dbh->prepare($query);
$stmt->execute(array_merge($stmtSetParams, $stmtInParams));
$result .= 'Update Completed!';
}
//Query for en fetch (updated) table data
$stmt = $dbh->query("SELECT * FROM `details`");
$tableData = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
//A PDO exception is raised
$result = 'Error: ' . addslashes($e->getMessage());
}
//Alert results of database operations
if ($result != '') {
echo "<script>alert('$result')</script>";
}
?>
<form id="form1" name="chooseFormNameIfNeeded" method="post" action="test.php">
<!-- attribute align is deprecated, define and use a class instead -->
<table class="info align-center">
<tr>
<!-- use th instead of td for table header -->
<!-- using <b> tag is discouraged -->
<th width="10"><b>No</b></th>
<th width="30"><b>Category</b></th>
<th width="50"><b>Job</b></th>
<th width="40"><b>Evaluate</b></th>
</tr>
<?php
foreach ($tableData as $rowData) {
//Print a table row for each of the fetched records
echo <<<HTML
<tr>
<td>{$rowData['item']}</td>
<td>{$rowData['category']}</td>
<td>{$rowData['job']}</td>
<td>
<!-- Assuming dB field 'item' is the primary key. -->
<input type="number" name="evaluate[{$rowData['item']}]" id="Evaluate" value="{$rowData['hole1']}"
min=1 max=5
>
</td>
</tr>
HTML;
}
?>
</table>
<!-- Attribute align is deprecated, define and use a class instead -->
<!-- Value attribute should not be specified -->
<input name="updateButton" type="image" id="Update_btn" src="http://via.placeholder.com/100x50/0000FF?text=Update"
alt="submit Button" class="align-right"
onmouseover="this.src='http://via.placeholder.com/100x50/00FF00?text=Update'"
onmouseout="this.src='http://via.placeholder.com/100x50/0000FF?text=Update'"
>
</form>
I have a problem with php script.
I have an array, which is generated from form, where $_POST['store'] is an array from jQuery form with functionality to add multiple rows:
Array
(
[client] =>
[darvad] =>
[owca] =>
[ldrive] =>
[store] => Array
(
[product] => Array
(
[0] => 430
[1] => 440
[2] => 430
)
[quantity] => Array
(
[0] => 123
[1] => 1223
[2] => 232
)
[segums] => Array
(
[0] => Mixed park
[1] => Light vehicle
[2] => Trucks
)
[deadline] => Array
(
[0] => 2015-08-04
[1] =>
[2] =>
)
[renewal] => Array
(
[0] => 1
)
)
)
And i need to get values from this array into sql insert statment and loop it.
$sql_rec = "INSERT INTO tsales_funnel_mrecord (product, quantity, segums, deadline)
VALUES (...),(...),(...)....
";
HTML CODE:
<div id="container">
<div id="content" role="main">
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
<form action="<?= $_SERVER['REQUEST_URI'] ?>" method="post" id=multiForm>
<label for="client">Klients: *</label><input id="client" type="text" name="client" placeholder="Reg.nr | Pk.kods" value="" /></br>
<label for="selector1">Darījuma vadītājs: *</label>
<select id="selector1" name="darvad" >
<option value="">-Dar. vadītājs-</option>
<?php
$sql = "SELECT Vards_Uzvards, Tables_ID FROM users";
$results = $wpdb->get_results($sql); // return an object, not ARRAY_N
if ($results) {
foreach ($results as $row) {
echo "<option value = '".$row->Tables_ID."'>".$row->Vards_Uzvards."</option>";
}}
echo "</select></br>";
?>
<label for="owcafind">Meklēt OWCA kodu: *</label><input id="owcafind" type="text" name="owca" placeholder="OWCA Kods (8)" value="" /></br>
<label for="ldrive">Mape L diskā:</label><input id="ldrive" type="text" name="ldrive" placeholder="Mape L diskā" value="" /></br>
Produkti: <img src="<?php echo site_url('/img/plus-icon.png'); ?>" width="15px"><br/>
<table class="multi">
<!-- table title -->
<tr><th>Produkts</th><th>Vienību skaits</th><th>Riska segums:</th><th>Deadline:</th><th>Atjaunojums</th><th>[Option]</th></tr>
<!-- row template, when added new row -->
<tr style="display:none;" class="templateRow">
<td><select name="store[product][]">
<option value="" selected="selected">-Produkts-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
</select></td>
<td><input type="text" name="store[quantity][]" /></td>
<td><select name="store[segums][]">
<option value="" selected="selected">-Riska segums-</option>
<option value="Mixed park">Mixed park</option>
<option value="Light vehicle">Light vehicle</option>
<option value="Trucks">Trucks</option>
<option value="Buss">Buss</option>
</select></td>
<td><input type="date" name="store[deadline][]" class="datepicker" /></td>
<td><input type="checkbox" name="store[renewal][]" value="1" /></td>
<td><a class="del" href="#"><img src="<?php echo site_url('img/minus-icon.jpg'); ?>" width="15px"></a></td>
</tr>
<!-- default values -->
<tr>
<td><select name="store[product][]" >
<option value="" selected="selected">-Produkts-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
</select></td>
<td><input type="text" name="store[quantity][]" /></td>
<td><select name="store[segums][]">
<option value="" selected="selected">-Riska segums-</option>
<option value="Mixed park">Mixed park</option>
<option value="Light vehicle">Light vehicle</option>
<option value="Trucks">Trucks</option>
<option value="Buss">Buss</option>
</select></td>
<td><input type="date" name="store[deadline][]" class="datepicker" /></td>
<td><input type="checkbox" name="store[renewal][]" value="1" /></td>
<td></td>
</tr>
<!-- /default values -->
</table>
From your question, it looks like this is what you're after
$itemCount = sizeof($array['store']['product']);
for ($i = 0; $i < $itemCount; $i++) {
$sql_rec = "INSERT INTO tsales_funnel_mrecord (product, quantity, segums, deadline) VALUES ("' . $array['store']['product'][$i] . '", "' . $array['store']['quantity'][$i] . '", "' . $array['store']['segums'][$i] . '", "' . $array['store']['deadline'][$i] . '");";
// Run the sql statement on the database here
}
You'll need to ensure that all user-supplied values are properly escaped before storing in the database.
If Array is called $array, then you can access the arrays values like so;
// product;
$array['store']['product'];
// quantity;
$array['store']['quantity'];
// etc.
Then, if they are to go into a single column (which is bad form and I don't recommend, then you can do something like this;
// product;
$prod_string = '';
foreach ($array['store']['product'] as $key => $prod) {
$prod_string .= $prod;
}
Then you can use $prod_string in your query.
OR, if you need to insert a row for EACH of the keys;
// We use the key from the product loop to get the others;
foreach ($array['store']['product'] as $key => $prod) {
$prod_val = $prod;
$qty_val = !empty($array['store']['quantity'][$key]) ? $array['store']['quantity'][$key] : '';
$seg_val = !empty($array['store']['segums'][$key]) ? $array['store']['segums'][$key] : '';
$dl_val = !empty($array['store']['deadline'][$key]) ? $array['store']['deadline'][$key] : '';
// Right here create your query and insert.
$sql_rec = "INSERT INTO tsales_funnel_mrecord (product, quantity, segums, deadline) VALUES ($prod_val, $qty_val, $seg_val, $dl_val);"
// I'm not sure what library you're using for your db management, so will leave that out.
}
Then you'll have the value of each.
NOTE - I have not checked for clean post values. Ie, sanitized input. Thats outside the scope of this question.
Have done it:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// We use the key from the product loop to get the others;
$array = $_POST;
$itemCount = sizeof($array['store']['product']);
// Loop through all $itemCount
$values_string = '';
for ($i = 0; $i < $itemCount; $i++) {
$prod = esc_sql($array['store']['product'][$i]);
$quant = esc_sql($array['store']['quantity'][$i]);
$seg = esc_sql($array['store']['segums'][$i]);
$deadline = esc_sql($array['store']['deadline'][$i]);
$renewal = esc_sql($array['store']['renewal'][$i]);
if ($i < $itemCount - 1) {
$new_str = "('".$prod."','".$quant."','".$seg."','".$deadline."','".$renewal."'),";
} else{
$new_str = "('".$prod."','".$quant."','".$seg."','".$deadline."','".$renewal."');";
}
$values_string .= $new_str;
}
// Run the sql statement on the database here
$sql_rec = "INSERT INTO tsales_funnel_mrecord (Product_type, Vien_skaits, Riska_segums, Deadline, Atjaunojums) VALUES $values_string";
$wpdb->query($sql_rec);
}
This question already has answers here:
Get all mysql selected rows into an array
(6 answers)
Closed 9 years ago.
I have the following code in my page
<?php
$dbc = mysql_connect();
$db = mysql_select_db();
$results= mysql_query("SELECT * FROM tbl_teams");
?>
<div class="datagrid"><table>
<thead><tr><th>header</th><th>header</th><th>header</th></tr></thead>
<tbody>
<tr>
<td>
<select name="game1_team1"><option value="0">Choose Team 1</OPTION><?php while($row = mysql_fetch_array($results)) {echo '<option value="'.$row['team_ID'].'">'. $row['team_name'].'</option>';}?></select>
</td>
<td>Vs.</td>
<td>
<select name="game1_team2"><option value="0">Choose Team 2</OPTION><?php while($row = mysql_fetch_array($results)) {echo '<option value="'.$row['team_ID'].'">'. $row['team_name'].'</option>';}?></select>
</td>
</tr>
The code shows the names of football teams from the MySQL table in dropdown game1_team1 but not in game1_team2; it's as though I can't use the same query twice. How do I remedy this? I'd like to use the same values for 60 identical drop downs on the page.
Can I store the values into an array and resuse them in each dropdown?
NOTE: The mysql_* function family is deprecated!
What does that mean? It means you should stop using it today. Old code should be updated as time and budget allow, but you should never, EVER write a new line of code that involves these functions
Another note: it is bad practice to use SELECT *... -- explicitly name the columns you are going to use in your query. That way, if the table structure changes, you can detect that because your query will fail, and react accordingly (in code). This is part of a broader concept known as defensive coding.
On to the problem at hand!
You can use PDO to fetch an array of results out of the database. You can then use that array as many times as you'd like!
// simple sample for connecting with PDO
$host="my.host.name"; // Host name
$username="my_user_name"; // username
$password="my password"; // password
$db_name="my_database_name"; // Database name
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name, $username, $password);
// actually do the query
$statement= $pdo->prepare('
SELECT
time_ID,
team_name
FROM
`tbl_teams`
');
$statement->execute();
// get an array with all the results
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
After that, you can loop the array to make a set of options, or do anything else with the data. For example:
$options = array();
foreach ($results as $one_result){
$options[] = '<option value="'.$one_result['team_ID'].'">'.$one_result['team_name'].'</option>';
}
print '<select name="someSelectElement">'.implode('', $options).'</select>';
Documentation
Deprecation notice for mysql_* functions - http://www.php.net/manual/en/function.mysql-query.php
PHP PDO - http://php.net/manual/en/book.pdo.php
PHP mysqli - http://php.net/manual/en/book.mysqli.php
Using PDO you can easily fetch your results into an array, besides, the mysql_* functions are deprecated.
<?php
$db = new PDO( ... );
$stmt = $db->prepare("SELECT * FROM tbl_teams");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="datagrid">
<table>
<thead><tr><th>header</th><th>header</th><th>header</th></tr></thead>
<tbody>
<tr>
<td>
<select name="game1_team1">
<option value="0">Choose Team 1</OPTION>
<?php
foreach($results as $team) {
echo "<option value='{$team['team_ID']}'>{$team['team_name']}</option>";
}
?>
</select>
</td>
<td>Vs.</td>
<td>
<select name="game1_team2">
<option value="0">Choose Team 2</OPTION>
<?php
foreach($results as $team) {
echo "<option value='{$team['team_ID']}'>{$team['team_name']}</option>";
}
?>
</select>
</td>
</tr>
</tbody>
</table>
However, for efficiency I'd do this:
<?php
$db = new PDO( ... );
$stmt = $db->prepare("SELECT * FROM tbl_teams");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$teamList = '';
foreach($results as $team) {
$teamList .= "<option value='{$team['team_ID']}'>{$team['team_name']}</option>";
}
?>
...
<select name="game1_team1">
<option value="0">Choose Team 1</OPTION>
<?php echo $teamList; ?>
</select>
...
<select name="game1_team2">
<option value="0">Choose Team 2</OPTION>
<?php echo $teamList; ?>
</select>
you can also use MYSQLI_*
<?php
$dbc = mysqli_connect('host','user','password','db_name');
$results= mysqli_query("SELECT `team_ID`,`team_name` FROM tbl_teams");
?>
<div class="datagrid">
<table>
<thead><tr><th>header</th><th>header</th><th>header</th></tr></thead>
<tbody>
<tr>
<td>
<select name="game1_team1">
<option value="">Choose Team 1</OPTION>
<?php while($row1 = mysqli_fetch_array($dbc ,$results)) { echo '<option value="'.$row1['team_ID'].'">'. $row1['team_name'].'</option>';} ?>
</select>
</td>
<td>Vs.</td>
<td>
<select name="game1_team2">
<option value="">Choose Team 2</OPTION>
<?php while($row2 = mysqli_fetch_array($dbc ,$results)) {echo '<option value="'.$row2['team_ID'].'">'. $row2['team_name'].'</option>';}?>
</select>
</td>
</tr>
</tbody>
</table>
it will work now.. :)