Inserting multiple rows to database from a while loop - php

Good day! I am having a problem in storing values in my database. The flow of the program is the user will input in how many subject he will get. For example, he/she can put 6 subjects. So it will release 6 input types with values equal to text. My problem is I don't get 6 rows in my database as the user take 6 inputs.
HTML/PHP
<form method="POST">
<table>
<tr>
<td>SUBJECT CODE/SUBJECT DESCRIPTION/SEMESTER</td>
</tr>
<?php $counter=1 ;
while($counter <= $subj){?>
<tr>
<td>
<select name="sub">
<?php $select=mysql_query("SELECT * FROM subject
WHERE course_code = '$course' AND semester = '$sem'");
while($rows=m ysql_fetch_assoc($select)){
$code=$rows['subj_code'];
$desc=$rows['subj_desc'];
$units=$rows['units'];
$yr=$rows[ 'year_level'];
?>
<**option value="<?php echo $codes[$code]; ?>">
<?php echo $code. " - ".$desc; ?>
</option>**
<?php } ?>
</select>
</td>
<td>
</td>
</tr>
<?php $counter++; } } ?>
<tr>
<td>
<input type="submit" name="add" value="add subjects">
</td>
</tr>
</table>
</form>
PHP/SQL
<?php
if (isset($_POST['add'])) {
$data = array();
$subject = $_POST['sub'];
$sem = $_SESSION['sem'];
for ($i = 0; $i < count($subject); $i++) {
$subject = mysql_real_escape_string($subject[$i]);
$sem = mysql_real_escape_string($sem[$i]);
$yr = mysql_real_escape_string($yr[$i]);
$fac = mysql_real_escape_string($fac[$i]);
$col = mysql_real_escape_string($col[$i]);
$set = mysql_query("SET foreign_key_checks = 0");
if (!$set) {
die("Foreign key SET failed");
} else {
$insertmid = mysql_query("INSERT INTO grade_midterm
(midterm_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject', '$user','$fac','$col')");
if (!$insertmid) {
die("Failed to insert midterm" . mysql_error());
} else {
$insertfinal = mysql_query("INSERT INTO grade_final
(final_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject','$user','$fac','$col')");
if (!$insertfinal) {
die("Failed to indert final");
} else {
$set2 = mysql_query("SET foreign_key_checks = 1");
echo "<script>alert('Success Adding Subject');</script>";
}
}
}
}
}
?>

You have a select box with name sub in your loop
<select name="sub">
this means every next selectbox will overwrite the previous one
use
<select name="sub[]">
to create a array in your $_POST variable

Related

Datalist only displaying and serving 1st word

OK, Let's start again. The purpose of this code is to update a database table (db.aotm) comprising the club members who will be featured during the coming year as "The Artist of the Month". The first (html)table shows a list of members who gualify as Features Artists. Their names are hald in the $featuredArtist array.
Next, the $aotm array is populated with the current list of "month" and "member" held in the db.aotm table these are used as the default values of the form.
Then the datalist is populated with names from the $featuredArtist array.
The problem is that when the Form Input box is clicked the datalist box only shows the first name of each artist and any selection only enters the first name.
I have tried using a simple variable instead ogf th array in the datalist but the same happens if $name = "John Smith"; then only "John" is displayed and entered into the input box. If I replace the soft datalist a hard coded datalist then it functions normally. So it seems tha any variable in the datalist only serves the first word.
My code is :
<?php
echo '<div class="dbrd">
$query = " SELECT id, status, fullname FROM members ";
$result = mysqli_query($db, $query);
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
if (bitN($row[status],2) == 1 && $row[id] > 20){
$featuredArtist[$i]['id'] = $row['id'];
$featuredArtist[$i]['artist'] = $row['fullname'];
$i++;
}
}
?>
<div style="text-align:center;width:100%;">
<table style="width:100%;">
<thead>
<tr><th colspan="3">Featured Artists</th></tr>
</thead>
<tbody>
<?php
$j = 0;
while ($j < $i){
echo " <tr><td>".$featuredArtist[$j]['artist']."</td>";
$j++;
echo " <td>".$featuredArtist[$j]['artist']."</td>";
$j++;
echo " <td>".$featuredArtist[$j]['artist']."</td></tr>";
$j++;
}
?>
</tbody>
</table>
<br />
</div>
<?php
$query = "SELECT id, artist FROM aotm";
$result = mysqli_query($db, $query);
$k = 0;
while ($row = mysqli_fetch_assoc($result)) {
$aotm[$k]['id'] = $row['id'];
$aotm[$k]['artist'] = $row['artist'];
$k++;
}
$l = 0;
echo '<datalist id = "artist">';
while ($l < $i) {
$artist = $featuredArtist[$l]['artist'];
echo " <option value = ".$artist.">";
$l++;
}
?>
</datalist>
<form action = "" method = "POST">
<table style="width:100%;">
<tbody>
<tr><td>Jan</td><td><input type = "text" list = "artist" name="1" size = "45" ></td></tr>
<tr><td>Sept</td><td><input list = "artist" type = "text" name="2" value = "<?php echo $aotm[1]['artist'];?>" size = "45" /></td></tr>
<tr><td colspan="2"><input type = "submit" name = "aotm" value = "Save" /></td></tr>
</tbody>
</table>
</form>
</div>

how to insert multidimensional array using for loop

I have 2 tables. One is for students and one of subjects. I want to fetch data from the students and subjects tables on same page. In front of student 1 subject 1 subject 2 subject 3. Then in front of student 2 subject 1 subject 2 subject 3. It is to submit result.
I have done this.
Than I have to insert this in 3rd table of results. I have successfully inserted students in result table. And subjects. But on the time of marks, I am unable to insert. I used a multidimensional array. I am unable to insert marks data into array. How can I do this?
Let me show some snapshots.
My multidimensional array is not working, and I don't know how to do this. Kindly help me out.
This is a detailed pic: This is the detailed snapshot.
// count students
$sql = "SELECT * FROM tb_students";
$run = mysqli_query($mysqli,$sql);
$total_students = mysqli_num_rows($run);
$numbers=$total_students;
for($i=1;$i<=$numbers;$i++)
{
while ($rows = mysqli_fetch_assoc($run)) {
$id = $rows['student_id'];
$name = $rows['student_name'];
?>
<tr>
<td>Name</td>
<td hidden><input type="text" value="<?php echo $id?>" name="student_id[]" /></td>
<td><?php echo $name ?> </td>
</tr>
<input type="hidden" value="<?php echo $numbers;?>" name="numbers" />
<?php
$sel_sub = "SELECT * FROM subjects WHERE class_name = '1st year'";
$run_sub = mysqli_query($mysqli,$sel_sub);
$total_sub = mysqli_num_rows($run_sub);
for ($k=0; $k < $total_sub ; $k++) {
while ($rows = mysqli_fetch_assoc($run_sub)) {
$sub_id = $rows['sub_id'];
$sub_name = $rows['sub_name'];
?>
<tr>
<td><?php echo $sub_name; ?></td>
<td hidden><input type="" value="<?php echo $sub_id;?>" name="sub_id[]" /></td>
<input type="hidden" value="<?php echo $total_sub;?>" name="subject" />
<td><input type="text" name="marks[][]" placeholder="Marks" /></td>
</tr>
<?php
}
}
?>`
and this is isnert query
<?php
$mysqli = mysqli_connect("localhost","salman","salman1214","shan");
if(mysqli_connect_errno())
die("Connection failed".mysqli_connect_error());
$s = '';
for($i=0;$i<$_POST['numbers'];$i++)
{
for($j=0;$j<$_POST['subject'];$j++)
{
$s = "insert into result(student_id,exam_name, subject_name, sub_marks) values";
$s .="('".$_POST['student_id'][$i]."','".$_POST['exam_name']."','".$_POST['sub_id'][$j]."','".$_POST['marks'][$i][$j]."'),";
$s = rtrim($s,",");
if(!mysqli_query($mysqli,$s))
echo mysqli_error();
else
echo "Records Saved <br />";
$sub_list = $_POST['marks'][$i][$j];
echo $sub_list;
}
}
mysqli_close($mysqli);?>
I don't want to say if this way is the best way.
But, your problem is you are using the lines in the loops which should not. Try this:
<?php
$mysqli = mysqli_connect("localhost","salman","salman1214","shan");
if(mysqli_connect_errno())
die("Connection failed".mysqli_connect_error());
$s = '';
$s = "insert into result(student_id,exam_name, subject_name, sub_marks) values";
for($i=0;$i<$_POST['numbers'];$i++)
{
for($j=0;$j<$_POST['subject'];$j++)
{
$s .="('".$_POST['student_id'][$i]."','".$_POST['exam_name']."','".$_POST['sub_id'][$j]."','".$_POST['marks'][$i][$j]."'),";
}
}
$s = rtrim($s,",");
if(!mysqli_query($mysqli,$s))
echo mysqli_error();
else
echo "Records Saved <br />";
mysqli_close($mysqli);?>

Database won't stay updated after switching script

I'm trying to update this database, and I've verified within this script that the update is completed, and that the $nw and $p variables are correct.
<?php
session_start();
$num = (int) $_SESSION["cart"];
$cart = $num + 1;
$_SESSION["cart"] = (string) $cart;
$nme = $_POST['nameofitem'];
$pst = $_SESSION["user"];
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$query = "select * from Items where Items.Id = '$nme'";
$result = $db->query($query) or die ($db->error);
$item = $result->fetch_array();
$nw = $item[5] - 1;
$p = (int) $pst;
echo $p;
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
$db->query($query3) or die ("Invalid insert " . $db->error);
$query2 = "insert into Bought (Name, Cost, BuyerID) values ('$item[1]', '$item[4]', '$pst')";
$db->query($query2) or die ("Invalid insert " . $db->error);
header("Location: store.php");
?>
However, when it redirects to this script, it echoes the information as if it weren't updated. What is the problem?
<?php
session_start();
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$user = $_SESSION["user"];
$pw = $_SESSION["pw"];
# determines number of items in cart to display
if (!isset($_SESSION["category"]))
$_SESSION["category"] = "Book";
if (isset($_POST["Ccategory"])) {
$cat = $_POST["Ccategory"];
$_SESSION["category"] = $cat;
}
if (!isset($_SESSION["cart"]))
$_SESSION["cart"] = "0";
$cart = $_SESSION["cart"];
?>
<!DOCTYPE html>
<html>
<?php # setting up table with items to buy ?>
<table border = "1" border-spacing = "5px" >
<caption><h2> UVA Bookstore 2.0</h2>
<p align=right> Items in cart: <?php echo $cart?> </p> <br />
<b><i>Welcome to the new and improved bookstore with a better selection than ever</i></b>
<br/><br/>
</caption>
<tr align = "center">
<th>Item</th>
<th>Description</th>
<th>Price</th>
<th>Number left</th>
<th>Buy</th>
</tr>
<?php
$category = $_SESSION["category"];
$query = "select * from Items where Items.Category = '$category'";
$result = $db->query($query) or die ($db->error);
$rows = $result->num_rows;
for ($i = 0; $i < $rows; $i++)
{
$row = $result->fetch_array();
?>
<form action="addtocart.php"
method="POST">
<tr align = "center">
<td>
<?php
echo $row[1];
?>
</td>
<td> <?php echo $row[3];?> </td>
<td> <?php echo $row[4];?> </td>
<td> <?php echo $row[5];?> </td>
<?php # sets up add to cart button that adds item to cart ?>
<td> <input type = "hidden" name ='nameofitem'
value= "<?php echo $row[0]?>">
<input type='submit' value='Add to Cart'> </input> </td>
</tr>
</form>
<?php
}
# form to check out and go to summary page ?>
<form action = "store.php"
method = "POST">
<tr align = "center"> <td>
<select name = "Ccategory">
<option value = "Book">Books</option>
<option value = "Music">Music</option>
<option value = "Car">Cars</option>
</select>
<input type = "hidden" name = "cat"> </td>
<td> <input type = "submit" value = "Switch Category"> </td>
</form>
<form action="summary.php"
method="POST">
<td> <input type = "submit" value = "Check out"> </td> </tr>
</table><br/>
</form>
</html>
Have you tried changing
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
to
$query3 = "update Items set Quantity = '$nw' where Id = $p";
The best way to determine if an UPDATE should work is to replace it with a SELECT containing the same WHERE clause. This way you can see what rows would be changed if you were to run the original query.
Otherwise, it seems to be the case that your changes in the current transaction are never committed. Is this the only script that has an issue with updates to the database? Please see the PHP manual for more information:
//mysqli::commit -- mysqli_commit — Commits the current transaction
bool mysqli::commit ([ int $flags [, string $name ]] )
A commit should be issued when you are done doing all updates that have dependencies (or for those that are atomic), however, you don't always have to commit depending on the configuration of your server. Also, it looks like your script has SQL injection vulnerabilities as other have mentioned. It would probably be best to use prepared statements or sanitize your inputs.

PHP Checkbox ordered by click and send thru post form to a news sql query on the clicked order

I have a code on page1.php where I have an array of checkbox populated with mysql data through a query. I can successfully submit the value of the checked checkbox to the page2.php. But I want to submit it according to the sequence the checkbox was checked by the user. I´ve seen that jQuery can do this, but i don´t know how and where to place the jQuery code.
My intention is to show on page2.php what the user selected, on a specific order, from the page1.php form
MODIFIED: Well , I managed to create the list and send via form . The problem now is to put a comma between the numbers . I know this must be the easiest problem to solve , but I can not yet.
The SQL Query is looking like this, for example:
SELECT * FROM emp WHERE id IN (7,9,30) ORDER BY FIELD (id,
30 9 7)
page1.php
<script type="text/javascript">
var listCheckedOptions = [];
function addToList(checkObj, outputObjID) {
//Remove from array if the element already in.
if (listCheckedOptions.indexOf(checkObj) >= 0) {
listCheckedOptions.splice(listCheckedOptions.indexOf(checkObj), 1);
}
listCheckedOptions.push(checkObj);
document.getElementById(outputObjID).value = ""; //Clean textarea
document.getElementById(outputObjID).value = listCheckedOptions.map(function (o) {
return o.value;
}).join('\r\n'); //Add to textarea
if (!checkObj.checked) checkObj.nextSibling.querySelector('span').innerHTML = '';
listCheckedOptions.forEach(function (el, i) {
var span = el.nextSibling.querySelector('span').innerHTML = i + 1;
});
return;
}
</script>
<?php
$query = "SELECT * FROM imoveis";
$result = mysql_query($query,$conn);
?>
<form action="page2.php" method="post">
<input type="submit" value="Create" id="enviarButton"/></td>
<br><br>
<table border="1">
<?
$i = 0;
echo "<tr>";
while($imovel = mysql_fetch_array($result)){
$name = $imovel['emp'];
$id = $imovel['id'];
?>
<td>
<?=$name;?><br>
<input type="checkbox" name="op_imovel[]" value="<?=$id;?>" onClick="addToList(this, 'txt1')">
</td>
<?
$i++;
if(($i % 3) == 0){
echo "</tr><tr>";
}
}
mysql_close();
?>
</table>
<br>
<input type="hidden" name="txt1" id="txt1">
</form>
page2.php
<?php
$checkbox = $_POST['op_imovel'];
$lista = $_POST['txt1'];
if (is_array($checkbox) && count($checkbox) > 0){
$res = '';
$tot = count($checkbox) - 1;
for ($y = 0; $y <= $tot; $y++) {
$res .=$checkbox[$y];
if ($y < $tot)
$res .= ",";
}
}
$query = "SELECT * FROM emp WHERE id IN ($res) ORDER BY FIELD (id, $lista)";
$result = mysql_query($query,$conn);
?>
<br>
<div align="center">
<table border="1">
<?
$i = 0;
echo "<tr>";
if (is_array($checkbox) && count($checkbox) > 0){
while($imovel = mysql_fetch_array($result)){
$name = ($imovel['emp']);
?>
<td>
<p>
<?= $name;?>
</p>
</td>
<?
$i++;
if(($i % 3) == 0){
echo "</tr><tr>";
}
}
}
?>
</div>
<? mysql_close(); ?>

Insert and Update data in database at the same time

What i want- i want to insert data into database if no existing data, and update if the data already exist in database.
Problem - If i click submit button without enter new data, the data still insert into database.
This is my code so far:
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<?php
mysql_connect("localhost","root","");
mysql_select_db("cuba");
if(isset($_POST['hantar']))
{
for($a=1; $a<=count($_POST['name']); $a++)
{
/*$sqlQuery = "REPLACE INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."')"; */
$sqlQuery = "INSERT INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' ) on DUPLICATE KEY UPDATE name='".$_POST['name'][$a]."', ic ='".$_POST['ic'][$a]."'";
mysql_query($sqlQuery)or die(mysql_error());
}
}
?>
<form action="" method="post">
<div class="b">
<?php
$a = 1;
$share = mysql_query("select *from a")or die(mysql_error());
while($share_papar = mysql_fetch_array($share))
{
?>
<table class="bb" style="border:1px solid #003;">
<tr>
<td width="200">Name</td>
<td> : <input type="text" class="input_teks" name="name[]" value="<? php echo $share_papar['name'];?>" />
</td>
</tr>
<tr>
<td>ic</td>
<td> : <input type="text" class="input_teks" name="ic[]" value="<?php echo $share_papar['ic'];?>" /></td>
</tr>
<tr>
<td>id</td>
<td> : <input type="text" class="input_teks" name="id[]" value="<?php echo $share_papar['id'];?>" id="akhir"/></td>
</tr>
<tr>
<td colspan="2" align="right" class="b_buang">Remove</td>
</tr>
</table>
<?php
}?>
</div>
<input type="submit" value="ss" name="hantar">
</form>
<span class="b_tambah">Add new group</span>
<script type="text/javascript">
$(function()
{
//nk clone
$('.b_tambah').on('click',function(e)
{
$(".b").find(".bb").last().clone(true).appendTo(".b");
alert( $(".bb:last").find("input[id=akhir]").last().val());
var m = $(".bb:last").find("input[id=akhir]").last();
m.val("");
});
//nk buang
$(".b_buang").click(function () {
if($('.bb').length < 2)
{
alert("Remove operation can be done if GROUP more than one");
}
else
{
$(this).parents(".bb").remove();
}
});
});
</script>
<!-- close clone Shareholders -->
</td>
I'm using jquery to clone form same with update form, then reset value to blank for input type name (id), so i can have non match id with existing data. But if i submit form without cloning those form, the data will insert into database. What i want is, no need to insert data into database if i dont cloning the new data and just update the existing. How i can achieve that..
Use this code
if(isset($_POST['hantar']))
{
for($a=1; $a<=count($_POST['name']); $a++)
{
$name = $_POST['name'][$a];
$ic = $_POST['ic'][$a];
$name = $_POST['name'][$a];
$sel = mysql_query("select * from a where name = '$name' and ic = '$ic' ");
if(mysql_num_rows($sel) > 0){
//write update query
$fet =mysql_fetch_array($sel);
$auto_increment_id = $fet['id'];
$sqlQuery = " update a set name = '$name' , ic = '$ic' where id = '$auto_increment_id' ";
}
else {
// write insert query
$sqlQuery = "INSERT INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' ) ";
}
mysql_query($sqlQuery)or die(mysql_error());
}
}
first check the $_POST['name'] in SELECT query if it is exsits update in the query if not then insert into database
try replacing
for($a=1; $a<=count($_POST['name']); $a++)
to
for($a=0; $a < count($_POST['name']); $a++)
And also check validation
e.g.
if(isset($_POST['name'][$a]) && trim($_POST['name'][$a]) != "")
Finally.. This code save me..
if(isset($_POST['hantar']))
{
for($a=0; $a < count($_POST['name']); $a++)
{
if($_POST['name'][$a]=="")
{
}else
{
if($_POST['id'][$a]=="")
{
$sqlQuery = "INSERT INTO a (name,ic) VALUES ('".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' )";
mysql_query($sqlQuery)or die(mysql_error());
}
else
{
$sqlQuery = " update a set name = '{$_POST['name'][$a]}' , ic = '{$_POST['ic'][$a]}' where id = '{$_POST['id'][$a]}' ";
mysql_query($sqlQuery)or die(mysql_error());
}
}
}
}

Categories