Inserting an array into a relational table - php

I have 3 tables:
user_login
doc_list
user_cat_link_table
So I am creating a new user and apart of the form shows an array of the available categories which are pulled from the cat_list table.
I am struggling to along with the other form data update the user_cat_link_table.
The script to take the ID of the new user and take the ID of the category selected from the checkboxes array:
Here is my input form:
<form action="actions/add_emp.php" method="post">
<input type="text" name="user" placeholder="Username" required="required" /><br/>
<input type="text" name="pass" type="password" placeholder="Password"/></label><br/>
<input type="text" name="firstname" id="name" required="required"
placeholder="Firstname"/><br />
<input type="text" name="lastname" id="email" required="required"
placeholder="Lastname"/><br/>
<input type="email" name="email" id="city" required="required"
placeholder="Email Address"/><br/>
<input type="text" name="extension" id="extension" required="required"
placeholder="Extension Number"/><br/>
<select name="title">
<option selected disabled>Please Select a Job Title...</option>
<option disabled></option>
<option disabled>Helpesk:</option>
<option value="Technical Support Advisor">Technical Support Advisor</option>
<option value="Deputy Team Leade">Deputy Team Leader</option>
<option value="Team Leader">Team Leader</option>
<option value="Incident Resolution Advisor">Incident Resolution Advisor
</option>
<option disabled></option>
<option disabled>Call Centre:</option>
<option value="Technical Support Advisor">Technical Support Advisor</option>
<option value="">Deputy Team Leader</option>
<option value="">Team Leader</option>
<option disabled></option>
</select>
<div id="checkboxlist" >
<?php
foreach($category as $cat){
?>
<input type="checkbox" value="<?php echo $cat["cat_id"]; ?>"
name="cat_no[]" id="box1"> <?php echo $cat["cat_title"]; ?></a><br>
<?php
}
?>
</div>
<input type="submit" value="Add User" name="submit"/><br />
</form>
I can see if I do a print_r() or var_dump() I am getting the results I expect:
Array ( [action] => id
[user] => test23wer3e4weret4essd
[pass] => test [firstname] => test
[lastname] => test
[email] => tes#test.com
[extension] => 1234
[cat_no] => Array ( [0] => 69
[1] => 70
[2] => 71 )
[submit] => Add User )
Here is the form which acts as the script to insert the data into both the user_login table (which works) but its the part at the bottom trying to insert into the join table I am having trouble with:
<?
session_start();
session_regenerate_id();
if(!ini_get('date.timezone'))
{
date_default_timezone_set('GMT');
}
if(isset($_POST["action"])){
if(isset($_POST['submit'])){
include_once'../../config.php';
$dbh = new PDO("mysql:host=$hostname;dbname=dashboardr",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['user']) && isset($_POST['pass'])){
$password=$_POST['pass'];
$sql=$dbh->prepare("SELECT COUNT(*) FROM `user_login` WHERE `username`=?");
$sql->execute(array($_POST['user']));
if($sql->fetchColumn()!=0){
die("User Exists");
}else{
function rand_string($length) {
$str="";
$chars = "subinsblogabcdefghijklmanopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
$p_salt = rand_string(20);
$site_salt="subinsblogsalt";
$salted_hash = hash('sha256', $password.$site_salt.$p_salt);
$sql=$dbh->prepare("INSERT INTO `user_login`
(`id`, `username`, `password`, `psalt`,
`firstname`, `lastname`, `email`, `extension`)
VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)");
$sql->execute(
array($_POST['user'], $salted_hash, $p_salt, $_POST["firstname"],
$_POST["lastname"], $_POST["email"], $_POST["extension"]));
print_r($_POST);
die();
$docId = $dbh->lastInsertId();
$sql = "INSERT INTO `user_cat_link_table`(`UserID`, `Cat_ID`) VALUES";
$values = "";
$params = [];
foreach($_POST["cat_no"] as $cat)
{
$values.= "(?, ?), ";
$params[] = $cat; // correct here
$params[] = $docId;
}
$values = substr($values, 0, -2);
$sql.= $values;
$query = $dbh->prepare($sql);
$query->execute($params);
if ($dbh->query($sql)) {
}else{}
$dbh = null;
} //catch(PDOException $e)
header ('Location: ../list_doc.php?success=1');
}
}
}
?>

Related

