mysql update using for each loop from post array - php

sorry for my confusing question.
let me rephrase the details:
$query = "SELECT * FROM table";
sample data:
Item Name: Quantity:
Coke 2
Pepsi 3
Gatorade 4
<form action="exec.php" method="POST">
<input type="hidden" name="item_name" value="<?php for each loop goes here?/>"
<input type="hidden" name="quantity" value="<?php for each loop goes here?/>"
<input type="submit" name="submit"/>
</form>
Now, in my exec.php page.
if(isset($_POST['submit'])){
$item_code =$_POST['item_code'];
$quantity =$_POST['quantity'];
$test= explode('\n',$item_code);
$test2 = explode('\t',$quantity);
this part is where my problem is..
here is my update query:
foreach($item as $test){
$update = "UPDATE table SET quantity='$quantity' WHERE item_code='$item_code'"
}
}
as you can see, $quantity will be left out, since it would also need to be looped to match the $item_code.
or is there any better way to do this?
im quite new to php, so please pardon me if im doing it wrong the way..

I dont understand, do you have an issue reading the data from MySQL? do you have an issue updating the data to MySQL? In any case it seems that you are refering a SQL issue rather than an HTML or PHP, can you post your SQL script?

Related

Inserting an array to mysql using php

i have this two text fields that ask the user to put in two numbers that are limited to 49 numbers, so that i can have an array of number 1 to 50, or 151 to 200, or 27551 to 27600 any number but a series of 49 consecutive numbers, my problem is i dont know how to put them inside the database, i have no clue i have been searching for everything about inserting arrays but they dont work on my case,
This is my form
<form id="form3" name="form1" method="post" action="">
<p>From:
<input type="text" name="from" id="form_number" class="from" />
- To:
<input type="text" name="to" id="form_number" class="to" />
</p>
<p>Waybill Booklet:
<select name="waybill_booklet[]" id="form_list">
<?php
do {
?>
<option value="<?php echo $row_Booklet['id_waybill_booklet']?>"><?php echo $row_Booklet['booklet_no']?></option>
<?php
} while ($row_Booklet = mysql_fetch_assoc($Booklet));
$rows = mysql_num_rows($Booklet);
if($rows > 0) {
mysql_data_seek($Booklet, 0);
$row_Booklet = mysql_fetch_assoc($Booklet);
}
?>
</select>
</p>
<p>
<input type="hidden" name="status[]" value="4" />
<input type="submit" name="button" id="form_button" value="OK!" />
</p>
</form>
the 49 series of consecutive numbers will be inserted into the database with a foreign key what is chosen from the drop down menu, and a value of 4 that is in the hidden field, so basically there are 4 columns to my table 1 for primary key 1 for the series of numbers and 1 for the foreign key and the last will be the value of the numbers.
This is my php code to get the series of numbers
<?php
$booklet = $_POST['waybill_booklet'];
$status = $_POST['status'];
$from = $_POST['from'];
$to = $_POST['to'];
$number = range($from,$to);
$count = 0;
$myArray = range($from,$to);
while($count<=49){
if($count<49){
echo $myArray[$count]. ", ";
}else{
echo $myArray[$count];
}
$count++;
}
?>
i dont know how to insert the data's
$waybill = mysql_real_escape_string($_POST['waybill_booklet'][0]);
$status = mysql_real_escape_string($_POST['status'][0]);
foreach (range($from, $to) as $number) {
$sql = "INSERT INTO yourTable (id, waybill, status) VALUES($number, '$waybill', '$status')");
mysql_query($sql) or die(mysql_error());
}
You should also switch to PDO or mysqli, so you can use parametrized queries instead of substituting strings into the query. Then you don't need to escape the values like that.
Instead of storing this as an array (since you want to store this as bulk, I assume it will not involve any direct database level aggregation or computation), you can store it as a json string using the json_encode($myArray_series_of_numbers). This gives you the flexibility to store them as a string column and when you retrieve it back, you can use json_decode($model->series_of_numbers_column,true) to get it back as an array for easy computation back in PHP.
Hope this helps
Here is a tutorial on using mysql in php http://www.w3schools.com/php/php_mysql_insert.asp specifically the INSERT command. just build your data into variables instead of echo'ing it and then follow the guide to interact with a database
here is the auto increment tutorial to generate primary ids for each array element http://www.w3schools.com/sql/sql_autoincrement.asp
you can greatly increase the speed of the inserts and do it in one submit by building a multiple insert sql string.. and then using the insert guide above to run it.
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

