php/mysql two variable array - php

I am allowing user to create up to ten categories using text boxes in a form. To do this I have ten textboxes in the form with name = cat[]. The first time they enter categories--however many, up to ten, on the receiving end, I just collect the array of categories and save them to a table of categories using an insert statement. So far so good.
However, now I want to let them change categories they already set or add extras up to ten total. The categories they already set have ids. So I echo the ids to the form along with the category names. My problem is how do I collect the names and ids now? New ones need to be inserted and existing ones may need to be updated in the table? For some reason, I'm at a total loss how to do this. This is what I have so far>
Table Cats
id | catname | userid
Form page:
//retrieve existing cats if any...also get catids
echo '<form action = storecats.php method=post>';
$i=1;
//Get all existing cats
while($row = mysql_fetch_array($res))
{
$catname = $row['catname'];
$catid = $row['id'];
echo '<input type = "text name="cat[]" value="'.$catname.'">Cat 1';
echo '<input type="hidden" name="id[]" value = "'.$catid.'">';
$i = $i+1;
}
//empty boxes up to ten.
while($i <= 10){
echo '<input type="text" size=18 name="cat[]" value=""> Cat '.$i.'<br>';
$i = $i+1;
}//end appending of blank categories
echo '<input type="submit" name="submit" value="submit"></form>';
On receiving end, I can collect the array for cat and id.
$idarray = $_POST['id']; //there will be as many elements as there were ids
$catarray = $_POST['cat']; //there will be ten elements in array
Where there is an id, I want to perform an update whereas where there is no id I want to insert unless the value is blank.
My problem is I can't figure out how to link the id and the cat names being received in the different arrays. Note, there will always be ten cat names but there will only be as many ids as were in the table for that user previously.

You can do it with 2 array on HTML side:
$x=0;
while ($row = mysql_fetch_array($res))
{
echo '<input type="text" name="updateCat['.$row["id"].']" value="'.$row["catname"].'"> Cat Name';
$x++;
}
// new ones
for(;$x<10;$x++)
{
echo '<input type="text" name="newCat[]">';
}
and on php side:
// update old categories
foreach ($_POST["updateCat"] as $key => $value)
{
mysql_update ("UPDATE table SET name = $value WHERE id = $key");
}
// insert
foreach ($_POST["newCat"] as $value)
{
mysql_update ("INSERT INTO table {...}");
}
You have also check that there are not more than 10 Categories when inserting new ones.

Name the inputs which are for existing categories cat_update[] and name inputs which are for new categories cat_insert[]. When you process the form data with PHP you have three arrays:
$ids = $_POST['id']; // Ids for update
$update = $_POST['cat_update']; // Values for UPDATE
$insert = $_POST['cat_insert']; // Values for INSERT
for($i = 0; $i < count($ids); $i++) {
//Execute 'UPDATE `table` SET `value` = $update[$i] WHERE `id` = $ids[$i]
}
for($i = 0; $i < count($insert); $i++) {
//Execute 'INSERT INTO `table` (`value`) VALUES ($insert[$i])
}

I'm not sure I get it, but you could simply give different names to the two sets of categories.
In your second loop putting 'name = "new_cat[]"' will allow you to distinguish between modified categories ('$_POST[cat]') and new ones to be inserted ('$_POST[new_cat]') in your receiving storecats.php code.

Related

How do I list each value from my_sqli_fetch_row?

