Update mysql database fields with array php - php

I'm trying to achieve a multiple update in one submit. I have a table with a number of rows and want to be able to update one field in each row just by tabbing to the next insert box.
My code is thus:-
//start a table
echo '
';
//start header of table
echo '<tr>
<td width="60" align="center"><strong>Lab Item ID</strong></td>
<td width="60" align="center"><strong>Test Suite Name</strong></td>
<td width="60" align="center"><strong>Test Name</strong></td>
<td width="50" align="center"><strong>Result</strong></td>
</tr>';
//loop through all results
while ($row=mysql_fetch_object($sql)) {
//print out table contents and add id into an array and email into an array
echo '<tr>
<td align="center"><input name="id[]" value='.$row->lab_item_id.' readonly> </td>
<td align="center">'.$row->test_suite_name.'</td>
<td align="center">'.$row->test_name.'</td>
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
</tr>';
}
//submit the form
echo'<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>';
//if form has been pressed proccess it
if($_POST["Submit"])
{
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
foreach( $_POST['id'] as $id ) {
$tresult = trim($_POST['test_result']);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
var_dump($tresult);
//redirect user
$_SESSION['success'] = 'Updated';
//header("location:index.php");
}
?>
When I print the $_POST arrays, everything is populating fine, however the variable is Null. I know I can't do a foreach on multiple arrays (at least I don't think I can) so is there some other trick I'm missing please? I can't be far away as the $_Post print has the right data in it.
Incidentally, the whole thing is generated by a query, so I never know how many records I'll have to update.
I've been looking at this (and other) forums, but can't seem to get a solution. I thought I understood arrays, but now I'm beginning to wonder!
edit - it's the $tresult variable that isn't working.
Many thanks,
Jason
Edit Thursday 21st Feb (05:41 UK time)
Thanks for your input everybody. I've solved this one now, and your collective advice helped. The code that finally cracked it is:-
//get data from form
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach ($id1 as $key => $value){
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id=$value ";
//execute query
Working through which variables etc were populated and what they were populated with was the key. Back to first principles, isn't it?
Cheers all.
J

Actually, you might get it done by doing a simpler (basic) form of for loop:
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
$numberOfData = count($_POST['id']);
for($index = 0; $index < $numberOfData; $index++)
{
$id = $_POST['id'][$index];
$tresult = trim($_POST['test_result'][$index]);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
I hope this helps.
Cheers

change the query like this :
$query = "UPDATE tbl_lab_item SET test_result=$tresult WHERE lab_item_id = $id";
By adding single quotes ' ' you tell it to read is as a String and not to take the value of the var.
Edit
Replace your foreach loop with the following and let me know :
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach( $id1 as $key => $value ) {
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id = '$key' ";
}

Problem is that you're telling PHP to build your input fields as arrays, but then treat it as a string later:
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
^^--- array
$tresult = trim($_POST['test_result']);
^^^^^^^^^^^^^^^^^^^^^--- no array key, so you're assigning the entire array
$query = "UPDATE tbl_lab_item SET test_result='$tresult'
^^^^^^^^^^--- array in string context
trim() expects a string, but you pass in an array, so you get back a PHP NULL and a warning. That null then gets stuffed into your SQL statement, and there's your problem.

Related

How to get user input to insert multiple records into database from table created with a for loop?

I have created a form that requires the user to input information on all fields and then submit the form. My goal is to get the user input and insert it into new records on the database. My current challenges are that since I used a for loop in PHP to create the table/form:
I can not access the input from $_POST
Not sure how to go about differentiating all of the rows and their inputs from each other (since I used a loop to create them). I was thinking an array...
Please see a screenshot of the form I am working with.
Below is what I have for my submit button.
if (isset($_POST['submit'])) {
$date = date('m\/d\/Y');
$ordnum = $_POST['cpOrderNumber'];
$ponum = $_POST['cpPoNumber'] . $_POST['cpPoNumberF'];
$palnum = $_POST['palnum'];
$casecount = $_POST['casecount'];
$cpsflot = $_POST['cpsflot'];
$sscc = $_POST['sscc'];
if(!empty($_POST['cpOrderNumber']) || !empty($_POST['cpPoNumber'])) {
require_once('mydatabase.php');
$query = "INSERT INTO ASN (date, ordnum, ponum, palnum, casecount, cpsflot, sscc )
VALUES ('$date', '$ordnum', '$ponum', '$palnum', '$casecount', '$cpsflot', '$sscc')";
$insert = sqlsrv_query($dbc, $query);
if( $insert === false ) {
die('Could not connect to database');
}
}
else {
die('Please enter the appropriate information');
}
sqlsrv_close($dbc);
}
And here is where I am having difficulty. I can get $date, $ordnum, and $ponum to insert into the database however $palnum will not. As you can see from what I've commented out I have tried to use an array.
<?php
for ($x = 1; $x < 25; $x++) {
echo
'<tr id="' .$x. '">
<td style="font-size: 160%" name="palnum" id="pallet">' .$x. '</td>
<td id="caseCount"><input type="number" name="casecount" id="inputText_Small" maxlength="2"/></td>
<td id="hilltopLot"><input type="text" name="cpsflot" id="inputText_Order" value="" maxlength="10"/></td>
<td id="sscc"><input type="number" name="sscc" id="inputText_Medd" value="" maxlength="4"/></td>
</tr>';
$palnum[$x] = $x;
//$palnum[$x] = 'palnum'.$x;
//$palnum = $palnumx.$x;
//$palnum1 = $palnum[1];
}
//echo count($palnumx);
//echo $palnum[1];
?>
i think you are looking for this. not 100% though. Basically, you can name an input wityh brackets to make it behave like an array in the post.
<input name="recurringName[]" value="moo" />
<input name="recurringName[]" value="moo2" />
if you do that, in the post you can access data this way
$_POST['recurringName'][0] == 'moo'
$_POST['recurringName'][1] == 'moo2'
i hope this helps! let me know if i did not understand you clearly

Display data from database without using form tags?

I have a search form where the user will insert his/her CODE and NAME & TELEPHONE of that CODE will then be shown inside a table which is working fine (Thanks to stack overflow).
<form action="list25.php" method="post">
Search By code:<input type="text" name="code"><br><br>
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="product-table">
<tr>
<th class="table-header-repeat line-left">Name</th>
<th class="table-header-repeat line-left">telephone</th>
</tr>
<?php
if (isset($_POST['search'])) {
$code = $_POST['code'];
$connect = mysqli_connect("localhost", "root", "", "sahmiye");
$query = "select * from balance where code = $code ";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['telephone']; ?></td>
</tr>
<?php
}
} else {
echo "Undifined ID";
$name = "";
$telephone = "";
}
mysqli_free_result($result);
mysqli_close($connect);
} else {
$name = "";
$telephone = "";
}
?>
</table>
<br><br>
<input type="submit" name="search" value="Find">
</form>
BUT i have a second completely different form as well and when the user writes his/her CODE in this second form i needed the NAME & TELEPHONE of that CODE to then be shown inside textboxes and the user will then fill up the rest of the form and then submit it so it can be saved into the database.
The problem being i know i cant have a form within a form but is there a way for me to run my first search form shown above with out using a form so that i can have the same function inside my second form whereby after CODE is given , it will fill up the textboxes with the NAME & TELEPHONE of that CODE ?
Display data from database without using form tags?
You need to use a GET array and use the parameter in the href.
I.e. and checking if it is set and not empty and equal to "something":
Name
Then use the GET array with the parameter.
if(!empty($_GET['var']) && $_GET['var'] == 'John'){
// do your thing to search for the string "John", as an example.
// ATT'N: John and john in the database are two different animals.
}
Use the same format for the other href.
Sidenote: Remove the href's from inside the <form></form> tags, as it may cause some havoc.
You will also need to quote the variable in the query when it is a string.
I.e.:
$query = "select * from balance where code = '$code' ";
...if $code is a string.
However, it will throw an error if the query contains characters that MySQL will complain about such as John's Bar & Grill, therefore a prepared statement/escaping the value will be required and will help prevent a possible SQL injection at the same time.
Reference:
https://en.wikipedia.org/wiki/Prepared_statement
Edit:
Going over the question again and TBH is a bit complicated, using sessions would be something to use in order to keep the values.
http://php.net/manual/en/session.examples.basic.php
...then checking if any of the session array(s) is/are set and not empty.
N.B.: session_start(); must reside inside all pages using sessions in order for this to work. Inputs can also contain sessions-related code and "if set/not empty". Otherwise, you will get errors about them being undefined.