PHP foreach Construct Confusion

I am having a hard time wrapping my head around the foreach construct. I have found numerous examples of course, but I never seem to be able to adapt them to my needs.
Please consider this working example I have:
I am collecting two dates in an HTML form:
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" name="FirstAGMDate" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" name="MinutesInspectedFromDate" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
On submit the values are being pushed to the mysql database with a PDO prepared statement:
if (isset($_POST['submit'])) {
$sql = "UPDATE jobsinglevalues SET Date = :FirstAGMDate WHERE FormId = 0;
UPDATE jobsinglevalues SET Date = :MinutesInspectedFromDate WHERE FormId = 1;";
$sth = $db->prepare($sql);
$sth->execute(array(':FirstAGMDate'=>($_POST['FirstAGMDate']), ':MinutesInspectedFromDate'=>($_POST['MinutesInspectedFromDate'])));
}
This works no problem, but it's not very clever when I need to repeat this for a dozen inputs. What I want to do is achieve this with only one line of sql; looping for each <input type="text" name="Value" />.
How can I place this into a foreach loop?
In my head it works like this:
On submit each input updates the value in the database based on FormId, which increments by 1 each loop starting at 0. FormId is not a primary key, it simply mirrors the order in which the form elements are displayed.
Update - working example
if (isset($_POST['submit'])) {
$FormId = 0;
foreach($_POST['Value'] as $avalue){
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId";
$sth = $db->prepare($sql);
$sth->execute(array(':Value'=>($avalue), ':FormId'=>($FormId)));
++$FormId;
}
}
This seems to logically work to me! Is the correct solution similar? Please let me know if I need to clarify anything.
Thankyou,
Sam
Let's start by making sure all our values are in an array after posted; if you don't care about the keys you can just use name="Values[]", but I'll use name="Value[FirstAGMDate]" etc so we know what key a value belongs to.
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" id="FirstAGMDate" name="Value[FirstAGMDate]" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" id="MinutesInspectedFromDate" name="Value[MinutesInspectedFromDate]" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
Now we can process the posted array of values. If we want to do something with the key, we can use foreach($_POST['Value'] as $akey => $avalue), if we are only interested in the values then foreach($_POST['Value'] as $avalue) suffices.
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId;";
$sth = $db->prepare($sql);
foreach($_POST['Value'] as $akey => $avalue) {
$sth->execute(array(':Value' => $avalue, ':FormId'=> $FormId ));
++$FormId;
}
[edit] As per edit-suggestion by #AravindKishore, creating the prepared statement is better done before the loop. Prepare once, enjoy forever.

Need Help In the PHP script and Mysql

