update query value in foreach statement with looping textbox values PHP - php

I want to update my database inside the foreach statement but it gives me the same values that I insert on to the last value that I input.
Let's say I have a looping textbox at the previous page.
$i = 0;
while($row_recordset = mysql_fetch_array($query_run))
{
echo "<tr>";
<td'><input type='text' name='atten_ave".$i."''></td>
echo "</tr>";
$i++;
}
Now this code will get each value of the textbox and should be update the database from the previous page.
foreach($_POST as $textbox => $values) {
$sessionbatch = getbatchno('BATCHNO');
$query_update = "UPDATE `grades`
SET
`ATTEN_SUM` = '$values'
WHERE
`BATCHNO` = '$sessionbatch'
";
if(mysql_query($query_update)){
echo 'SUCCESS';
} else{
die(mysql_error());
}
when I check my ATTEN_SUM COLUMN the values are the SAME base on the last input on the textbox.

First off, do not loop through every value in $_POST. Give your textboxes an idenitcal name that has [] appended to it, like name="atten_ave[]". This will create an array for them within $_POST, then you can loop through them all safely with:
foreach($_POST["atten_ave"] as $textbox => $values) { ....
Now whenever getbatchno('BATCHNO'); returns a value it has already returned within the life of that loop, it will overwrite the update it previously did with that similar value. So if it is returning the same value in every iteration, your query will just keep overwriting itself.

Related

Inserting and replacing values to multidimensional array when it exists or not

I am trying to replace the initial values of a multidimensional session array everytime the user submits a form. It must not have a duplicate in the array. I'm having trouble inserting user input value per form submission to specific row and column of the session array.
All codes are in one php file.
<?php
session_start();
$_SESSION['numbers'] = array(
array(0,0,0,0,0), //row1
array(0,0,0,0,0), //row2
array(0,0,0,0,0), //row3
array(0,0,0,0,0), //row4
array(0,0,0,0,0) //row5
);
?>
<?php
if (isset($_POST["num"]) && !empty($_POST["num"])){
$userInput = $_POST["num"];
if(!in_array($userInput, $_SESSION['numbers'])){
echo "<script>alert('does not exist')</script>";
//$_SESSION['numbers'] [] = $userInput;
}else{
echo "<script>alert('exists')</script>";
//don't add to array
}
}
echo "<table border = 1>";
for($row = 0; $row < sizeof($_SESSION['numbers']); $row++){
echo "<tr>";
for($col = 0; $col < sizeof($_SESSION['numbers']); $col++){
echo "<td>".$_SESSION['numbers'][$row][$col]."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
However, if I do
$_SESSION['numbers'] = $userInput;
it replaces the entire multidimensional array with just 1 value instead of inserting it to the specific row and column of the nested array.
If input is, lets say 1 and the user hits the submit button, the output I get in table for each row and column is just 1
I can't properly insert it in a specific row<tr> and column<td>.
It's easy if it's one dimensional array but I don't know how to do it in multidimensional arrays nested. Please help.
Thank you.
Each of the rows has numeric index in your array; e.g., row 1 is index 0, row 2 is index 1, etc. What you need to do is have the form submitted with a specific row number, that way you'll know where it needs to be inserted. With that in place, the following will do the trick for you.
Then, you can iterate the rows and add it in if it doesn't already exist.
foreach($_SESSION['numbers'] as $_row_index => &$_row) {
if($_row_index == (int)$_POST['row_index']) {
if (!in_array((int)$_POST['num'], $_row, true)) {
$_row[] = (int)$_POST['num']; // Add the num.
}
}
}

PDO update query pushes submit input value on all columns

I have a PDO update query gets the $_POST (or any other key-value array) and writes up the UPDATE query in respect to the inputs given.
I have an exclude array that I can specify keys to not include in the SQL query, such as the submit key and value of the form (action_update_survey, in this case.).
I create the SQL query by iterating through the array via foreach to firstly create the query and insert the parameter placeholders and secondly to bind the parameters to the parameter placeholder within the query.
Here is my code:
function save_survey($post){
global $pdo;
$exclude_names = array('action_update_survey');
$wp_userid = get_current_user_id();
$update_survey_query = "UPDATE kwc_surveysessions SET ";
foreach($post as $key=>$value){
if(!in_array($key, $exclude_names)) $update_survey_query .= $key." = :".$key.", ";
}
$update_survey_query = rtrim($update_survey_query, ", ")." WHERE wp_userid=:wp_userid";
$update_survey = $pdo->prepare($update_survey_query);
print_r($update_survey_query);
foreach($post as $key=>$value){
if(!in_array($key, $exclude_names)){
$update_survey->bindParam($key, $value);
}
}
$update_survey->bindParam("wp_userid", $wp_userid);
$update_survey->execute();
}
After executing my function following a post, all text columns in my database are set to the value 'Save', which is the value of the submit input, of name *action_update_survey*, which is strange, because it should be excluded from both foreach loops, which assign the keys and values.
Printing the PDO query before executing shows that there's been no setting of the excluded input anywhere in my query:
UPDATE kwc_surveysessions SET s1q1 = :s1q1, s1q2 = :s1q2, s1q7 = :s1q7, s1q8 = :s1q8, s1q9 = :s1q9, s1q10 = :s1q10, s1q11 = :s1q11, s2q6 = :s2q6, s3q7 = :s3q7 WHERE wp_userid=:wp_userid
Any idea what would be causing the submit input to push its value into all my fields?
The most probable cause is that bindParam() passes values by refference.
Try using an array like this:
arr = array();
foreach($post as $key=>$value){
if(!in_array($key, $exclude_names)){
arr[$key] = $value;
}
}
$update_survey->execute($arr);
and use "arr" to execute the query.

PHP loop make variable available in the next loop

I have a loop like this (just a sample, many vars are missing):
foreach($inserts as $insert) {
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIDs[] = array($tables[$tbl]['owner'] => $insert_update);
}
Now as you see $insertedIDs[] is getting in the array all the new inserted IDs.
The problem is that on the next $inserts loop I'll need that $insertedIDs[] to be available for other variables of the loop, that will need to get the last inserted ID.
The problem is that on the next loop this variable is not recognized and it returns errors.
How can I make $insertedIDs[] available on each next loop after the first loop?
I tried declaring $insertedIDs[] as global just after the foreach but no luck.
Try this may be it'll help you:
$insertedIDs=Array();
foreach($inserts as $insert) {
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIDs[] = array($tables[$tbl]['owner'] => $insert_update);
}
Now you are able to access $insertedIDs
$insertedIDs = array();
foreach($inserts as $insert) {
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIDs[ $tables[$tbl]['owner'] ] = $insert_update;
}
print_r($insertedIDs);
Pretty easy actually... Try not to over-think it.
//create an empty array
var $insertedIds = array();
//now loop and add to the array
foreach( $inserts as $insert )
{
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIds[][$tables[$tbl]['owner']] = $insert_update;
//or if you want the owners to be keys in the first level of the array...
//$insertedIds[$tables[$tbl]['owner']] = $insert_update;
}
//output the contents of the array
echo '<pre>' . print_r($insertedIds, true) . '</pre>';

How to get values of duplicate parameters from URL in php?

How can i use $_GET to return the values from the URL bar?
Checkboxes are ticked in a form, this is the part that concerns the $_GET variable (I have cut some of it out):
<form action= "<?php echo $_SERVER['PHP_SELF'];?>" method="get">
echo "<table border='1'>";
// Start of the table
while($row = mysql_fetch_array($result))
// The while loop enables each of the stock codes to have
// a separate page within the table, based on the stock code.
{
echo "<tr>";
// Starts the table row.
echo "<td>Stock Code: " . $row['stock_code'] . "
</br> Stock Name: " . $row['stock_name'] . "</td>";
$num = 0;
echo "<td><input type='checkbox' id='select" . $num . "' name='select" . $num . "' value=".$row['stock_code']."></input></td>";
$num = $num+1; }
When I click submit, the stock codes go into the URL bar like this:
submitcheckbox.php?select72=DFC107&select74=DFC120&select79=DFC123
I need it to loop through the $_GET values, check which boxes are set and then update the database if they have been checked with a marker.
I am looking at using a while loop, using isset to check whether the checkboxes have been selected:
$numrows = count($row);
$i=0;
while ($i<=$numrows){
if (isset ($_GET['select.i']));
echo $_GET['select.i'];
$i++;
$save = $_GET['select.i'];
echo $save;
Haven't been very successful so far... wondering if there may be a better to way to do it like using arrays?
At first - not while not even for but foreach. Then you just do this:
foreach($_GET as $key=>$value) {
if(substr($key, 0, 6)=="select") {//Just check the begining of the name - fur sure, can be ommited
echo "Checkbox #".substr($key, 6)." selected!<br>";
}
}
If you had used while properly (and you didn't) you would iterate through many undefined values - you seem to have over 70 checkboxes! Do you want the program to check them all? You can just check the sent values.
Foreach gives you an associative array key and value for each iteration. And it gives you just values for foreach($array as $value) syntax.
Fix of syntax errors in the question code:
In the second code, you have very obvious begginer syntax errors. I will point out a few, so you can avoid them in the future:
$numrows = count($row);
$i=0;
while ($i<=$numrows){
if (isset ($_GET['select'.$i])); { //This must have brackets too, if it involves multiple commands!
echo $_GET["select$i"]; //This is how we concat strings in php
$save = $_GET['select'.$i]; //Or this
echo $save;
}
$i++; //Iterate at the end
} //Mising ending bracket!!
If I understand what you're attempting to do, while you're looping through the number of potential 'selects' (i.e., $_GET['select'.$i]) you could add the $i's to an array with something like this:
if (isset($_GET['select'.$i])) {
$my_array[] = $i;
}
Then you can loop through $my_array and tick off the checkboxes that associate with $i with something like:
foreach($my_array as $checked) {
// do your checkbox stuff
}
Here is an idea on how to make it work
foreach($_GET as $key=>$value) {
// check if the key is something like select74
// by finding first occurance of the string on
// the key
$pos = strpos($key, 'select');
// If string exist
if ($pos !== false) {
// Get the save and save it
echo $value;
$save = $value;
echo $save;
}
}
Note: if instead of using a $_GET you can use a $_POST for your form you just need to change the field name from select74 to select[74] that way the $_POST will have an array call select where the key is 74 and the value DFC120
I'm not sure count($row) is what you think it is, can you post the whole page code with that part included, in the order which it is written?
Also it is $_GET['select'.$i] not $_GET['select.i'] :
$numrows = count($row); //make sure where this comes from and that it actually contains the number of rows
for($i=0;$i<$numrows;$i++){
if(isset($_GET['select'.$i])){
echo $i.' isset : '.$_GET['select'.$i].'<br/>';
//do whatever is required to save
}
}
You can use array_values($_GET) to get just the values selected from $_GET in a new array. You can then use a foreach loop to iterate these values.
foreach(array_values($_GET) as $selected) {
// Do things with $selected
}

PHP and MYSQL "while" prints only one value

Hey all i have a mind bug with this wile loop , i am a bit of a noob
$sql_advanced_bio = mysql_query("SELECT * FROM bio_details WHERE mem_id='$id'");
while($row = mysql_fetch_assoc($sql_advanced_bio)){
$bio_time_family = $row["bio_time_family"];
}
So this is the php now in my HTML i have this
*php echo $bio_time_family *
Why dose it echo only one value ?
SIMPLE ANSWER
so i tried somethingh easier like this $bio_fun_family .= $row["bio_fun_family"].",";
and then this
$bio_fun_family = substr($bio_fun_family,0,-1);
I added the .next to the =
It appends the values
You need to store the values in an array, otherwise you're just overwriting one variable each time, so you'll just end up with the last value.
You also need to use a loop to echo out each value in the array.
$sql_advanced_bio = mysql_query("SELECT * FROM bio_details WHERE mem_id='$id'");
$bio_time_family = array();
while($row = mysql_fetch_assoc($sql_advanced_bio)) {
$bio_time_family[] = $row["bio_time_family"];
}
And then for the output;
foreach($bio_time_family as $b) {
echo($b . '<br />');
}
With each iteration of the while loop, you're assigning to $bio_time_family the newly extracted value. If you'd like to make an array of the, instead, use $bio_time_family[] = $row["bio_time_family"];
Because every time you run through the loop you're re-assigning $bio_time_family to the next row's value. Try calling echo directly in your loop or add the row to an array, then loop through that and output the rows

Categories