I have two sql statements.
1 lists all columns from my table using mysqli_fetch_assoc
The other statements returns a row where id = specific id using mysqli_num_rows
My problem is that with the mysqli_fetch_assoc, I'm able to use something like:
$rowz['Field'] and it returns the value for every single column name. This is perfect, but, I am unable to get every single value in my row as well. In other words, My code lists all fields: id / name / phone... but when I use myqli_fetch_row, it returns the value for just one column over and over. So every field will just show '193' which is the id. I want all fields to show proper value instead of just the same value from one column over and over.
// listing all columns from table
$sql2 = ("SHOW COLUMNS FROM articles");
$result55 = mysqli_query($link, $sql2);
echo'<form action="update.php" method="POST">';
if (mysqli_num_rows($result55) > 0)
{
// to fetch row of specific id
$sql = "SELECT * FROM articles WHERE ID='".$id."'";
$result5 = mysqli_query($link, $sql);
if (!$result5) {
echo 'no';
}
$row = mysqli_fetch_row($result5);
while($rowz = mysqli_fetch_assoc($result55)){
$z = 0;
echo '
<input class="form-control" type="text" name="'.$rowz['Field'].'"
value="'.$row[$z].'" />';
}
}
echo' </form>';
The issue is the name of the input field, where I have '.$row[$z].' it just keeps returning 0 from array which is just the ID column. Hence why I just keep getting 193 over and over. However, the $rowz['Field'] works much better and loops every single time for each existing column. I hope to get: id = 193, name = john, phone = 123-3345 etc.. But instead I get: id = 193, name = 193, phone = 193.
Please send help!
$z is your column index. and it should be your counter, if you want to generate each column values.
$z = 0;
while($rowz = mysqli_fetch_assoc($result55)){
echo '
<input class="form-control" type="text" name="'.$rowz['Field'].'"
value="'.$row[$z].'" />';
$z = $z + 1;
}
You have declared $z=0 inside the while loop.
Rather you have to declare it before the while loop and increment it inside the loop.
You have used $z as the index for $row which indicates the specific column of the result obtained from the query.
When you fix it to 0, it means that the first column value only is getting accessed.
$row = mysqli_fetch_row($result5);
$z=0;
while($rowz = mysqli_fetch_assoc($result55))
{
echo '
<input class="form-control" type="text" name="'.$rowz['Field'].'"
value="'.$row[$z].'" />';
$z = $z +1;
}

insert using multiple foreach inside for each only gets the final value in every foreach