Please help me with this:
I am creating a survey facility for the administrator. The administrator is asked for the number of questions in the survey. And based on this a row is created in the table containing survey info. Based on number of questions the same number of rows are created in the question table. This has 4 columns for the answers with each question id the corresponding number of rows are created for the same in the question table.
Now I am trying to give a form on UI controlled by a loop so that admin can enter questions and answers one by one and the question table is updated each time.
survey table (sur_id [auto increment column],sur_subject,Sur_frm_dt,sur_to_dt,sur_is_active)
question table ( sur_id, q_id [auto increment column] , q_txt,ans1,ans2,ans3,ans4)
The page asks for survey details: survey subject , dates, and no of ques
and a row is generated in survey table.The survey id created and number of question is passed to the create question page. $sid is survey id and $noq is number of questions.
The code is as follows. Please dont mind the novice logic and script:
$sid = intval ($_GET['ids']);
$noq = intval ($_GET['qn']);
for($noq !=0;$noq >=1;$noq--)
{
$q = "insert into sur_ques (sur_id) values ('$sid')";
$ex = mysql_query($q);
$rs = mysql_affected_rows();
if($rs ==1)
{
echo" Questions Rows Created Corresponding to Survey Subject";
}
?>
<form name="form1" method="post" action="<?php echo($PHP_SELF); ?>">
<table width="500" border="0" cellspacing="1" cellpadding="0">
<tr><br><b>Ques No-<?php echo"$noq";?></b></tr><br>
<tr><textarea name = "q" rows ="10" cols = "70" wrap = "hard" ></textarea></tr><br>
<tr><td><b>Ans 1:</b></td><td><input type="text" name="a1" size="37" /></td></tr>
<tr><td><b>Ans 2:</b></td><td><input type="text" name="a2" size="37" /></td></tr>
<tr><td><b>Ans 3:</b></td><td><input type="text" name="a3" size="37" /></td></tr>
<tr><td><b>Ans 4:</b></td><td><input type="text" name="a4" size="37" /></td></tr>
</table>
<input type = "submit" name="qa" Value = "Add Q&A" />
<input type ="reset" Value="Reset" />
</form>
<?
if ($_POST['qa'])
{
$id = mysql_insert_id();
$result = mysql_query("update ques set q_txt = '$q', ans1 = '$a1' ans2 = '$a2' ans4 = '$a4' ans4 = '$a4' where q_id = '$id'");
if($r = mysql_num_rows($result))
{
echo" Question and answers updated";
}
}
else
{
break;
}
}
?>
1 immediate problem I am able to see in your code is that you are using a comparison operator in your for loop where it should be an assignment operator $noq != 0 should be $noq = 0 or some other value – Trevor 0 secs ago
I think you are mixing up server side and client side. The code you posted is processed at the moment someone opens the page.
If you want the individual questions to be updated the moment the visitor presses the submit button, you will need to use ajax to send the information of that specific form to the server to be processed while the form remains the same / does not reload.
As it is now, every time you open your page, new rows are added based on the GET variables but no row is ever updated because you are never posting, I don´t see $PHP_SELF defined anywhere but I suppose you mean / want $_SERVER['PHP_SELF'].

HTML input value change

I have a PHP update page in which I am showing a text field containing a value from the database. It is like this, and it is working,
<input type="text" name="title" id="title" class="text_box" value="<?php echo $row['title']?>"/>
Now I need to put this updated value back in the database! I have used the code like this, but it's not updating:
$title=$_POST['title'];
$v_id = $_GET['v_id'];
$sql = mysql_query("update vehicles set title = '$title' where v_id = '$v_id'");
In detail... an input field is there. It's showing a value contained in $title (retrieved from the database) and that value is to be edited and updated.
From my side my code is working perfectly without showing any error, but the value that I give $title is giving the same one without any change.
Is there any other way to show a value in an input field without putting in a "value" tag?
Two things wants to happen in a single input field!
You'll need to post your form HTML as well.
Unless your form looks like the following, that code won't work
<form method='post' action='page.php?v_id=1'>
<input type="text" name="title" id="title" class="text_box" value="<?php echo $row['title']?>"/>
</form>
This is because you're using $_GET to get the id field and $_POST to get the value field
EDIT
Your edit has muddied the water a bit more. I'm going to assume all you want to do is show a title and let the user update the title
<?php
if ($_POST) {
$title = mysql_escape_string($_POST['title']);
$id = intval($_GET['v_id']);
$sql = "update vehicles set title = '$title' where v_id = '$id'";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
}
if (isset($_GET['v_id'])) {
$id = intval($_GET['v_id']);
$sql = 'SELECT title FROM vehicles WHERE v_id = ' . $id;
$rs = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
$row = mysql_fetch_assoc($rs);
$title = htmlspecialchars($row['title']);
}
?>
<form method='post' action='?v_id=<?php echo $id?>'>
<input type="text" name="title" id="title" class="text_box" value="<?php echo $title ?>"/>
<input type='submit' value='update'>
</form>
This should work for you. I haven't error tested obviously, but the idea is sound. You should also add any other input screening you feel necessary.
You are using both $_POST and $_GET.
Depending on the method element value of <form>, you need either $_POST or $_GET.
If this is not helping, please show more code so it is possible to determine which one you need.
Also, you can try to update the database without reading the form, to check if the updating itself is working correctly.
is there any other way to showing a value in a input field without putting a "value" tag?
Nope.
That's exactly what value attribute for.
What's wrong with it?
only thing to mention, it should be not <?php echo $row['title']?> but
<?php echo htmlspecialchars($row['title'])?>

