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());
}
}
}
}
Related
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
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.
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(); ?>
I have a dynamic HTML table that allows users to enter receipt items in, and they can add as many rows as necessary.
If they forget to fill out a field upon form POST, I want all those rows with the data to stay shown, instead what happens, is they dynamic rows disappear and no values are saved in the one row that shows on default.
How can I achieve having those dynamic table rows shown with the values they've entered to avoid them having to enter all the data again?
<?php
if(isset($saveAdd))
{
$expenseType = safeDataMySQL($_POST['expenseType']);
//Save page, redirect to same page but increment receipt number.
if(empty($_POST['expenseNumber']))
{
//New expense so no records have been created as of yet. Otherwise, this would be stored in hidden field.
$getRef = mysql_query("SELECT CAST(SUBSTRING(refNumber,4) AS UNSIGNED INTEGER) AS referenceNumber FROM expense_main ORDER BY referenceNumber DESC LIMIT 1") or die("Ref No: " . mysql_error());
if(mysql_num_rows($getRef) > 0)
{
while($refData = mysql_fetch_array($getRef))
{
//Expense Number!
$refNumber = $refData['referenceNumber'];
$refNumber = ($refNumber + 1);
}
$ins = mysql_query("INSERT INTO `expense_main` (`respid`, `refNumber`, `dateCreated`, `draftMode`, `expenseType`) VALUES ('".$respid."', 'USA".$refNumber."', NOW(), '1', '".$expenseType."')") or die("Expense Insert: " . mysql_error());
$expClaimNumber = 'USA'.$refNumber;
}
}
else
{
$expClaimNumber = safeDataMySQL($_POST['expenseNumber']);
}
//Get the next receipt in line as well
$getRec = mysql_query("SELECT receiptNumber FROM expense_details ORDER BY receiptNumber DESC LIMIT 1") or die("Get Receipt: " . mysql_error());
if(mysql_num_rows($getRec) > 0)
{
while($recData = mysql_fetch_array($getRec))
{
$receiptNumber = $recData['receiptNumber'];
$receiptNumber = ($receiptNumber + 1);
}
}
$fields = array('recLineDate_', 'recLineCategory_', 'recLineDescr_', 'recLineAmount_');
foreach ($fields as $field)
{
foreach ($_POST[$field] as $key=>$line)
{
$returnArray[$key][$field] = $line;
}
}
foreach ($returnArray as $lineItem)
{
if(empty($lineItem['recLineDate_']))
{
$Errors[] = 'You forgot to enter the receipt date.';
}
else
{
$recDate = safeDataMySQL($lineItem['recLineDate_']);
}
if(empty($lineItem['recLineCategory_']))
{
$Errors[] = 'You forgot to enter a category.';
}
else
{
$recCategory = safeDataMySQL($lineItem['recLineCategory_']);
}
if(empty($lineItem['recLineDescr_']))
{
$Errors[] = 'You forgot to enter a description.';
}
else
{
$recDescr = safeDataMySQL($lineItem['recLineDescr_']);
}
if(empty($lineItem['recLineAmount_']))
{
$Errors[] = 'You forgot to enter your receipt amount.';
}
else
{
$recAmount = safeDataMySQL($lineItem['recLineAmount_']);
}
if(empty($_POST['alternateBranch']))
{
$alternateBranch = '0';
}
else
{
$alternateBrach = $_POST['alternateBranch'];
}
if(!isset($Errors))
{
$recDate = date("Y-m-d", strtotime($recDate));
$ins = mysql_query("INSERT INTO `expense_details` (`receiptNumber`, `claimId`, `alternateBranch`, `dateAdded`, `expenseDate`, `expenseDescription`, `expenseAmount`, `categoryId`)
VALUES ('".$receiptNumber."', '".$expClaimNumber."', '".$alternateBranch."', NOW(), '".$recDate."', '".$recDescr."', '".$recAmount."', '".$recCategory."')") or die("Could not insert receipt: " . mysql_error());
$nextReceipt = ($receiptNumber + 1);
//Redirect to same page, incrementing the receipt number by 1.
header('Location: createExpense.php?expenseNumber='.$expClaimNumber.'&receiptNum='.$nextReceipt);
}
}
}
$expenseNumber = safeData($_GET['expenseNumber']);
$receiptNumber = safeData($_GET['receiptNum']);
if (isset($Errors))
{
echo "<div align='center'><span class='errormessagered'><ul class='errors'>";
foreach ($Errors as $Error)
{
echo "<li>".$Error."</li>";
echo '<br />';
}
echo "</ul></span></div>";
}
?>
<form name="createNew" method="POST" action="">
<div id="row">
<div id="left">
<strong>Receipt Items:</strong>
</div>
<div id="right">
<i>Only add another line to the receipt below IF you have multiple items on one receipt.</i>
<br /><br />
<table border="0" width="825px" cellspacing="0" cellpadding="5" name="receipts" id = "receipts">
<thead>
<tr>
<th class="colheader" width="120px">Date</th>
<th class="colheader" width="120px">Category</th>
<th class="colheader" width="120px">Description</th>
<th class="colheader" width="120px">Amount</th>
<th class="colheader" width="145px"><span class="boldblacklinks">[Add +]</span></th>
</tr>
</thead>
<tbody class="lineBdy">
<tr id="line_1" class="spacer">
<td><input type="text" class="date fieldclasssm" id="recLineDate[]" name="recLineDate_[]" size="10" value = "<?=date("m/d/Y", strtotime($today))?>"/></td>
<td><select name="recLineCategory_[]" class="fieldclasssm">
<option value = "">Select a Category...</option>
<?php //Get Categories
$getCats = mysql_query("SELECT id, nominalName FROM expense_nominalCodes ORDER BY id") or die("Get Cats: " . mysql_error());
if(mysql_num_rows($getCats) > 0)
{
while($catData = mysql_fetch_array($getCats))
{
echo '<option value = "'.$catData['id'].'"'; if($catData['id'] == $_POST['recLineCategory_']) { echo "Selected = 'SELECTED'"; } echo '>'.$catData['nominalName'] . '</option>';
}
}
?>
</select>
</td>
<td><input type="text" class="lineDescr fieldclasssm" name="recLineDescr_[]" id="recLineDescr[]" value = "<?=$_POST['recLineDescr']?>" size="40" /></td>
<td colspan = "2"><input type="text" class="sum lineAmount fieldclasssm" name="recLineAmount_[]" id="recLineAmount[]" value = "<?=$_POST['recLineAmount']?>" size="12" /></td>
</tr>
</tbody>
</table>
</div>
" />
" />
<script type="text/javascript">
$(document).ready(function () {
$('.date').change(function () {
$('.date').val($('.date:nth-of-type(1)').val());
});
});
//Add new table row & clone date field
$('#add').on('click', function(){
addReceiptItem();
$('.date').focus(function() {
$(this).select();
});
$('.receipt').focus(function() {
$(this).select();
});
});
function addReceiptItem(){
var lastID = $('tr[id*="line_"]').length,
newTds = $('tr[id="line_' + lastID + '"] td').clone(),
newRow = document.createElement('tr');
// add new id and class to row, append cloned tds
$(newRow)
.attr('id', 'line_' + (lastID + 1 ))
.attr('class', 'spacer')
.append(newTds);
$(newRow).find('input').not(':eq(0)').val('');
// $(newRow).find('class').not(':eq(0)').not(':eq(0)').val('');
//add the new row to the table body
$('tbody.lineBdy').append(newRow);
$('.receipt').attr('readonly', true);
$('.date').attr('readonly', true);
};
</script>
Just to get you started. You can add the rows from $_POST["rows"]
foreach ($_POST["rows"] as $rowstring) {
list($date, $cat, $desc, $amt) = explode(",", $rowstring)
?>
<td><?php echo $date; ?></td>
<td><?php echo $cat; ?></td>
<td><?php echo $desc; ?></td>
<td><?php echo $amt; ?></td>
<td> </td>
<?php
}
Assuming you add a hidden input with a comma delimited string each time a dynamic row is added.
FWIW, I would also recommend doing all of the database queries (ie $getCats = ...) prior to rendering anything to the screen so that in case the 'or die()' happens, you wont get a half rendered page.
Any ideas why the following code is not adding anything into the database once the user fills out the form? I'd really appreciate it.
Thank you!
if($_SESSION['loginSuccess']==1) {
// ============================================================
// = Create the table of current tasks stored in the database =
// ============================================================
$userID = $_SESSION['userID'];
$result = mysql_query("SELECT * FROM Tasks WHERE userID = '$userID'");
echo "<div id=\"draggable\" class=\"ui-widget-content\"><table border='5'><tr class=\"ui-widget-header\"><td><u>Task Name:</u></td><td><u>Class:</u></td><td><u>Due Date:</u></td><td><u>Task Type:</u></td></tr>";
echo $_SESSION['userID'];
while($row = mysql_fetch_array($result)) {
$taskName = $row[1];
$class = $row[2];
$taskDueDate = $row[3];
$taskType = $row[4];
echo "<tr><td>'$taskName'</td><td>'$class'</td><td>'$taskDueDate'</td><td>'$taskType'</td></tr>";
}
echo "</table>";
function addNewTask ($name, $class, $dueDate, $type) {
mysql_query("INSERT INTO Tasks VALUES ('$userID','$name', '$class', '$dueDate', '$type')");
}
if($_POST['taskName'] != NULL) {
addNewTask($_POST['taskName'], $_POST['class'], $_POST['dueDate'], $_POST['dueDate']);
}
?>
<!-- <img border="1" alt="New" src="/newTask.png" id="newTask" onmouseClick="showTaskField"/> -->
<p><form name="newTask" method="post" action="index.php" id="newTask"><br>
Task Name: <input name="taskName" type="text"> (necessary)<br>
Class: <input name="class" type="text"><Br>
Due Date: <input name="dueDate" type="text" id="datepicker"><Br>
Type:
<input type="submit"></p></div>
Try getting rid of the ' around the variables in the insert statement. If that does nothing echoing mysql_error().