Display mysql database query result on second pages

I have a mysql database with some data.here i display data on one page Now I want to display this data on next page please give me suggestion how I can do this .........
I need some modifications in this code like
I want to display table this table on next page(book.php page that is populated with the database)......
Second thing that I need to know is it possible to store the value of calendar in session variable (is it ???than how?)
<?php
if(isset($_POST['search'])){
$from = $_POST['from'];
$to = $_POST['to'];
$query = mysql_query("select * from schedule where Destinatio='$from' AND Arriva ='$to'");
$c = mysql_num_rows($query);
if (!$query) {
die('Invalid query: ' . mysql_error());
}
if($c>0)
{
?>
<table>
<tr align="center"><td width="120"><span class="style23">Destination</span> </td>
<td width="57"><span class="style23">Arrival</span></td>
<td width="121"><span class="style23">Departure time</span></td>
<td width="98"><span class="style23">Arrival Time</span></td>
<td width="44"><span class="style23">Fare</span></td>
<td width="85"><span class="style23">Bus_type</span></td>
<td width="84"><span class="style23">Total_Seats</span></td>
<td width="81"><span class="style23">Available</span></td>
<td width="52"> </td>
</tr>
</section>
<?php
while($r1 = mysql_fetch_array($query))
{
$schedule= $r1['id'];
$Destinatio = $r1['Destinatio'];
$Arriva= $r1['Arriva'];
$Departure_time = $r1['Departure_time'];
$Arrival_time = $r1['Arrival_time'];
$Fare = $r1['Fare'];
$Bus_type = $r1['Bus_type'];
$Total_Seats = $r1['Total_Seats'];
$bust = $schedule.'schedule';
$query1 = mysql_query("SELECT * from $bust where status='Available'");
echo $query1;
if (!$query1) {
die('Invalid query: ' . mysql_error());
}
$c = mysql_num_rows($query1);
?>
<tr align="center"><td><?php echo $Destinatio;?></td><td><?php echo $Arriva;?></td><td><?php echo $Departure_time;?></td><td><?php echo $Arrival_time;?></td><td><?php echo $Fare;?></td><td nowrap="nowrap"><?php echo $Bus_type;?></td><td><?php echo $c;?></td><td>Book
</td>
</tr></table>
</form>
There are three main ways to pass variables:
Using a form button using $_POST variables to pass the content
(generally best when you also have user input).
Using an HTML anchor link to pass the variables through $_GET
Using a SESSION variable that can be accessed on all pages on your site.
Using SESSION variables is the more secure way, but it the data isn't secret use the $_GET method.
To store something in a SESSION variable you need to use:
start_session();
$_SESSION['varname'] = value;
on the following page, you can read your SESSION variable just by using it's name. For example:
start_session();
echo $_SESSION['varname'];

php submit only giving last value from array that populates form

Struggling with a one page form that i want to first populate a form from a mysql query, then enable a user to update some of the values in each of several table rows from text input fields in the form.
The code's intent is to update the field by referencing the row ID.
But for some reason I'm only able to update the last row in the form (the last row from the array). I've included some troubleshooting code to see what the ID variable is and it always comes up as the last iteration of the array. I think I'm either overwriting the ID variable in the while loop or the for loop.
I have tried moving the POST/update to a 2nd file but get the same results. Any thoughts/suggestions would be greatly appreciated
Here is the code minus the db connection:
$saveClicked = $_POST["saveClicked"];
{ // SAVE button was clicked
if (isset($saveClicked)) {
unset($saveClicked);
$ID = $_POST["ID"];
$win = $_POST["Winner"];
$winScr = $_POST["WinnerScore"];
$losScr = $_POST["LoserScore"];
$tschedule_SQLupdate = "UPDATE tschedule SET ";
$tschedule_SQLupdate .= "Winner = '".$win."', ";
$tschedule_SQLupdate .= "WinnerScore = '".$winScr."', ";
$tschedule_SQLupdate .= "LoserScore = '".$losScr."' ";
$tschedule_SQLupdate .= "WHERE ID = '".$ID."' ";
if (mysql_query($tschedule_SQLupdate)) {
echo '<p> the number of mysql affected rows is '.mysql_affected_rows().'</p>';
echo 'this is the value for post id '.$ID;
} else {
echo '<span style="color:red; ">FAILED to update the game.</span><br /><br />';
echo mysql_error();
}
}
// END: SAVE button was clicked ie. if (isset($saveClicked))
}
{ // Get the details of all associated schedule records
// and store in array: gameArray with key >$indx
$indx = 0;
$tschedule_SQLselect = "SELECT * ";
$tschedule_SQLselect .= "FROM ";
$tschedule_SQLselect .= "tschedule ";
$tschedule_SQLselect .= "WHERE week = 1 ";
$tschedule_SQLselect_Query = mysql_query($tschedule_SQLselect);
while ($row = mysql_fetch_array($tschedule_SQLselect_Query, MYSQL_ASSOC)) {
$gameArray[$indx]['ID'] = $row['ID'];
$gameArray[$indx]['Date'] = $row['Date'];
$gameArray[$indx]['week'] = $row['week'];
$gameArray[$indx]['Favorite'] = $row['Favorite'];
$gameArray[$indx]['Line'] = $row['Line'];
$gameArray[$indx]['Underdog'] = $row['Underdog'];
$gameArray[$indx]['OU'] = $row['OU'];
$gameArray[$indx]['Winner'] = $row['Winner'];
$gameArray[$indx]['WinnerScore'] = $row['WinnerScore'];
$gameArray[$indx]['LoserScore'] = $row['LoserScore'];
$indx++;
}
$numGames = sizeof($gameArray);
mysql_free_result($tschedule_SQLselect_Query);
}
{ // Output
echo '<form name ="postGame" action="'.$thisScriptName.'" method="post">';
echo '<table border="1">';
echo '<tr>
<th>ID</th>
<th class="date">Date</th>
<th class="num">Week</th>
<th>Favorite</th>
<th class="num">Line</th>
<th>Underdog</th>
<th class="num">OU</th>
<th>Winner</th>
<th>WScore</th>
<th>LScore</th>
<th>Save</th>
</tr> ';
for ($indx = 0; $indx < $numGames; $indx++) {
$thisID = $gameArray[$indx]['ID'];
$saveLink = '<input type = "submit" value = "Save" />';
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
$fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';
echo $fld_ID;
echo $fld_saveClicked;
echo '<tr>
<td>'.$gameArray[$indx]['ID'].'</td>
<td>'.$gameArray[$indx]['Date'].'</td>
<td>'.$gameArray[$indx]['week'].'</td>
<td>'.$gameArray[$indx]['Favorite'].'</td>
<td>'.$gameArray[$indx]['Line'].'</td>
<td>'.$gameArray[$indx]['Underdog'].'</td>
<td>'.$gameArray[$indx]['OU'].'</td>
<td><input type="text" size =5 name="Winner">'.$gameArray[$indx]['Winner'].'</td>
<td><input type="number" size=5 name="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
<td><input type="number" size=5 name="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
<td>'.$saveLink.'</td>
</tr> ';
}
echo '</table>';
echo '</form>';
echo' View Schedule';
}
You're using the same names for each field in each row, so when you post the form, only the last is accessible. Use array notation for the fields like this:
<input type="text" size =5 name="Winner[]">
^^
This will give you an array for $_POST['Winner'] instead of a single value. Do the same for the other <input> elements.
Also, the code that processes the form after it's submitted only processes one value. You'll need to modify that to loop through these arrays.
Warnings:
don't use mysql_*() for new code - it's depracated. Switch to mysqli_*() or PDO now.
Your code is susceptible to SQL injection. Escape your input variables with mysql_real_escape_string() (or the mysqli equivalent) or better, switch to prepared statements.
After some more research I think I understand the two answers already shared much better. However I have chosen a different path and have resolved my issue -I wrapped the form tags directly around each row:
echo '<form name ="postGame'.$indx.'" action="'.$thisScriptName.'" method="POST">';
$fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';
echo $fld_saveClicked;
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
echo $fld_ID;
echo '<tr>
<td>'.$gameArray[$indx]['ID'].'</td>
<td>'.$gameArray[$indx]['Date'].'</td>
<td>'.$gameArray[$indx]['week'].'</td>
<td>'.$gameArray[$indx]['Favorite'].'</td>
<td>'.$gameArray[$indx]['Line'].'</td>
<td>'.$gameArray[$indx]['Underdog'].'</td>
<td>'.$gameArray[$indx]['OU'].'</td>
<td><input type="text" size=5 name="Winner" id="Winner">'.$gameArray[$indx]['Winner'].'</td>
<td><input type="number" size=5 name="WinnerScore" id="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
<td><input type="number" size=5 name="LoserScore" id="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
<td><button type="submit" />Save</button></td>
</tr></form>';
}
One of the key trouble shooting steps was to use var_dump to validate that the $_POST actually contained data. I understand there are several ways this could be done including the responses shared by Hobo and Syed, as well as using javascript, but was really glad I could accomplish my goal with just php.
Your For Loop is storing the last value of the array in your form.
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
Store the ID value as an array in HTML form and when a form is posted get all the ID values and update using your same mysql update query.
Your winner and loser score are also returning the last array values.

Inserting specific values into a DB, and displaying it on a table?

I'm trying to insert specific values(knife, and blanket) into a Database, but's not inserting into the DB/table at all. Also, I want to display the inserted values in a table below, and that is not working as well. It is dependant on the insert for it to show on the table. I am sure, because I inserted a value through phpmyAdmin, and it displayed on the table. Please, I need to fix the insert aspect.
The Insert Code/Error Handler
<?php
if (isset($_POST['Collect'])) {
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}else {
// this makes sure that all the uses that sign up have their own names
$sql = "SELECT id FROM objects WHERE object='".mysql_real_escape_string($_POST['Object'])."'";
$query = mysql_query($sql) or die(mysql_error());
$m_count = mysql_num_rows($query);
if($m_count >= "1"){
echo 'This object has already been taken.!';
} else{
$sql="INSERT INTO objects (object)
VALUES
('$_POST[Object]')";
echo "".$_POST['object']." ADDED";
}
}
}
?>
TABLE PLUS EXTRA PHP CODE
<p>
<form method="post">
</form>
Pick Object: <input name="Object" type="text" />
<input class="auto-style1" name="Collect" type="submit" value="Collect" />
</p>
<table width="50%" border="2" cellspacing="1" cellpadding="0">
<tr align="center">
<td colspan="3">Player's Object</td>
</tr>
<tr align="center">
<td>ID</td>
<td>Object</td>
</tr>
<?
$result = mysql_query("SELECT * FROM objects") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table?>
<tr>
<td><label for="<?php echo $row['id']; ?>"><?php
$name2=$row['id'];
echo "$name2"; ?>
</label></td>
<td><? echo $row['object'] ?></td>
</tr>
<?php }// while loop ?>
</table>
</body>
if(($_POST['Object'])!= knife || ($_POST['Object'])!= blanket)
THese value knife and blanket are string. So you may need to use quotes around them to define them as string, or php won't understand ;)
If the primary key of Objects is id and it is set to auto-increment
$sql = "INSERT INTO objects SET id = '', object = '".$_POST['Object']."'";
try
$sql= "INSERT INTO objects(object) VALUES ('".$_POST['Object'].")';
and you should probably put an escape in there too
You insert query is nor correct.
$sql = "INSERT INTO objects (id, object) values('','".$_POST['Object']."') ";
and this code
if(($_POST['Object'])!= "knife" || ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
will always be executed value of object is knife or blanket, because a variable can have one value. You must use
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
Your SQL syntax is wrong. You should change the:
INSERT INTO objects SET id = '', object = '".$_POST['Object']."'
to
INSERT INTO objects ( id, object ) VALUES ('', '".$_POST['Object']."'
If you want your inserts to also replace any value that might be there use REPLACE as opposed to INSERT.

Categories