I'm trying to insert multiple rows in a while loop with a form using implode but cannot seem to make it work. I want to insert multiple values named "weight". Like values 30,20,15,10,5 and the remaining emp_id and task_id.
page1.php
$sql = mysql_query("SELECT
task_tbl.task_id,
task_tbl.task_name,
task_tbl.task_sem,
task_tbl.task_yr,
task_tbl.post_id,
post_tbl.post_id,
post_tbl.post_name AS ppost_name
FROM
task_tbl
LEFT JOIN
post_tbl
ON
task_tbl.post_id = post_tbl.post_id
WHERE
task_sem = '$sem'
AND
task_yr = '$yr'
ORDER BY
task_id ASC");
echo '<form action = "upds_peval.php" name = "add" method = "post">';
while($row = mysql_fetch_assoc($sql)){
echo "<br/>";
echo "<b>Employee ID No.:</b>";
echo '<input size = "2" type = "text" name = "emp_id'.$id.'" value = "';
echo $_POST['emp_id'];
echo '"/>';
echo "<br/>";
echo "<b>Work/Activity ID No.:</b> ";
echo '<input size = "2" type = "text" name = "task_id'.$row['task_id'].'" value = "';
echo $row['task_id'];
echo '"/>';
echo "<br/>";
echo "<b>Work/Activity:</b> ";
echo $row['task_name'];
echo "<br/>";
echo "<b>Weight:</b> ";
echo '<input size = "1" type="text" name="weight" value = ""/>';
echo "%";
echo "<br/>";
}
echo '<input type="submit" name="submit" value="ADD"/>';
echo "</form>";
the output would be like:
Employee ID No.: 1001
Work/Activity ID No.: 2002
Work/Activity: Supervises Maintenance and Troubleshooting of Computers
Weight: [__]%
Employee ID No.: 1001
Work/Activity ID No.: 2003
Work/Activity: Supervises Software Installation and Maintenance
Weight: [__]%
Employee ID No.: 1001
Work/Activity ID No.: 2004
Work/Activity: Maintains, Monitors, and Troubleshoots Virtual Terminals
Weight: [__]%
|SUBMIT|
page2.php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("emp_db0");
if(isset($_POST['submit'])){
$_POST['weight'];
$vals=implode(",",$_POST);
error_reporting(E_ALL ^ E_NOTICE);
mysql_query("INSERT INTO peval_tbl(weight,task_id,emp_id) VALUES('$vals')");
echo "<br/>";
echo "You have successfully added work/activities!";
echo "<br/>";
}
okay based on my impression of your question, you want a form that is extensible right, where you can access all of its instance in one name?
1st Instance of form sample:
<input size = "2" type = "text" name = "emp_id[]" value = "1">
<input size = "2" type = "text" name = "task_id[]" value = "5001">
<input size = "2" type = "text" name = "weight[]" value = "50">
2nd Instance sample:
<input size = "2" type = "text" name = "emp_id[]" value = "2">
<input size = "2" type = "text" name = "task_id[]" value = "5003">
<input size = "2" type = "text" name = "weight[]" value = "30">
this will convert your posts into arrays
to access:
$var_emp_id = $_POST["emp_id"];
$var_task_id = $_POST["task_id"];
$var_weight_id = $_POST["weight"];
use a loop to access those variables.
to access the first instance of emp_id u use:
$var_emp_id[0]; //will output 1
$var_emp_id[1]; //will output 2
$var_task_id[0]; //will output 5001
$var_task_id[1]; //will output 5003
to insert it on your database:
for ($i = 0; $i <= count($var_emp_id); $i++){
mysql_query("INSERT INTO peval_tbl(weight,task_id,emp_id) VALUES('$weight[$i]','$var_task_id[$i]','$var_emp_id[$i]')");
}
You are addressing the $_POST array incorrectly, so rather than recode your script try this.
Add this line to your code in page2.php before the mysql_connect
echo '<pre>' . print_r($_POST,true) . '</pre>';
This will dump a nice print of the post array so you can see how data arrives in $_POST.
$sql = "select * from login where nombre !='carlos'";
$result = $conn->query($sql);
$index = 1;
while($row = mysqli_fetch_array($result)){
$valor = $row["nombre"];
$valor2 = $row["apellido"];
$insertsql= "insert into lista (`dato1`,`dato2`)values ('$valor', now())";
// mysql_query($insertsql);
$conn->query($insertsql);
$index++;
}
http://www.baulphp.com/insertar-multiples-registros-ciclo-while-php/
Related
My Issue:
<?php //sqltest.php
//Part 01 - The first part of the code will establish connection with DB using mysqli method
require_once 'login.php';
$conn = new mysqli($hn,$un,$pw,$db);
if ($conn->connect_error) die ($conn->connect_error);
// Part - 02 - Here is the method to delete some data using query by taking input and later checking using isset
if (isset($_POST['delete']) && isset ($_POST['isbn'])){
$isbn = get_post($conn,'isbn');
$query ="DELETE FROM classics WHERE isbn = '$isbn'";
$result = $conn->query($query);
if (!$result) echo "DELETE failed: $query<br>". $conn->error . "<br><br>";
}
//Part 04 - Here is the method to insert some data using query by taking input by get_post method-(see the last code) and checking using isset
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn'])){
$author = get_post($conn,'author');
$title = get_post($conn,'title');
$category = get_post($conn,'category');
$year = get_post($conn,'year');
$isbn = get_post($conn,'isbn');
$query = "INSERT INTO classics VALUES" . "('$author','$title','$category','$year','$isbn')";
$result = $conn->query($query);
if (!$result) echo "INSERT failed: . $query<br> ". $conn->error. "<br><br>";
}
//Part - 05 - FORM handler
echo <<<_END
<form action="sqltest.php"
method="post">
<pre>
Author <input type = "text" name ="author">
Title <input type = "text" name = "title">
Category <input type = "text" name = "category">
Year <input type = "text" name = "year">
ISBN <input type = "text" name = "isbn">
<input type = "submit" value = "ADD RECORD">
</pre>
</form>
_END;
// Part - 06 -A new query for showing the whole classics table from DB
$query = "SELECT * FROM classics";
$result = $conn->query($query);
if(!$result) die ("Database access failed: ". $conn->error);
$rows = $result->num_rows;
for ($j=0; $j<$rows; ++$j){
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
// Part - 07 The following html code will take the iput for deleting any entry using isbn - refers to 1st part of the code
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action = "sqltest.php" method = "post">
<input type ="hidden" name = "delete" value = "yes">
<input type = "hiddden" name = "isbn" value = "$row[4]">
<input type="submit" value = "DELETE RECORD">
</form>
_END;
}
$result->close();
$conn->close();
//Part 08 - actually the code begins from here
function get_post($conn,$var)
{
return $conn->real_eascape_string($_POST[$var]);
//to avoid special charecter
}
?>
/** The code is working very fine. Except two thing: 1. In part 7 of the code i mentioned the isbn number to be keep hidden and only show the delete button. But in output it is showing both number and button. 2. The boxes with the record fields are not set according which is not looking good as expected - i used pre but still it's showing broken output.**/
For #1, you have a typo in hiddden (correct one should be hidden).
For #2, learn how to use css to style the form. Also learn how to use html label tag.
Some people suggests to use table for formatting which is not a best practice and should be avoid.
In general, HTML should only contain information about your content, and CSS take care of the presentation of the content. This is called Separation of Concerns.
The isbn is displayed because you have a spelling issue. You wrote hidden with 3 d‘s in part 7. hope this helps :)
<?php //sqltest.php
//Part 01 - The first part of the code will establish connection with DB using mysqli method
require_once 'login.php';
$conn = new mysqli($hn,$un,$pw,$db);
if ($conn->connect_error) die ($conn->connect_error);
// Part - 02 - Here is the method to delete some data using query by taking input and later checking using isset
if (isset($_POST['delete']) && isset ($_POST['isbn'])){
$isbn = get_post($conn,'isbn');
$query ="DELETE FROM classics WHERE isbn = '$isbn'";
$result = $conn->query($query);
if (!$result) echo "DELETE failed: $query<br>". $conn->error . "<br><br>";
}
//Part 04 - Here is the method to insert some data using query by taking input by get_post method-(see the last code) and checking using isset
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn'])){
$author = get_post($conn,'author');
$title = get_post($conn,'title');
$category = get_post($conn,'category');
$year = get_post($conn,'year');
$isbn = get_post($conn,'isbn');
$query = "INSERT INTO classics VALUES" . "('$author','$title','$category','$year','$isbn')";
$result = $conn->query($query);
if (!$result) echo "INSERT failed: . $query<br> ". $conn->error. "<br><br>";
}
//Part - 05 - FORM handler
echo <<<_END
<form action="sqltest.php"
method="post">
<pre>
Author <input type = "text" name ="author">
Title <input type = "text" name = "title">
Category <input type = "text" name = "category">
Year <input type = "text" name = "year">
ISBN <input type = "text" name = "isbn">
<input type = "submit" value = "ADD RECORD">
</pre>
</form>
_END;
// Part - 06 -A new query for showing the whole classics table from DB
$query = "SELECT * FROM classics";
$result = $conn->query($query);
if(!$result) die ("Database access failed: ". $conn->error);
$rows = $result->num_rows;
for ($j=0; $j<$rows; ++$j){
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
// Part - 07 The following html code will take the iput for deleting any entry using isbn - refers to 1st part of the code
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action = "sqltest.php" method = "post">
<input type ="hidden" name = "delete" value = "yes">
<input type = "hidden" name = "isbn" value = "$row[4]">
<input type="submit" value = "DELETE RECORD">
</form>
_END;
}
$result->close();
$conn->close();
//Part 08 - actually the code begins from here
function get_post($conn,$var)
{
return $conn->real_escape_string($_POST[$var]);
//to avoid special charecter
}
?>
I'm using a datalist to store all of the names and surnames in that I retrieve from a MySQL database table.
When someone inputs the name and surname of a tutor and clicks "show tutor", showTutor() is called.
<input list="tutorData" name="tutors" id="tutorToShow">
<datalist id="tutorData">
<?php
$sql = "SELECT name, surname FROM tutors ORDER BY surname ASC";
if (!$res = $link->query($sql)) {
trigger_error('error in query ' . $link->error);
} else {
while ($row = $res->fetch_assoc()) {
$name = $row['surname'];
$sName = $row['name'];
?>
<option value="<?php echo "$sName $name" ?>" >
<?php
}
}
?>
</datalist>
<input type="button" value="Weergeven" onclick="showTutor();">
My datalist is filled up and works perfectly. Now: When showTutor is called, so when the button was clicked:
function showTutor(){
var tut = document.getElementById("tutorToShow").value;
}
This gives me something like John Smith or Mary Jane Dough.
What the problem is though, when I reload the shown tutor div with ajax, I need to retrieve that tutor's ID from the database.
So what I'll definitely need is this SQL:
SELECT ID
FROM tutors
WHERE name LIKE '$name%'
AND surname LIKE '$surname%'
Now I just need to separate the name.
In other words, how do I retrieve the ID from a table with columns ID, name, surname, without knowing the separation between name or surname?
John Smith: easy, first word is name, second word is surname
Mary Jane Dough: now what?
I thought of adding a comma that seperates both names, but that's not very stylish.
Another option is to add a column to my database that has both names in one record, but that's a hassle when new tutors need to be added.
Do this before you assign the data into your elements
if (strpos($sName, ' ') != false) {
// if above string position of space isn't false,
// explode the string at the space into an array of
// individual names.
$sName = explode(' ', $sName);
echo $sNames[0];
echo $sNames[1];
// you will need to look at foreach loop and counting the array length
}
Try this.
<datalist id="tutorData">
<?php
$sql = "SELECT name, surname FROM tutors ORDER BY surname ASC";
if (!$res = $link->query($sql)) {
trigger_error('error in query ' . $link->error);
} else {
while ($row = $res->fetch_assoc()) {
$surname = $row['surname'];
$first_names = $row['name'];
if (strpos($first_names, ' ') != false) {
/*
if above string position of space isn't false,
explode the string at the space into an array of
individual names.
*/
$first_name = explode(' ', $first_names); // EG: Paul John
$name1 = $first_name[0]; // Paul
$name2 = $first_name[1]; // John
/*
you will need to look at foreach loop and counting
the array length
*/
}
?>
<option value="<?php echo $name1 . ' ' . $name2 . ' ' . $surname" ?>" >
<?php
}
}
?>
</datalist>
I'm sorry for the delay, #Oli helped me in chat a few weeks ago.
<input list="tutorData" name="tutors" id="tutorToShow">
<datalist id="tutorData">
<?php
$sql = "SELECT name, surname, id FROM tutors ORDER BY surname ASC";
if (!$res = $link->query($sql)) {
trigger_error('error in query ' . $link->error);
} else {
while ($row = $res->fetch_assoc()) {
$name = $row['surname'];
$sName = $row['name'];
$id = $row['id'];
?>
<option value="<?php echo "$sName $name" ?>" data-id="<?php echo $id; ?>">
<?php
}
}
?>
</datalist>
<input type="button" value="Show" onclick="showTutor();">
So basically I've only added a data-id, I then wrote this javascript:
<script>
function showTutor() {
var tut = document.getElementById("tutorToShow").value;
var list = document.getElementById("tutorData");
var length = list.options.length;
var id;
for (var i = 0; i < length; i++) {
var eachTutor = list.options[i].value.toLowerCase();
if (tut === eachTutor) {
id = list.options[i].getAttribute('data-id');
}
}
}
</script>
I now have the id of the tutor, without separating any name. I also post it to a php page with ajax, but that is not relevant to the question.
Thanks again to the ones that helped.
I've got a dropdown menu that is supposed to update my SQL query. If I create the dropdown from the select HTML, it works fine, but when I run it from a PHP array it doesn't select the other options when posted (though it does select them if I manually select the array element from in the program.
Moreover, I've put several echo statements throughout the program to trouble shoot, and I can clearly see that the correct item is being selected, AND that it's posting to the SQL code, but it's just not working right.
For example, my echo statements print out the SQL query
sql = SELECT * from finished_goods WHERE BrandDesc LIKE '%Alma Rosa%'
which works fine. but if I use the drop down to select "alere" it doesn't work.
sql = SELECT * from finished_goods WHERE BrandDesc LIKE '%Alere%'
<table>
<form id = "myform" method="post" action="">
<th>FG id : <input type = "text" name = "finished_goods_id2"/></th>
<th>Product No : <input type = "text" name = "ProdNo"/></th>
<th>Product Name : <input type = "text" name = "ProductName"/></th>
<th>Product Group : <input type = "text" name = "ProductGroup"/></th>
<!-- this code puts a drop down in, but it doesnt update the form -->
<th>Brand : <!-- this select statement works fine
<select name = "BrandDesc">
<option value = "Alma Rosa">Alma Rosa text</option>
<option value = "Alere">Alere</option>
<option value = "Hitching Post">Hitching Post text</option>
</select>
-->
<?php // this array replaces the select dropdown, but doesn't update
$name = 'BrandDesc';
$selected = 0;
$options = array( 'Alma Rosa', 'Alere', 'Hitching Post' );
echo dropdown( $name, $options, $selected );
?>
<th>Varietal : <input type = "text" name = "Varietal"/></th>
<th>Vintage : <input type = "text" name = "VintYear"/></th>
<th>Quantity :</th>
<th><input type = "submit" name = "send" value = "Submit"/></th>
<tr></tr>
<?php
// new connection
$conn = dbConnect('read', 'thereal8_work', 'PDO'); // database for online
$brandNo = 0; // sets the brand so that it displays the first select statement
$brandAccess = $options[$brandNo];
echo " first Brand Access = ".$brandAccess. " <br>";
if ($_POST['BrandDesc']) {
echo " base brandNo = ".$brandNo. "<br>";
$brandNo = $_POST['BrandDesc'];
echo " posted brandNo = ".$brandNo. " <br> ";
echo "options in the function = ".$options[$brandNo]. "<br>";
//$brandAccess = $_POST['BrandDesc'];
$brandAccess = $options[$brandNo];
echo "submitted brand = ".$brandAccess. " <br> ";
}
$sql = "SELECT * from finished_goods WHERE BrandDesc LIKE '%$brandAccess%' ";
echo "sql = ".$sql." <br>";
// get the result
Thanks,
I have a form that is dynamically created based off multiple mysql tables. This form sends to an external page for processing.
this means that my $_POST data will always be different. I need to extract the post array, strip it down and create a query.
here's the print_r of the Posted array:
Array ( [userid] => 1 [modid1] => on [fid1] => on [fid3] => on [fid5] => on [fid7] => on [fid8] => on [modid3] => on )
as you can see I have three parts to this userid, modid, and fid. the catch is, the only way I could pass the id's I need is to name the fields that. So each modid and fid are rows in the db. the number after that is the id that needs updating, and of course "on" is from the check box.
so end result would be something like:
to give a better idea here's how I would write the query normally
for modid1:
UPDATE table SET var = var WHERE modid = 1
for fid1
UPDATE table SET var = var WHERE fid = 1
heres the code that generated this array:
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$modsql = mysql_query("SELECT * FROM modules")or die("Mod failed " .mysql_error());
while($row = mysql_fetch_array($modsql))
{
echo '<div class="rights">';
echo "<ul>";
$userid = safe($_POST['user']);
$id = $row['id'];
$sql = mysql_query("SELECT * FROM modpermissions WHERE userid = '$userid' AND modid = '$id'")or die("Mod died " .mysql_error());
$sql2 = mysql_fetch_array($sql);
$modper = $sql2['modpermission'];
if($modper == 1){
echo '<li><input type="checkbox" name="modid'.$row["id"].'" checked> <b>'.$row["name"].'</b></li>';
}
if($modper == 0){
echo '<li><input type="checkbox" name="modid'.$row["id"].'"> <b>'.$row["name"].'</b></li>';
}
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT * FROM features WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
$userid2 = safe($_POST['user']);
$id2 = $row2['id'];
$sql3 = mysql_query("SELECT * FROM fpermissions WHERE userid = '$userid2' AND fid = '$id2'")or die("features died " .mysql_error());
$sql4 = mysql_fetch_array($sql3);
$fper = $sql4['fpermission'];
if($fper == 1){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'" checked> '.$row2['feature'].'</li>';
}
if($fper == 0){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'"> '.$row2['feature'].'</li>';
}
}
echo "</ul>";
}
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
its a mess I know, im learning. If someone can understand my question and point me in the right direction to accomplish what Im attempting I would be grateful.
First thing to do is to store the old value as well as having the check box (using a hidden field).
I would also suggest as a minimum using a fixed character as a delimeter in your field names so you can explode the field name to easy get the part that is the id.
Also consider using joins rather than looping around one result, and for each one doing another query.
Your output script would look something like this:-
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$userid = safe($_POST['user']);
$modsql = mysql_query("SELECT modules.id, modules.features, modules.name, modpermissions.modpermission
FROM modules
LEFT OUTER JOIN modpermissions
ON modules.id = modpermissions.modid
AND modpermissions.userid = '$userid'")or die("Mod failed " .mysql_error());
$PrevModuleId = 0;
while($row = mysql_fetch_array($modsql))
{
if ($PrevModuleId != $row['id'])
{
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
echo '<div class="rights">';
echo "<ul>";
$PrevModuleId = $row['id'];
}
echo '<li><input type="checkbox" name="modid_'.$row["id"].'" '.(($row['modpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="modid_old_'.$row["id"].'" value="'.$row['modpermission'].'"> <b>'.$row["name"].'</b></li>';
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT features.id, features.feature, fpermissions.fpermission
FROM features
INNER JOIN fpermissions
ON features.id = fpermissions.fid
AND fpermissions.userid = $userid
WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
echo '<li><input type="checkbox" name="fid_'.$row2["id"].'" '.(($row2['fpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="fid_old_'.$row2["id"].'" value="'.$row2['fpermission'].'"> '.$row2['feature'].'</li>';
}
echo "</ul>";
}
}
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
You can then loop through each entry on the $_POST array, explode the key based on the _ character, check when the values have changed and if needs be do an update Or possibly you can use an INSERT instead, but using ON DUPLICATE KEY update type syntax (this way you can update many rows with different values easily).
Note you also need to put the userid value somewhere in your form (probably as another hidden field) so you have the value to process with the updates.
I've got this code designed to echo a list of people from a specific location. You can then group all these people by checking boxes next to their names and submitting the form which will update the database with the new group. It all sounds pretty simple. But unfortunately the database is set up using a lot of tables that are associated with one another. So it gets a bit complicated. Here's what I have so far:
<?php
//Query the database for the Location ID of the currently logged in user
$query1 = mysql_query("SELECT * FROM `Location` WHERE Name = '".$_SESSION['Location']."'");
$array1 = mysql_fetch_array($query1);
//Query the database for the all the participants in this location, make an array of the results and then implode the array
$query2 = mysql_query("SELECT idParticipant FROM `Participant/Location` WHERE idLocation = ".$array1['idLocation'].";");
$column1 = array();
while($row = mysql_fetch_array($query2)){
$column1[] = $row['idParticipant'];
}
$values = implode(' OR ', $column1);
//Query database for all first names where the particpant ID's equal those of the above $values
$query3 = mysql_query("SELECT firstName FROM `Participant` WHERE idParticipant = $values;");
$columnFirstName = array();
while($row = mysql_fetch_array($query3)){
$columnFirstName[] = $row['firstName'];
}
foreach($columnFirstName as $value){
echo "<input type='checkbox' name='check[]' id='' value='' />";
echo $value."<br><br>";
}
?>
<input type="submit" name="submit" value="Save New Group">
</form>
So the above code echoes out all the first names in that location and adds a check box beside it. The problem is I need the second names to appear beside the first names too. AND I need to get the ID's of each person to put in the value for the checkbox.
I'm not sure how I can do this... I think I need to make a second query for the second names then tweak my foreach loop...and I'll probably need a whole new foreach loop for the id's, won't I?
This is what I needed to do:
$query3 = mysql_query("SELECT * FROM `Participant` WHERE idParticipant = $values;");
$columnFirstName = array();
$columnSecondName = array();
$columnID = array();
while($row = mysql_fetch_array($query3)){
$columnFirstName[] = $row['firstName'];
$columnSecondName[] = $row['secondName'];
$columnID[] = $row['idParticipant'];
}
for($i=0;$i<count($columnFirstName);$i++) {
$firstName = $columnFirstName[$i];
$secondName = $columnSecondName[$i];
$id = $columnID[$i];
echo "<input type='checkbox' name='check[]' id='$id' value='$id' />";
echo $firstName." ";
echo $secondName."<br><br>";
}
?>
<input type="submit" name="submit" value="Save New Group">
</form>