Inserting Data into MySQL table using HTML form

I am currently trying to insert rows into a MySQL database, and most of the code is there but I'm having a few issues I can't diagnose. I know the database connection is good, and every time the submit button is pressed it runs the correct php script. The issue I'm having is that it always adds 2 records to the database table and fails to carry though any of the form data (it inserts two completely blank rows.)
Here's the code for the form (with a little extra code for the wordpress page)
<div class="main-container">
<div class="content-area">
<div class="middle-align">
<div class="site-main" id="sitefull">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<div>
<form method="POST" name="cutting tool" action="add-tool-script.php">
<table style="width:auto;">
<tr>
<th width="50%"><h2><ul>Tool Information</ul></h2><br></th>
<th width="50%"><ul><h2>Storage Information</h2></ul><br></th>
</tr>
<tr>
<td width="50%">
<h3>Tooling Name</h3><br>
<input type="text" name="name" placeholder="e.g. ShearHog"><br><br>
<h3>Tooling Type</h3><br>
<select name="type">
<option selected disabled hidden style='display: none' value=''></option>
<option value="Ballnose Endmill">Ballnose Endmill</option>
<option value="Bullnose Endmill">Bullnose Endmill</option>
<option value="Boring Bar">Boring Bar</option>
<option value="Brush">Brush</option>
<option value="Burnishing">Burnishing</option>
<option value="Chamfer Mill">Chamfer Mill</option>
<option value="Countersink">Countersink</option>
<option value="Drill">Drill</option>
<option value="Drill/Mill">Drill/Mill</option>
<option value="Engraver">Engraver</option>
<option value="Face Mill">Face Mill</option>
<option value="Flat Endmill">Flat Endmill</option>
<option value="High Feed Mill">High Feed Mill</option>
<option value="Reamer">Reamer</option>
<option value="Slitting Saw">Slitting Saw</option>
<option value="Spot Drill">Spot Drill</option>
<option value="Tap">Tap</option>
<option value="Threadmill">Threadmill</option>
<option value="Woodruff">Woodruff</option>
<option value="Other">Other</option>
</select><br><br>
<h3>Tooling Brand</h3><br>
<input type="text" name="brand" placeholder="e.g. Lakeshore Carbide"><br><br>
<h3>Part Number</h3><br>
<input type="text" name="part_number" placeholder="e.g. 360014X"><br><br>
<h3>Price</h3><br>
<input type="text" name="price" placeholder="e.g. 24.95"><br><br>
<h3>Overall Length</h3><br>
<input type="text" name="oal" placeholder="e.g. 2.5"><br><br>
<h3>Tooling Material</h3><br>
<select name="material">
<option selected disabled hidden style='display: none' value=''></option>
<option value="Carbide">Carbide</option>
<option value="Ceramic">Ceramic</option>
<option value="Diamond">Diamond</option>
<option value="HSS">HSS</option>
<option value="Powdered Metal">Powdered Metal</option>
</select><br><br>
<h3>Cutting Diameter</h3><br>
<input type="text" name="cutting_diam" placeholder="e.g. 0.250"><br><br>
<h3>Shank Diameter</h3><br>
<input type="text" name="shank_diam" placeholder="e.g. .250"><br><br>
<h3>Number of Flutes</h3><br>
<input type="text" name="flutes" placeholder="e.g. 3"><br><br>
<h3>Length of Cut (Flute Length)</h3><br>
<input type="text" name="loc" placeholder="e.g. .750"><br><br>
<h3>Corner Radius</h3><br>
<input type="text" name="corner_rad" placeholder="e.g. .004"><br><br>
</td>
<td width="50%">
<h3>Quantity in Stock</h3><br>
<input type="text" name="qty" placeholder="e.g. 37"><br><br>
<h3>Minimum Trigger Quantity</h3><br>
<input type="text" name="trigger_qty" placeholder="e.g. 4"><br><br>
<h3>Reorder Link</h3><br>
<input type="text" name="reorder_link" placeholder="e.g. example.com"><br><br>
<h3>Toolbox Number</h3><br>
<input type="text" name="toolbox_no" placeholder="e.g. 1"><br><br>
<h3>Drawer Number</h3><br>
<input type="text" name="drawer_no" placeholder="e.g. 1"><br><br>
<h3>Bin Number</h3><br>
<input type="text" name="bin_no" placeholder="e.g. 1"><br><br>
<h3>Product</h3><br>
<input type="text" name="product" placeholder="e.g. Widget #2"><br><br>
<input type="submit" value="Add to Tool Crib" name="submitbutton" action="submit"/>
</td>
</tr>
</table>
</form>
</div>
<?php
//If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() )
comments_template();
?>
<?php endwhile; // end of the loop. ?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<?php get_footer(); ?>
And here's the code for the php script to add form data to the database:
//MySQL Database
$servername = "url.com";
$username = "user_login";
$password = "user_password";
$datab = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $datab);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_REQUEST['name'];
$type = $_REQUEST['type'];
$brand = $_REQUEST['brand'];
$part_number = $_REQUEST['part_number'];
$price = $_REQUEST['price'];
$oal = $_REQUEST['oal'];
$material = $_REQUEST['material'];
$cutting_diam = $_REQUEST['cutting_diam'];
$shank_diam = $_REQUEST['shank_diam'];
$flutes = $_REQUEST['flutes'];
$loc = $_REQUEST['loc'];
$corner_rad = $_REQUEST['corner_rad'];
$qty = $_REQUEST['qty'];
$trigger_qty = $_REQUEST['trigger_qty'];
$reorder_link = $_REQUEST['reorder_link'];
$toolbox_no = $_REQUEST['toolbox_no'];
$drawer_no = $_REQUEST['drawer_no'];
$bin_no = $_REQUEST['bin_no'];
$product = $_REQUEST['product'];
$username = $user_login;
$sql = "INSERT INTO `cutting tools` (`name`, `type`, `brand`, `part_number`, `reorder_link`, `oal`, `price`, `material`, `cutting_diam`, `shank_diam`, `flutes`, `loc`, `corner_rad`, `qty`, `trigger_qty`, `user`, `drawer_no`, `bin_no`, `toolbox_no`)
VALUES ('$name', '$type', '$brand', '$part_number', '$reorder_link', '$oal', '$price', '$material', '$cutting_diam', '$shank_diam', '$flutes', '$loc', '$corner_rad', '$qty', '$trigger_qty', '$username', '$drawer_no', '$bin_no', '$toolbox_no')";
if(mysqli_query($conn, $sql)){
echo "Record added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
Also I know my database is vulnerable to injection, that was a change I planned on making once the form was up and running.
Use WordPress to your advantage. Instead of defining your own connection, use global $wpdb, and then use the insert command.
global $wpdb;
$success = $wpdb->insert('tbl_name', array(<br>
'field1_name' => $_REQUEST['field1'],<br>
'field2_name' => $_REQUEST['field2'],<br>
));<br>
if($success){<br>
echo "Inserted correctly";<br>
} else {<br>
echo "Something went awry!";<br>
}
Here's a prepared statement, a more secure way of creating a MYSQL record in your table.
<?php
//MySQL Database
$servername = "url.com";
$username = "user_login";
$password = "user_password";
$datab = "database_name";
// Create connection
$con = new mysqli($servername, $username, $password, $datab);
global $con;
// Post form data
$name = $_POST['name'];
$type = $_POST['type'];
$brand = $_POST['brand'];
$part_number = $_POST['part_number'];
$price = $_POST['price'];
$oal = $_POST['oal'];
$material = $_POST['material'];
$cutting_diam = $_POST['cutting_diam'];
$shank_diam = $_POST['shank_diam'];
$flutes = $_POST['flutes'];
$loc = $_POST['loc'];
$corner_rad = $_POST['corner_rad'];
$qty = $_POST['qty'];
$trigger_qty = $_POST['trigger_qty'];
$reorder_link = $_POST['reorder_link'];
$toolbox_no = $_POST['toolbox_no'];
$drawer_no = $_POST['drawer_no'];
$bin_no = $_POST['bin_no'];
$product = $_POST['product'];
// Prepared statement
$insert = mysqli_prepare($con, "insert into cutting tools (name,type,brand,part_number,reorder_link,oal,price,material,cutting_diam,shank_diam,flutes,loc,corner_rad,qty,trigger_qty,user,drawer_no,bin_no,toolbox_no) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
mysqli_stmt_bind_param($insert, "sssssssssssssssssss", $name,$type,$brand,$part_number,$reorder_link,$oal,$price,$material,$cutting_diam,$shank_diam,$flutes,$loc,$corner_rad,$qty,$trigger_qty,$product,$drawer_no,$bin_no,$toolbox_no);
mysqli_stmt_execute($insert);
if ($insert) { echo "success"; mysqli_close($con); } else { echo "error"; mysqli_close($con); }
?>
Pay close attention to the order of your columns and the data you are submitting to those columns. I have edited this post because your order was incorrect in several places.
The column names and the data variables being uploaded to them have to be in the exact same order if you want data created correctly.
By the way the variable $product does not seem to match the column name of user, you may want to check this.

Script posts the first number in value

I am trying to post data to my database. When I post the data I can see that the first number of the value is posted to the database:
Example:
I want to post the value 15. The script posts 1.
I want to post the value 550. The script posts 5.
I want to post the value 30. The script posts 3.
Does someone know the reason for that?
Here is my script:
<input type="text" id="quantity" name="quantity" value="15" />
<input type="text" id="name" name="name" value="550" />
<input type="text" id="price" name="price" value="30" />
<?php
for($count=0; $count<$_POST["total_item"]; $count++)
{
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3= "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
$stmt3 = $db3->prepare($query3);
$exec3 = $stmt3->execute(array(
':id' => $_SESSION['id'],
':quantity' => $_POST["quantity"][$count],
':name' => $_POST["name"][$count],
':price' => $_POST["price"][$count]
));
if($exec3)
{
header('Location: ../succ.php');
}
}
?>
Update 1:
With the answer of Justinas I build the following script:
Dynamic rows:
<input type="text" id="quantity1" name="quantity" value="15" />
<input type="text" id="name1" name="name" value="550" />
<input type="text" id="price1" name="price" value="30" />
<input type="text" id="quantity2" name="quantity" value="15" />
<input type="text" id="name2" name="name" value="550" />
<input type="text" id="price2" name="price" value="30" />
Post:
<?php
foreach($_POST as $i => $item)
{
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3= "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
$stmt3 = $db3->prepare($query3);
$exec3 = $stmt3->execute(array(
':id' => $_SESSION['id'] . '_' . $i,
':quantity' => $_POST["quantity"],
':name' => $_POST["name"],
':price' => $_POST["price"]
));
if($exec3)
{
header('Location: ../succ.php');
}
}
?>
When I post the data to the database I get 18 rows in the database. The data that is posted looks like random data with has no relation with the values in quantity, name or price.
Does someone know what is wrong with the script?
To answer your first issue, the reason that you were only getting the first character of each field value is because you were trying to access the values as if they were arrays, but they were strings -- when you ask for [0] from a string, you will receive the character at the first "offset" aka the first character.
Furthermore, because you had your header() line inside your foreach() loop, you were never going to process more than one set of data before the redirect was executed. The redirect must go outside the loop to prevent causing an early exit.
As for prepared statements, the beauty of prepared statements is that you write the query only once and merely update the bound variables for subsequent executions. In the same vein, you should only create one database connection and keep using it in your script.
Now, as a matter of personal preference, you can choose to write one INSERT query with the entire batch of data or you can conduct several single-row INSERT queries.
As for your question update, you have created unique id values, but duplicated name values for your <input> tags. This means that when the form is submitted, you will not have all of the values in your $_POST array, you will have the "last iterated" set of data. The POST superglobal array is generated using the name values as keys and duplicates keys are not permitted on the same level of an array. So you will have something like this:
$_POST = ["quantity" => "15", "name" => "550", "price" => "30"];
The best advice I can give is to fix your html form. If you don't care about the number associated with each set of fields, use this syntax:
<input type="text" name="quantity[]" value="15" />
<input type="text" name="name[]" value="550" />
<input type="text" name="price[]" value="30" />
With empty square brackets in the name value, php will apply indexed keys while generating a multi-dimensional POST array.
$_POST = [
0 => ["quantity" => "15", "name" => "550", "price" => "30"]
];
If you want to have complete control over the numeric key generated for POST, then write whatever number you wish into the square brackets.
<input type="text" name="quantity[1]" value="15" />
<input type="text" name="name[1]" value="550" />
<input type="text" name="price[1]" value="30" />
<input type="text" name="quantity[4]" value="6" />
<input type="text" name="name[4]" value="577" />
<input type="text" name="price[4]" value="39" />
This generates:
$_POST = [
1 => ["quantity" => "15", "name" => "550", "price" => "30"],
4 => ["quantity" => "6", "name" => "577", "price" => "39"]
];
As for the querying, here is a fully tested demo snippet:
session_start();
$_SESSION['id'] = 44;
$_POST = [
1 => ['quantity' => '15', 'name' => '550', 'price' => '30'],
4 => ['quantity' => '16', 'name' => '551', 'price' => '30']
];
try {
$db = new PDO("mysql:host=localhost;dbname=db;charset=utf8", "root", "");
$stmt = $db->prepare("INSERT INTO scu_test (id, quantity, name, price) VALUES (:id, :quantity, :name, :price)");
foreach ($_POST as $key => $set) {
$exec = $stmt->execute([
':id' => "{$_SESSION['id']}_$key",
':quantity' => $set["quantity"],
':name' => $set["name"],
':price' => $set["price"]
]);
}
header('Location: ../succ.php'); // if error-free, then all successful; redirect
} catch(PDOException $e){
echo "Error message: " , $e->getMessage(); // do not show error messages to users when you go live
}
Inserted Data:
id | quantity | name | price
------|------------|--------|---------
44_1 | 15 | 550 | 30
44_4 | 16 | 551 | 30
It's because your posted data is not multi-dimensional array, but single array:
['quantity' => '', 'name' => '', 'price' => '']
How to fix it:
Add [#] to your HTML:
<div class="item">
<input type="text" class="quantity" name="[0]quantity" value="15" />
<input type="text" class="name" name="[0]name" value="550" />
<input type="text" class="price" name="[0]price" value="30" />
</div>
....
<div class="item">
<input type="text" class="quantity" name="[10]quantity" value="15" />
<input type="text" class="name" name="[10]name" value="550" />
<input type="text" class="price" name="[10]price" value="30" />
</div>
Then in PHP use foreach:
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3 = "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
foreach($items as $i => $item) {
$stmt3 = $db3->prepare($query3);
$result2 = mysqli_fetch_assoc($res2);
$exec3 = $stmt3->execute(array(
':id' => $_SESSION['id'] . '_' . $i, // Don't know why not using Auto-Increment field
':quantity' => $item["quantity"],
':name' => $item["name"],
':price' => $item["price"]
));
if(!$exec3) {
header('Location: ../error.php');
}
}
header('Location: ../succ.php');
Try this
<input type="text" id="quantity1" name="quantity[]" value="15" />
<input type="text" id="name1" name="name[]" value="550" />
<input type="text" id="price1" name="price[]" value="30" />
<input type="text" id="quantity2" name="quantity[]" value="15" />
<input type="text" id="name2" name="name[]" value="550" />
<input type="text" id="price2" name="price[]" value="30" />
your php:
foreach($_POST['quantity'] as $i => $item)
{
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3= "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
$stmt3 = $db3->prepare($query3);
$exec3 = $stmt3->execute(array(
':id' => $_SESSION['id'] . '_' . $i,
':quantity' => $_POST["quantity"][$i],
':name' => $_POST["name"][$i],
':price' => $_POST["price"][$i]
));
if($exec3)
{
header('Location: ../succ.php');
}
}
You should use array in name when using multiple possibilities
<input type="text" id="quantity1" name="quantity[]" value="15" />
<input type="text" id="name1" name="name[]" value="550" />
<input type="text" id="price1" name="price[]" value="30" />
<input type="text" id="quantity2" name="quantity[]" value="15" />
<input type="text" id="name2" name="name[]" value="550" />
<input type="text" id="price2" name="price[]" value="30" />
And in your php script you dont need to append $i in your $_SESSION['id'] just make it primary key and set auto increment in database and do not include it in query it will automatically incremented in each insertion:
<?php
foreach($_POST['quantity'] as $i => $item)
{
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3= "INSERT INTO scu_test(quantity, name, price) VALUES (:quantity, :name, :price)";
$stmt3 = $db3->prepare($query3);
$exec3 = $stmt3->execute(array(
':quantity' => $_POST["quantity"][$i],
':name' => $_POST["name"][$i],
':price' => $_POST["price"][$i]
));
if($exec3)
{
header('Location: ../succ.php');
}
}
?>
This should insert values as they are if the problem still persists check the length in your database for column quantity, name and price. You need to set int(11) for column quantity, name and price if you want to store integer values and if you want to store alphanumeric values than it should be varchar(250)

PHP MySQL insert/update multiple rows at once [duplicate]

This question already has an answer here:
Post form and update multiple rows with mysql
(1 answer)
Closed last year.
I have read this question: https://stackoverflow.com/questions/20255690/php-insert-a-variable-number-of-records-to-mysql-from-a-html-form#=
But I cannot figure out how to apply this to a form with multiple inputs.
I want these inputs to go into the same row (per array id).
My PHP renders the following HTML:
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3 employee-container">
<label for="visible-107">
<img title="Jane Doe" src="/images/prof-pics/default.jpg" class="img-responsive img-circle" alt="Jane Doe">
</label>
<h4><input type="checkbox" name="visible[0]" id="visible-107"> <label for="visible-107">Jane Doe</label></h4>
<div class="input-group">
<span class="input-group-addon">Function</span>
<input type="text" class="form-control" name="function[0]" id="function-107">
</div>
<div class="input-group">
<span class="input-group-addon">Order</span>
<select class="form-control" name="order[0]" id="order-107">
<option value="">-- select one --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
Description<br>
<textarea class="form-control" name="description[0]" id="description-107"></textarea>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3 employee-container">
<label for="visible-2"><img title="John Doe" src="/images/prof-pics/default.jpg" class="img-responsive img-circle" alt="John Doe"></label>
<h4><input type="checkbox" name="visible[1]" id="visible-2"> <label for="visible-2">John Doe</label></h4>
<div class="input-group">
<span class="input-group-addon">Function</span>
<input type="text" class="form-control" name="function[1]" id="function-2">
</div>
<div class="input-group">
<span class="input-group-addon">Order</span>
<select class="form-control" name="order[1]" id="order-2">
<option value="">-- select one --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
Description<br>
<textarea class="form-control" name="description[1]" id="description-2"></textarea>
</div>
</div>
</div>
How would I iterate these arrays so that I can insert/update them as a row per array ID?
After implementing Nana Partykar's answer
function set_team($web_mysqli, $mysqli, $uid, $visible, $function, $order, $description, $action, $update_id = null ) {
$number_empl = sizeof($function);
for($i=0; $i<$number_empl; $i++) {
$uid = $uid[$i];
$visible = $visible[$i];
$function = $function[$i];
$order = $order[$i];
$description = $description[$i];
$name = get_full_name($mysqli, $uid, false);
$sql = "INSERT INTO team (name, function, description, displayorder, visible) VALUES ('$name', '$function', '$description', '$order', '$visible')";
$web_mysqli->query($sql) or die(mysqli_error($web_mysqli));
}
$_SESSION['success'] = "Employee list website updated";
header("Location: ".BASE_PATH."/includes/views/list-employees.php");
exit();
if(isset($_POST['submit-btn'])) {
set_team($web_mysqli, $mysqli, $_POST['uid'], $_POST['visible'], $_POST['function'], $_POST['order'], $_POST['description'], 'insert');
}
When I save only the first name is inserted into the table followed by 3 blank rows.
No Need for name[0],
<input type="checkbox" name="visible[0]" id="visible-107">
<input type="text" class="form-control" name="function[0]" id="function-107">
<select class="form-control" name="order[0]" id="order-107">
<textarea class="form-control" name="description[0]" id="description-107"></textarea>
Make
<input type="checkbox" name="visible[]" id="visible-107">
<input type="text" class="form-control" name="function[]" id="function-107">
<select class="form-control" name="order[]" id="order-107">
<textarea class="form-control" name="description[]" id="description-107"></textarea>
SomePage.php (Submit Page)
<?
extract($_POST);
$sizeOfFunc=sizeof($function);
for($i=0;$i<$sizeOfFunc;$i++)
{
$Visible=$visible[$i];
$Function=$function[$i];
$Order=$order[$i];
$Description=$description[$i];
echo $Visible." ".$Function." ".$Order." ".$Description;
//Use $Visible, $Function, $Order, $Description in your query
}
?>
Updated Code
Don't use same variable name. Atleast change variable name.
This is wrong.
$uid = $uid[$i];
$visible = $visible[$i];
$function = $function[$i];
$order = $order[$i];
$description = $description[$i];
This is correct
$Uid = $uid[$i];
$Visible = $visible[$i];
$Function = $function[$i];
$Order = $order[$i];
$Description = $description[$i];
I've changed your code. Use the below code. It will work.
<?
function set_team($web_mysqli, $mysqli, $uid, $visible, $function, $order, $description, $action, $update_id = null ) {
$number_empl = sizeof($function);
for($i=0; $i<$number_empl; $i++) {
$Uid = $uid[$i];
$Visible = $visible[$i];
$Function = $function[$i];
$Order = $order[$i];
$Description = $description[$i];
$name = get_full_name($mysqli, $Uid, false);
$sql = "INSERT INTO team (name, function, description, displayorder, visible) VALUES ('$name', '$Function', '$Description', '$Order', '$Visible')";
$web_mysqli->query($sql) or die(mysqli_error($web_mysqli));
}
$_SESSION['success'] = "Employee list website updated";
header("Location: ".BASE_PATH."/includes/views/list-employees.php");
exit();
if(isset($_POST['submit-btn'])) {
set_team($web_mysqli, $mysqli, $_POST['uid'], $_POST['visible'], $_POST['function'], $_POST['order'], $_POST['description'], 'insert');
}
?>
I checked your code in my system after editing. It working fine.
<?
error_reporting(0);
extract($_POST);
echo $number_empl = sizeof($function);
for($i=0; $i<$number_empl; $i++)
{
$Visible = $visible[$i];
$Function = $function[$i];
$Order = $order[$i];
$Description = $description[$i];
$name="Just";
echo $sql = "INSERT INTO team (name, function, description, displayorder, visible) VALUES ('$name', '$Function', '$Description', '$Order', '$Visible')"."<br>";
}
?>

Write loop sql query from data array (php, mysql)

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);
}

PHP mysql: inserting data from an array

I'm having trouble extracting arrays to insert into the database. My form accepts multiple and dynamic number of inputs so I have the data in an array with inputs phonenos[] and phonetypes[]:
<form name="add" action="" method="POST">
<input name="name" type="text" placeholder="Name"></input><br />
<input name="qty" type="text" placeholder="Qty"></input><br /> -->
<input class="form-control required" name="phonenos[]" maxlength="14" type="text" placeholder="number..."><br>
<select class="form-control" name="phonetypes[]">
<option value="0">Choose a phone type</option>
<option value="Main">Main</option>
<option value="Fax">Fax</option>
<option value="Mobile/Direct">Mobile/Direct</option>
</select>
<div id="addmore">
<input type="button" value="Add More" onClick="addRow(this.form)"></input>
</div>
<input type="submit" value="submit" name="action"></input>
</form>
In my PDO query:
..... first query insertion...
$phonenos = $_POST['phonenos'];
foreach($_POST['phonenos'] as $phoneno) {
$phoneno;
}
$phonetypes = $_POST['phonetypes'];
foreach($_POST['phonetypes'] as $phonetype) {
$phonetype;
}
$sql = 'INSERT INTO phone (p_id, phoneno, phonetype) values (:p_id, :phoneno, :phonetype)';
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phoneno'=>$phoneno,
':phonetype'=>$phonetype
));
So I did a var_dump on variables $phoneno and $phonetype after a submission of multiple phone numbers and it only printed out the last number and type whereas I wanted the entire list that was submitted. How do I get all the data so I can insert it into the database?
If you want all the numbers inserted in the same column, then the best solution I can think is to serialize them before you insert in db.
$phonenos = serialize($_POST['phonenos']);
$phonetypes = serialize($_POST['phonetypes']);
$sql = 'INSERT INTO phone (p_id, phoneno, phonetype) values (:p_id, :phoneno, :phonetype)';
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phoneno'=>$phonenos,
':phonetype'=>$phonetypes
));
I figured out the solution through a for loop.
$phones = $_POST['phones'];
$phonetypes = $_POST['phonetypes'];
for($i = 0, $j = 0; $i <= $phones, $j <= $phonetypes; $i++, $j++) {
$phone = $phones[$i];
$phonetype = $phonetypes[$j];
$sql = "INSERT INTO phone (p_id, phone, phonetype) values (:p_id, :phone, :phonetype)";
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phone'=>$phone,
':phonetype'=>$phonetype
));
}

Categories