How to work with checkboxes in relation to database?

Hi I am trying to build a form with checkboxes and upon submitting the form, I want to see which checkboxes were checked and update the database accordingly. How is this done? I've tried so many different code and none of them worked. The closest I've gotten was to update only the checked ones. I also need to update the database if they are unchecked as well like a toggle.
So far my code is like this for the form
<form action="" method="post">
<input type=checkbox" value="<?php echo member['id']; ?>" name="member[]" />
<input type="submit" name="update" value="Update" />
</form>
And for the PHP loop I have (excerpt)
foreach ((array)$_POST['test'] as $member) :
$sql = "UPDATE `sp_members` SET `allow_test` = '1' WHERE `id` = '$member'";
Since I think the loop only picks up the checkboxes that are checked, it doesn't pick up the ones that were orignally checked and now unchecked...
Any help appreciated!
Simply update everything instead of trying to figure out what changed - if you programmed it yourself, you would have to make your code a lot more complicated, and as the database is already optimized for speed, it's better to just stuff it in the DB and let it handle it.
You could use a ternary operator to set the correct value.
$sql = "UPDATE `sp_members` SET `allow_test` = '"
. ( $_REQUEST['checkbox'] ? 1 : 0 )
. "' WHERE `id` = '" . mysql_real_escape_string( $member ) . "'";
It checks $_REQUEST['checkbox'] for a non-null, non-zero string and if true, returns 1, if false, returns 0.
(($_post['member']) ?$allow_test = 1 : $allow_test = 0;
$sql = "UPDATE `sp_members` SET `allow_test` = $allow_test WHERE `id` = '$member'";
The reason why this hasn't been working (and won't in the already provided answers) is because checkboxes that are not checked won't exist in the $_POST/$_REQUEST arrays. The other side of that is if they do exist, they must be true.
When you're doing the check to see what the value is, you are causing an error because the key to the array doesn't exist.
Instead, you need to know the available checkboxes and then check if each isset() in the array.
Webform:
<form action="foo.php" method="post">
<input type="checkbox" value="<?php echo $value1; ?>" name="checkbox1" />
<input type="checkbox" value="<?php echo $value2; ?>" name="checkbox2" />
<input type="submit" name="update" value="Update" />
</form>
PHP:
$checkboxes = array(
'column1' => 'checkbox1',
'column2' => 'checkbox2',
);
foreach ($checkboxes as $column => $checkbox)
{
$value = (isset($_POST[$checkbox]) ? 1 : 0);
$sql = "UPDATE `table` SET `$column` = '$value' WHERE `id` = '$member'";
}
When confronted with this, I usually punt and rely on a transaction to update this stuff for me. As you've discovered, unchecked checkboxes won't get submitted with the form, so you'd have to do tedious comparisons to figure out what's changed each time and build up an appropriate update and/or delete query sequence.
Instead, I fire up a transaction, delete all the old checkbox values stored in the DB, and then insert the new ones submitted with this request. Unless you've got the checkboxes acting as foreign keys and/or triggers set on them at the DB level, this is a relatively lightweight option and saves you the trouble of having to compare the old and new lists for changes.

Categories