I am currently working on a evaluation system. The questions are dynamically created/
So I already tried insert values from different foreach of input fields I use input type text instead of radio button. my code is just inserting the last value get from each foreach loop.
<?php
session_start();
include('connectDB.php');
$userId= $_SESSION['id'];
mysqli_query($conn,"UPDATE student SET evaluationId = 1 WHERE studentId='$userId'");
foreach($_POST['nPersonnelId'] as $personnelId ){
for ($i=0; $i<count($_POST['rCourteous']); $i++){
$rCourteous = $_POST['rCourteous'][$i];
}
for ($i=0; $i<count($_POST['rPrompt']); $i++){
$rPrompt = $_POST['rPrompt'][$i];
}
for ($i=0; $i<count($_POST['rCompetent']); $i++){
$rCompetent = $_POST['rCompetent'][$i];
}
for ($i=0; $i<count($_POST['rAccom']); $i++){
$rAccom = $_POST['rAccom'][$i];
}
mysqli_query($conn,"INSERT INTO qpanswer
(studentId,personnelId,courteous,prompt,competent,accommodating)
VALUES ('$userId','$personnelId','$rCourteous','$rPrompt','$rCompetent','$rAccom')");
}
header('location:studentDashboard.php');
?>
You don't need all of the inner loops, just get the index from the outer loop and use that for all of the inner arrays. So here get $i from the foreach key...
foreach($_POST['nPersonnelId'] as $i => $personnelId ){
$rCourteous = $_POST['rCourteous'][$i];
Same for each of the other fields.
Also as pointed out - use prepared statements.

Passing multiple checkbox values to different columns of database

I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."

Loop through form to update SQL Database

I am building a page that writes out a varying number of categories and then, under each category, writes out the units associated with that category. Each category section is a single form with fields that are repeated and named according to what row they belong to. The layout is like this:
Category 1
Unit 1 Update Fields
Unit 2 Update Fields
Unit 3 Update Fields
Submit Button for Category 1
etc.
Each field is named the same thing with the unit number added on the end:
Features1, Features2, Features3, etc.
The total number of rows in a given category is held in the variable $id# where # is the category's ID (ex: $id1, $id2, $id3, etc).
I've got most of this sorted out. However, I want to loop through and perform a SQL query if the form has been changed, and that's where I'm having trouble. At this point, I'm at a loss. Here is a simplified version of my code:
if (isset($_POST['submit'])) {
$form = $_POST['form']; //save which category we're on in a variable.
for ($i = 1; $i <= ${id.$form}; $i++) { //I think the problem is here
$Feature = $_POST['Feature'.$i];
$update = "UPDATE Units
SET Feature ='$Feature'
WHERE ID='$i'";
if (($Feature!=${initialFeature.$i})) {
$updateQuery = mysqli_query($dbc, $update);
}
}
}
How can I make this work? Is there a better way to do this?
The way I would do it is using an array in field names.
<input type="text" name="id[]" value="$foo">
Then on the action page for the form
$id = $_POST['id'];
for($i=0;$i<sizeof($id),$i++){
...//do something here using $id[$i] to select elements in the array
}
I think that is what you're trying to do.
try this
for($i=0; $i<3; $i++)
echo '<input type="text" name="feature[]" value=""/>';
echo '<input type="submit" name="go" value="submit">';
if (isset($_POST['go'])) {
$feature = $_POST['feature'];
if(is_array($feature)){
for ($i = 1; $i <= count($feature); $i++) {
$update = "UPDATE Units
SET Feature ='$feature[$i]'
WHERE ID='$i'";
$updateQuery = mysqli_query($dbc, $update);
}
}else{
$update = "UPDATE Units
SET Feature ='$feature'
WHERE ID='$i'";
$updateQuery = mysqli_query($dbc, $update);
}
}
hope this code can solve your problem

1 checkbox with 2 value from sql pass the selection

Hi all
Now is 2 week that i searching for an answer to my problem and no luck. hope somone can help me on this
i have a chackbox option that i call from the database
<form style="margin-top:-30px" method="POST" action="extradata.php">
<?php
$sql = "SELECT ext_id,ext_price,ext_name,ext_description FROM tbl_extra ORDER by ext_id ASC";
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
$number = mysql_num_rows($result);
$i = 0;
while ($number > $i) {
$NA= mysql_result($result,$i,"ext_name");
$PR= mysql_result($result,$i,"ext_price");
print "<input type='checkbox' name='extra[]' value='$NA'></td>";
$i++;
}
?>
What i trying to do is to pass the value to extradata.php with 2 value
1.$NA,
2.$PR
when selected box then insert to the database the value of $NA to ex_tra and $PR to ex_price
the extradata.php
<?php
require_once 'library/config.php';
$id=$_POST['pd_id'];
$ssid=$_POST['ct_session_id'];
$total=$_POST['tot'];
$name=$_POST['basedes'];
$qty=$_POST['ct_qty'];
$extra_array = $_POST['extra'];
if ( $extra_array > "0" ) {
foreach ($extra_array as $one_extra) {
$source .= $one_extra.", "; }
$extra = substr($source, 0, -2);
} else {}
$result=mysql_query("INSERT INTO tbl_cart (pd_id, ct_qty, ct_session_id, ex_tra, ex_tra2, ex_price, ct_date) VALUES ('$id','$qty','$ssid','$extra','$name','$total', NOW())");
?>
Best regard to all
Sending two values in one variable is bound to get messy. I would just send the id and get the corresponding values from the database again in extradata.php.
If you really want to send multiple values, I would use fixed indices for the checkboxes (not extra[] but extra[SOME_NUMBER] and add a hidden field next to it (extra_pr[SOME_NUMBER]?) to pass the second value.
Note that you have to use fixed indices as unchecked checkboxes donĀ“t get posted but all hidden fields will get posted.

Categories