How to update through foreach loop - php

I want to update data of form fields in database through foreach loop. I have two columns in test_table ID and Input. I have fetched data through while loop and also have printed the value. Now I want to update fetched value. Please give some guidance for this.
Here is my code,
$sql = "select * from test_table";
if($result = mysqli_query($conn, $sql))
{
while($row = mysqli_fetch_array($result))
{
$inputResult[]=$row;
}
} <form method="POST"> <input type="text" value=<?php
echo $inputResult[0]['Input']; ?> id="$inputResult[0]['ID']"> <input
type="submit" name="submit"> </form> <?php
if (isset($_POST['submit'])
{
$input = $inputResult[];
foreach($input as $inputs => $value)
{
$Sql = "update test_table set Input='$value' where = '$inputs'";
mysqli_query($conn, $sql);
}
} ?>
Please let me know what errors have in my code ? Thanks in advance.

Next solution is very specific to your problem. The input text is the first element in your form, so, in the PHP code, we can get the input's ID and the VALUE by accessing the first item in the array $_POST (changes are pointed by arrows ◄■■■):
<?php
$sql = "select * from test_table";
if($result = mysqli_query($conn, $sql)) {
while($row = mysqli_fetch_array($result)) {
$inputResult[]=$row;
}
}
?>
<form method="POST">
<input type="text" value="<?php echo $inputResult[0]['Input'];?>"
name="<?php echo $inputResult[0]['ID'];?>" /> ◄■■■ NAME, NOT ID.
<input type="submit" name="submit" />
</form>
<?php
if ( isset($_POST['submit']) ) {
$value = reset( $_POST ); // ◄■■■ FIRST VALUE IN $_POST (['input']).
$id = key( $_POST ); // ◄■■■ FIRST KEY IN $_POST (['ID']).
$Sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
mysqli_query($conn, $sql);
}
?>
I replaced the attribute id= by name= in the input text, because PHP needs names, not ids.
After we get the first value and the first key, we can insert them into the sql string.
Edit :
Fixed the missing tags (oops!). I think I found the error, it's so little that it's hard to see : pay attention to next line:
▼
$Sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
Do you see the variable on the left : $Sql (the first letter is uppercased). Now let's see the next line:
▼
mysqli_query($conn, $sql);
The same variable is not uppercased, once you fix that, everything works :
▼
$sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
mysqli_query($conn, $sql);
▲

Related

How to use a value i get from a form in another php

<?php
if(isset($_POST['edit_button'])){
$ID=$_POST['edit_button'];
$query = "SELECT PNAME , GENDER, AGE, ADDRESS , PHONENUMBER
FROM PATIENT LEFT OUTER JOIN PHONENUMBER
ON PID=EPID AND '$ID'=PID";
$stid = oci_parse($conn, $query);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$patient_name= $row['PNAME'];
$patient_gender= $row['GENDER'];
$patient_address= $row['ADDRESS'];
$patient_age= $row['AGE'];
$patient_phone= $row['PHONENUMBER'];
}
?>
<?php
if(isset($_POST['Edit_Patient'])){
$new_pname=$_POST['pName'];
$new_pGender=$_POST['pGender'];
$new_pAge=$_POST['pAge'];
$new_pAddress=$_POST['pAddress'];
$new_phone=$_POST['phone'];
$update_query=" UPDATE PATIENT
SET PNAME= '$new_pname', GENDER= '$new_pGender', AGE=$new_pAge, ADDRESS='$new_pAddress'
WHERE PID= '$ID'";
$stid = oci_parse($conn, $update_query);
$result=oci_execute($stid);
if (!$result) {
echo oci_error();
}
}
?>
THESE TWO PHPS ARE IN THE PHP FILE registration.php
So, my question is: i get the Id from the first php but i can't use in the second where both are in the same php file.Also, i tried putting the $ID=$_POST['edit_button']; above the if statement, but it gave me an error
You need to assign $ID in one hidden field of Update Patient form. So when you submit that form you will get a value of $ID as follows:
Initialize $ID with blank value above the first if statement:
$ID = "";
Update Patient Form
<form>
...
<input type="hidden" name="patient_id" value="<?php echo $ID; ?>" />
...
</form>
Second If statement
if(isset($_POST['Edit_Patient'])){
...
$ID = $_POST['patient_id'];
...
}
Hope this may helpful to anyone!

PHP MYSQL update stament not working

This code is meant to check the submitted form values and update the table,
however it just replaces the field with a blank
Any ideas where it is gone wrong, please?
<form action = "update.php" method = "POST">
<p>
New Name: <input type "text" name="name">
<input type= "submit">
</p>
</form>
<?php
require ('/var/www/html/site1/connect_db.php');
if(!empty($_POST['name']) && !is_numeric($_POST['name']))
{
$name=$_POST['name'];
$name=mysqli_real_escape_string($dbc,$query);
$name=strip_tags($name);
#$query='update customers SET customerName = '".$name."' where customerNumber=114';
$query = "update customers ". "SET customerName = $name"."where customerNumber=114" ;
mysqli_query($dbc,$query);
}
else
{
echo $name;
}
$query = 'select * from customers where customerNumber=103';
$result = mysqli_query($dbc,$query);
while ($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
echo"<p>Name : $row[1]</p>";
}
mysqli_close($dbc);
?>
You are updating customer number 114 but selecting 103 out, whose name may be blank.
Your update statement needs to have quotes around the $name bit as below:
$query = "UPDATE customers SET customerName = '$name' WHERE customerNumber=114";
Edit: please see the parameterised query advice in the question comments.

generating reference id after form submit

I am trying to generate a reference id like this CTS-P 0 then CTS-P 1 each time a user submits a form and it gets inserted.
what i have came up with is inserting CTS-P 0 to database as i submit.but the problem is its not incrementing CTS-P 0 to CTS-P 1 after i submit again.
i tried to use mysql_insert_id() here is what i have done so far.this is the smallest thing but i could not solve. please have a look
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("dbname",$con);
$genid="";
if(isset($_POST['submit'])) {
$frstname=$_POST["frstname"];
$genid=mysql_insert_id();
$genid .=count($genid);
//echo $genid;
for($i=0; $i<$genid; $i++) {
$sql = "INSERT INTO tblname (`namecol`,`refidcol`) VALUES ('$frstname','CTS-P $genid[$i]')";
$result = mysql_query($sql);
}}
?>
//here is the form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="generate" >
First Name<input type="text" name="frstname" />
<input type="submit" name="submit" value="Submit" />
</form>
it is inserting it in my refid column as CTS-P 0 but not incrementing from next time i submit.i know its very noobish but i am stuck.
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("dbname",$con);
if(isset($_POST['submit'])) {
$frstname=$_POST["frstname"];
$sql = "SELECT * FROM tblname";
$genid = mysql_query($sql, $con);
$genid = mysql_num_rows($genid);
//Since you're using "0" as your first number, I decided to comment this out, if not, uncomment it
//$genid++;
$sql = "INSERT INTO tblname (`namecol`,`refidcol`) VALUES ('$frstname','CTS-P $genid')";
$result = mysql_query($sql);
}
?>

PHP array updating multiple Mysql rows

I've a problem when updating multiple Mysql rows when using an array, Lets start with the following submit form :
$n = array(); //Supplier Name
$s = array(); //Short Name
$o = array(); //Shipment No.
$id = array(); //Supplier ID
<form action="editing_supplier.php" method="post">
<input type="hidden" value="<?php echo $row['id'] ?>" name="id[]">
<input type="text" value="<?php echo $row['name']?>" required name="n[]">
<input type="text" value="<?php echo $row['short_name']?>" required name="s[]">
<input type="text" value="<?php echo $row['shipment_no']?>" required name="o[]">
<input type="submit" value="Confirm Editing" >
</form>
Now when clicking Submit, which directly opens up "editing_supplier.php" page- The following codes are bellow :
if((isset($_POST['n'])) && (isset($_POST['s'])) && (isset($_POST['o']))){
//Shows up the ID for each Supplier Name
if(is_array($_POST['id'])) {
foreach($_POST['id'] as $id){
//Updates Supplier Name
if(is_array($_POST['n'])) {
foreach($_POST['n'] as $value){
$query = "UPDATE suppliers SET name = '".$value."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Short_Name
if(is_array($_POST['s'])) {
foreach($_POST['s'] as $value1){
$query = "UPDATE suppliers SET short_name = '".$value1."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Shipment No.
if(is_array($_POST['o'])) {
foreach($_POST['o'] as $value2){
$query = "UPDATE suppliers SET shipment_no = '".$value2."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//End of for Each id
}
}
What actually Does, When Selecting a single row to update..It works perfectly ! But when doing a multiple selection in-order to make an update for them, it messes up all the values..As if copying the last id,supplier name, short name and shipment no. to all the selected rows.
I think this is due to the series of foreach within the foreach($id). I would write :
foreach($_POST['id'] as $index=>$id) {
to keep track of the index of your record, and then do not do any other foreach but rather :
$query = "UPDATE suppliers SET name = '".$_POST['n'][$index]."' where id ='".$id."'";
so you keep the link between the $id value and the other variables.

how to insert an hidden field value along side with a checkbox in to the database

i am new here but i have a problem in inserting the id and the value of the checkboxes into my database here is the code of the form:
<?php
include('db.php');
$sql = "select * from sheet1 order by course_level asc";
$r = mysqli_query($dbc,$sql) or die(mysqli_error($dbc));
$co = '';
while($row = mysqli_fetch_array($r)) {
$co .= '<tr><td>'.$row['course_level'].'</td><td><input name="courses[]"
type= "checkbox" value = "'.$row['course_code'].'">'.$row['course_code'].'
</td> <td>'.$row['course_title'].'</td><td>'.$row['course_lecturer'].'
</td><input type=hidden name=cid[] value="'.$row['cid'].'">
</tr>';
}
?>
And this is the action code:
<?php
include('db.php');
if(isset($_POST['courses']))
echo 'lie';
else
echo 'true';
foreach($_POST['courses'] as $row=>$id){
$courses=$id;
$cid = $_POST['cid'][$row];
$sql = "insert into selected_courses values ('','$courses','$cid')";
$r = mysqli_query($dbc,$sql);
}
if($r)
echo 'done';
?>
thanks a lot.
You have several problems here, the main one being you are attempting to store two different reference values to the same row (course_code and cid) in your selected_courses table. You should really only store the primary key (cid?).
I'd suggest dropping the course_code column from your selected_courses table, remove the hidden input and structure your checkbox like this
<input type="checkbox"
name="courses[]"
value="<?php echo htmlspecialchars($row['cid']) ?>">
Then your INSERT query simply becomes
// Forget mysqli, move to PDO
$stmt = $dbc->prepare('INSERT INTO selected_courses (cid) VALUES (?)');
$stmt->bindParam(1, $cid);
foreach ($_POST['courses'] as $cid) {
$stmt->execute();
}

Categories