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.
Related
Can someone please tell me how I can get my $cat_id variable recognised in the SECOND PART of my code ? It works fine in the FIRST PART - I mean the $cat_id value is inserted into mysql database with :
$insert_review_command = "INSERT INTO review VALUES(NULL,'$cat_id','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
But nothing inserts in the SECOND PART. I don't think my $cat_id is recognised. But why shouldn't it be ?Should $cat_id not be recognised throughout my whole code ? If it is defined within an If statement is it only recognised within that If statement? Thanks for any help.
<?php require('dbConnect.php');
if (isset($_POST['create'])) {
$category = ($_POST['category']);
$name = ($_POST['name']);
$phonenumber = ($_POST['phonenumber']);
$address = ($_POST['address']);
$comment = ($_POST['comment']);
//check if the category being entered is already there
$select_from_cat_table = "SELECT * FROM category WHERE cat_name = '$_POST[category]'";
$result=mysqli_query($con,$select_from_cat_table);
$num_rows = mysqli_num_rows($result);
// get the matching cat_id
$row = mysqli_fetch_assoc($result);
$cat_id = $row["cat_id"];
// ****FIRST PART**** $CAT_ID IS INSERTED INTO THE DB
//if the category name already exists in the category table, then don't add it in again
if($num_rows >= 1) {
echo "This Already Exists<br/>";
//but do add it to the review table
//for the cat_id, we want to get the cat_id of the category name that already exists, that has
//just been posted. This is $cat_id. $user_id is the user id of the person posting
$insert_review_command = "INSERT INTO review VALUES(NULL,'$cat_id','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
$insert_into_review_table = mysqli_query($con,$insert_review_command);
}
// ****SECOND PART**** $CAT_ID IS NOT INSERTED INTO THE DB
else if ($num_rows < 1)
{
//if it's not in there, then add the category in the category table.
$insert_category_command = "INSERT INTO category VALUES(NULL, '{$category}', '$user_id')";
$insert_into_category_table = mysqli_query($con,$insert_category_command);
//****WHY IS CAT_ID NOT WORKING HERE????******
//and add it to the review table
//for the cat_id, we want to get the cat_id of the category name that already exists, that has
//just been posted. This is $cat_id. $user_id is the user id of the person posting
$insert_review_command = "INSERT INTO review VALUES(NULL,'$cat_id','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
$insert_into_review_table = mysqli_query($con,$insert_review_command);
echo "Yes, it's been added correctly";
echo $cat_id;
}
$con->close();
header('Location:volleyLogin.php');
}
?>
<!doctype html>
<html>
<body>
<h2>Create new Contact</h2>
<form method="post" action="" name="frmAdd">
<p><input type="text" name = "category" id = "category" placeholder = "category"></p>
<p><input type="text" name = "name" id = "name" placeholder = "name"></p>
<p><input type="text" name = "phonenumber" id = "phonenumber" placeholder = "phone number"></p>
<p><input type="text" name = "address" id = "address" placeholder = "address"></p>
<p><input type="text" name = "comment" id = "comment" placeholder = "comment"></p>
<h2>Visible to :</h2>
<input type="radio" name="allmycontacts" value="All my Contacts">All my Contacts
<input type="radio" name="selectwho" value="Select Who">Select Who
<input type="radio" name="public" value="Public">Public
<input type="radio" name="justme" value="Just me">Just me
<p><input type="submit" name = "create" id = "create" value = "Create new Contact"></p>
Exit
</form>
</body>
</html>
Your logic is split into two parts, if $num_rows is greater than 0, or if it's 0. This is the result of a query, obviously. So when you do
$cat_id = $row["cat_id"];
from the first query, and $num_rows is zero, your $cat_id doesn't hold any values, because mysqli_fetch_assoc() returned no rows (mysqli_num_rows() is 0), so $row is null.
Your solution is to fetch the recent inserted ID from your category table before you insert it into your review table.
Simply add
$cat_id = mysqli_insert_id($con);
before your insert-query for the review table (but after you insert values into the category table).
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);
▲
i have multiple checkbox values in my form as shown in figure
I know i can store values for single checkbox in db but here situation is slightly different,so ho could i successfully store them in different different rows for same db.
my table struture is
1.content_table
title,description,category_id(fk),course_id(fk),subject_id(fk),content_type_id(fk)
2.category_table
entrance,school,ug,pg
3.subject_table
english,hindi,maths......
4.content_type_table
notes,summary,videos,question_bank
i have to insert data from shown form in content_table which store data by category_id,course_id,subject_id,content_type_id
i have tried following code which is only working for single checkbox i.e category ,so please someone suggest me how to do for different type of checkbox.
my code is
<?php
include 'includes/dbconfig.php';
if($_SERVER['REQUEST_METHOD']=='GET')
{
echo $title = $_GET['title'];
echo $description = $_GET['description'];
echo $content_url = $_GET['content_url'];
echo $thumb_icon_url = $_GET['thumb_icon_url'];
$category = $_GET['category'];
$course = $_GET['course'];
echo $select_subject = $_GET['select_subject'];
echo $select_content_type = $_GET['select_content_type'];
foreach (array_combine($category, $course) as $cat => $cose) {
$sql = mysqli_query($conn,"SELECT category_id from category_ref_table where category = '$cat'") or die(mysqli_error());
$row = mysqli_fetch_array($sql,MYSQLI_ASSOC);
echo $category_id = $row['category_id'];
$sql1 = mysqli_query($conn,"SELECT course_id from course_ref_table where course = '$cose'") or die(mysqli_error());
$row1 = mysqli_fetch_array($sql1,MYSQLI_ASSOC);
echo $course_id = $row1['course_id'];
$sql2 = mysqli_query($conn,"SELECT subject_id from subject_ref_table where subject = '$select_subject'") or die(mysqli_error());
$row2 = mysqli_fetch_array($sql2,MYSQLI_ASSOC);
echo $subject_id = $row2['subject_id'];
$sql3 = mysqli_query($conn,"SELECT content_type_id from content_type_table where content_type = '$select_content_type'") or die(mysqli_error());
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
echo $content_type_id = $row3['content_type_id'];
mysqli_query($conn,"INSERT INTO content_ref_table (title,description,content_url,thumb_icon_url,category_id,course_id,subject_id,content_type_id,login_id)VALUES ('$title','$description','$content_url','$thumb_icon_url','$category_id','$course_id','$subject_id','content_type_id')");
}
}
?>
try something like this(array variable)
<input type="checkbox" name="category[]" value="entrance">
<input type="checkbox" name="category[]" value="School">
<input type="checkbox" name="category[]" value="ug">
<input type="checkbox" name="category[]" value="pg">
Upon using like this you can get the list of checked items as an array. After that do the required save it in your table.
I am trying to take input from an HTML form where there are checkboxes. The checkboxes are created with the student_ids from the database. Like so:
<td><input type="checkbox" name="{$row['STUDENT_ID']}" />
What I want to do is step through the Students table and check all of the entries against which of the checkboxes are checked. I want to then delete the entries from the database that have been checked with the checkboxes.
8 $query = "SELECT STUDENT_ID From Students";
9 $result = mysql_query($query) or die(mysql_error());
10 while($row=mysql_fetch_array($result)){
11 $checkname=$row['STUDENT_ID'];
12 foreach($_POST[$checkname] as $student_id =>val)
13 {
14 if($val == 'YES'
15 {
16 echo $_POST['STUDENT_ID'];
17 $query = "DELETE FROM Students WHERE STUDENT_ID" . mysql_real_escape_string($STUDENT_ID);
18 }
19 echo $query;
20 $result = mysql_query($query) or die(mysql_error());
21 //echo $POST['STUDENT_ID'];
22 }
23 }
Create an array of checkbox :
<input type="checkbox" name="studentID[]" value="{$row['STUDENT_ID']}" />
From PHP :
$studentID = $_POST['studentID'];
foreach($studentID as $ID){
echo $ID.'<br />'."\n";
}
EDIT :
Not sure but I think this is the right way :
$studentID = $_POST['studentID'];
$i=0;
foreach($studentID as $ID){
$i++;
echo $_POST['studentID'][$i].'<br />'."\n";
}
Try this for your form:
<input type="checkbox" name="STUDENT_ID[<?php echo $row['STUDENT_ID'] ?>]" value="YES" />
and this for your PHP loop:
foreach ($_POST['STUDENT_ID'] as $student_id => $val) {
if ($val == 'YES') {
$query = "DELETE FROM Students WHERE STUDENT_ID=" . mysql_real_escape_string($student_id);
$result = mysql_query($query) or die(mysql_error());
}
}
A better way of doing this is to take the Student IDs from your checkboxes that were submitted and then run deletes on those.
HTML
<input type="checkbox" name="students_to_delete[]" value="{$row['STUDENT_ID']}" />
PHP
$students_to_delete = $_POST['students_to_delete'];
if(is_array($students_to_delete) && count($students_to_delete) > 0) {
$query = "DELETE FROM Students WHERE STUDENT_ID IN (" . implode(",", $students_to_delete) . ")";
$result = mysql_query($query) or die(mysql_error());
}
The above code is vulnerable to SQL injection. If someone posts back to the server a value of 0 OR STUDENT_ID!=0 then all rows in the Students table will be deleted.
Your code is also inefficient - you are returning all the students and then iterating over each student to see if this requires deleting.
You would be better using in your markup:
<input type="checkbox" name="STUDENT_TO_DELETE" value="$row['STUDENT_ID']" />
and then in the php:
foreach ($_POST['STUDENT_TO_DELETE'] as $student_id => $val) {
$sql = "DELETE FROM Students WHERE STUDENT_ID=" . mysql_real_escape_string($student_id);
mysql_query($sql);
}
}
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();
}