Not Able to save data to Mysql database - php

I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}

You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.

Related

Update multiple record with single query in database using php [duplicate]

This question already has an answer here:
Post form and update multiple rows with mysql
(1 answer)
Closed last year.
I am making an invoice in PHP where multiple products are inserted at once into one table and there grand total goes to another table. I am trying to UPDATE the invoice in MYSQL and PHP. When I press the submit button, the multiple records data from the form goes to the update.php but the query does not run.
database.php
<?php
$connect = mysqli_connect('localhost','root','','invoice');
if (!$connect){
die("Connection failed: " . mysqli_connect_error());
}
?>
edit_invoice.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
table,tr,td,th { border: 1px black solid;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Back to Invoice List<br><br>
<?php
include('database.php');
$invoice_number = $_GET['invoice_number'];
$sql = "SELECT * from invoice where invoice_number = '$invoice_number' ";
$query = mysqli_query($connect, $sql);
if ($query->num_rows > 0) {
// output data of each row
$fetch = $query->fetch_assoc();
}
?>
<form method="POST" action="update_invoice.php">
<table>
<thead>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Width</th>
<th>Height</th>
<th>Total</th>
<th>Action</th>
</thead>
<?php
$sql2 = "SELECT * from invoice_order where invoice_number = '$invoice_number' ";
$query2 = mysqli_query($connect, $sql2);
if ($query2->num_rows > 0) {
// output data of each row
$srno = 1;
$count = $query2->num_rows;
for ($i=0; $i < $count; $i++) {
while($row = $query2->fetch_assoc()) {
?>
<tbody id="product_table">
<tr>
<td><input type="text" name="product[]" value="<?php echo $row["product"]; ?>"></td>
<td><input type="text" name="price[]" value="<?php echo $row["price"]; ?>"></td>
<td><input type="text" name="quantity[]" value="<?php echo $row["quantity"]; ?>"></td>
<td><input type="text" name="width[]" value="<?php echo $row["width"]; ?>"></td>
<td><input type="text" name="height[]" value="<?php echo $row["height"]; ?>"></td>
<td><input type="text" name="total[]" value="<?php echo $row["total"]; ?>" class="totalPrice" readonly></td>
<td><input type="button" value="X" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
<?php
}
}
} else {
echo "No Record Found";
}
?>
<input type="button" name="submit" value="Add Row" onclick="add_fields();">
<span>Invoice Date:<input type="date" value="<?php echo $fetch["invoice_date"]; ?>" name="invoice_date"></span>
<span>Invoice #:<input type="text" name="invoice_number" value="<?php echo $fetch["invoice_number"]; ?>" readonly></span>
<span>Select Customer:
<select name="to_user" class="form-control">
<option><?php echo $fetch["customer_id"]; ?></option>
<?php
include('database.php');
$sql = mysqli_query($connect, "SELECT * From customer");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option value='". $row['customer_id'] ."'>" .$row['customer_id'] ." - " .$row['customer_name'] ."</option>" ;
}
?>
</select>
</span>
</table>
<span>Grand Total<input type="text" name="grandtotal" id="grandtotal" value="<?php echo $fetch["grandtotal"]; ?>" readonly></span><br><br>
<span>Paid Amount<input type="text" name="paid" id="paid" value="<?php echo $fetch["paid"]; ?>"></span><br><br>
<span>Balance<input type="text" name="balance" id="balance" value="<?php echo $fetch["balance"]; ?>" readonly></span><br><br>
<input type="submit" name="send" value="Submit">
</form>
</body>
<script>
const table = document.getElementById('product_table');
table.addEventListener('input', ({ target }) => {
const tr = target.closest('tr');
const [product, price, quantity, width, height, total] = tr.querySelectorAll('input');
var size = width.value * height.value;
var rate = price.value * quantity.value;
if (size != "") {
total.value = size * rate;
}else{
total.value = rate;
}
totalPrice();
});
function add_fields() {
var row = document.createElement("tr");
row.innerHTML =
'<td><input type="text" name="product[]"></td>' +
'<td><input type="text" name="price[]"></td>' +
'<td><input type="text" name="quantity[]"></td>' +
'<td><input type="text" name="width[]" value="0"></td>' +
'<td><input type="text" name="height[]" value="0"></td>' +
'<td><input type="text" name="total[]" class="totalPrice" readonly></td>' +
'<td><input type="button" value="X" onclick="deleteRow(this)"/></td>';
table.appendChild(row);
}
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
totalPrice();
}
function totalPrice() {
var grandtotal = 0;
var paid = 0;
$(".totalPrice").each(function() {
grandtotal += parseFloat($(this).val());
paid = grandtotal;
});
$("#grandtotal").val(grandtotal);
$("#paid").val(paid);
}
$(document).ready(function() {
$('#paid').on('input', function() {
grandtotal = $("#grandtotal").val();
paid = $("#paid").val();
balance = parseFloat(grandtotal) - parseFloat(paid);
$("#balance").val(balance);
})
});
</script>
</html>
Update_invoice.php
<?php
include('database.php');
if (isset($_POST['send'])) {
$product = $_POST['product'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$width = $_POST['width'];
$height = $_POST['height'];
$total = $_POST['total'];
$customer_id = $_POST['to_user'];
$invoice_date = $_POST['invoice_date'];
$invoice_number = $_POST['invoice_number'];
$grandtotal = $_POST['grandtotal'];
$paid = $_POST['paid'];
$balance = $_POST['balance'];
$amount_status = "";
if ($grandtotal == $paid) {
$amount_status = "Paid";
} elseif ($grandtotal == $balance) {
$amount_status = "Due";
} else {
$amount_status = "Partial";
}
// Start of Updating data to invoice_order table
for ($i = 0; $i < count($_POST['total']); $i++) {
if ($i <> count($_POST['total'])) {
$sql = "UPDATE invoice_order SET invoice_number = '$invoice_number' , product = '$_POST['product'][$i]', price = '$_POST['price'][$i]' , quantity = '$_POST['quantity'][$i]', width = '$_POST['width'][$i]' , height = '$_POST['height'][$i]' , total = '$_POST['total'][$i]' WHERE invoice_number='$invoice_number' ";
$query = mysqli_query($connect, $sql);
if ($query) {
header('location: list_invoice.php');
} else {
echo "Unable to enter records in invoice_order table";
}
}
}
// End of updating data to invoice_order table
// Start of updating data to invoice table
$sql2 = "UPDATE invoice SET customer_id = '$customer_id', grandtotal = '$grandtotal', invoice_number = '$invoice_number', invoice_date = '$invoice_date', paid = '$paid', balance = '$balance', amount_status = '$amount_status' WHERE invoice_number='$invoice_number' ";
$query2 = mysqli_query($connect, $sql2);
if ($query2) {
header('location: list_invoice.php');
} else {
echo "Unable to enter record in invoice table";
}
// End of updating data to invoice table
}
?>
The approach you are using is not the preferred way of doing the job. Use mysql prepare statement. This will make the code clean, easy to read and secured. Here is the link you can refer Mysql Prepared Statement in PHP

Data not being able to be saved into database PHP

I have this problem here where when I press the Add button, it should save my selected choices into my table in database.
But when I press it, my table in database did not receive any data.
Did I do something wrong with my code? I need to find a right way to save the data into my designated table.
Any help would be greatly appreciated. Thanks
<?php
include "..\subjects\connect3.php";
//echo "Connection successs";
$query = "SELECT * FROM programmes_list";
$result = mysqli_query($link, $query);
?>
<form name = "form1" action="dropdownindex.php" method="post">
<table>
<tr>
<td>Select Pragramme</td>
<td>
<select id="programmedd" onChange="change_programme()">
<option>select</option>
<?php while($row=mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row["ID"]; ?>"><?php echo $row["programme_name"]; ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Select intake</td>
<td>
<div id="intake">
<select>
<option>Select</option>
</select>
</div>
</td>
</tr>
<tr>
<td>Select Subjects</td>
<td>
<div id="subject">
<select >
<option>Select</option>
</select>
</div>
</td>
</tr>
<input type="submit" value="Add" name="send">
</table>
</form>
<?php
if(isset($_POST['Add'])) {
//print_r($_POST);
$course1 = implode(',',$_POST['programmedd']);
$course2 = implode(',',$_POST['intake']);
$course3 = implode(',',$_POST['subject']);
$db->query("INSERT INTO programmes(programme_registered, intake_registered, subjects_registered)
VALUES (' ".$course1." ',' ".$course2." ', ' ".$course3." ' )");
echo $db->affected_rows;
}
?>
<script type="text/javascript">
function change_programme()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?programme="+document.getElementById("programmedd").value,false);
xmlhttp.send(null);
document.getElementById("intake").innerHTML=xmlhttp.responseText;
if(document.getElementById("programmedd").value=="Select"){
document.getElementById("subject").innerHTML="<select><option>Select</option></select>";
}
}
function change_intake()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?intake="+document.getElementById("intakedd").value,false);
xmlhttp.send(null);
document.getElementById("subject").innerHTML=xmlhttp.responseText;
}
</script>
//ajax.php
<?php
$dbhost = 'localhost' ;
$username = 'root' ;
$password = '' ;
$db = 'programmes' ;
$link = mysqli_connect("$dbhost", "$username", "$password");
mysqli_select_db($link, $db);
if (isset($_GET["programme"])) {
$programme = $_GET["programme"];
} else {
$programme = "";
}
if (isset($_GET["intake"])) {
$intake = $_GET["intake"];
} else {
$intake = "";
}
if ($programme!="") {
$res=mysqli_query($link, "select * from intakes where intake_no = $programme");
echo "<select id='intakedd' onChange='change_intake()'>";
echo "<option>" ; echo "Select" ; echo "</option>";
while($value = mysqli_fetch_assoc($res)) {
echo "<option value=".$value['ID'].">";
echo $value["intake_list"];
echo "</option>";
}
echo "</select>";
}
if ($intake!="") {
$res=mysqli_query($link, "select * from subject_list where subject_no = $intake");
echo "<select>";
echo "<option>" ; echo "Select" ; echo "</option>";
while($value = mysqli_fetch_assoc($res)) {
echo "<option value=".$value['ID'].">";
echo $value["subjects"];
echo "</option>";
}
echo "</select>";
}
?>
Your error is where you check for button click.
Change to this
If(isset($_POST['send']))
For future purposes and references, When doing the above, include the name attribute from your button and not the value attribute

PHP SQL Insert text value into database

I am working on an online shopping cart project, which requires me to be able to add a custom text input field to each item that is added to the shopping cart. However, when I attempt to insert the information for each item in the card into a database, I cannot figure out how to pass the itemtext value into my INSERT statement. How would I go about being able to pass the itemtext value from the initial item list into my database for Orderitems? The itemtext input is on line 170, and I want to pass it into the INSERT statement seen on line 83.
<?php
session_start();
$user = $_SESSION['user'];
if(!isset($user)) {
header("Location:userlogin.php");
}
$cart = $_COOKIE['WSC'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("WSC", $new_cart, $expire);
header("Location:order.php");
}
if(isset($_POST['PlaceOrder'])) {
$email = $user;
$orderdate = date('m/d/Y');
$ordercost = $_POST['ordercost'];
$ordertype = $_POST['ordertype'];
$downcost = $_POST['downcost'];
$cardtype = $_POST['cardtype'];
$cardnumber = $_POST['cardnumber'];
$cardsec = $_POST['cardsec'];
$cardexpdate = $_POST['cardexpdate'];
$orderstatus = "Pending";
if($ordertype=="") {
$ordertypeMsg = "<br><span style='color:red;'>You must enter an order type.</span>";
}
if($cardtype=="") {
$cardtypeMsg = "<br><span style='color:red;'>You must enter a card type.</span>";
}
if($cardnumber=="") {
$cardnumberMsg = "<br><span style='color:red;'>You must enter a card number.</span>";
}
if($cardsec=="") {
$cardsecMsg = "<br><span style='color:red;'>You must enter a security code.</span>";
}
if($cardexpdate=="") {
$cardexpdateMsg = "<br><span style='color:red;'>You must enter an expiration date.</span>";
}
else {
include ('includes/dbc_admin.php');
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
$sql = "SELECT orderid FROM Orders";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$myid = $row[orderid];
}
$itemnumber = 1;
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$itemtext = $_POST['itemtext'];
$sql= "INSERT INTO OrderItems (orderid, itemnumber, itemid, itemtype, media, itemtext, price)
VALUE ('$myid', '$itemnumber', '$row[itemid]', '$row[itemtype]', '$row[media]', '$itemtext[itemnumber]', '$row[price]')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
}
$itemnumber++;
}
$inserted = "<h2>Thank You!</h2> <h3>Your order has been placed.</h3>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Williams Specialty Company</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function validateForm() {
var ordercost = document.form1.ordercost.value;
var downcost = document.form1.downcost.value;
var ordertype = document.form1.ordertype.value;
var cardtype = document.form1.cardtype.value;
var cardnumber = document.form1.cardnumber.value;
var cardsec = document.form1.cardsec.value;
var cardexpdate = document.form1.cardexpdate.value;
var ordertypeMsg = document.getElementById('ordertypeMsg');
var cardtypeMsg = document.getElementById('cardtypeMsg');
var cardnumberMsg = document.getElementById('cardnumberMsg');
var cardsecMsg = document.getElementById('cardsecMsg');
var cardexpdateMsg = document.getElementById('cardexpdateMsg');
if(ordertype == ""){ordertypeMsg.innerHTML = "You must enter an order type."; return false;}
if(cardtype == ""){cardtypeMsg.innerHTML = "You must enter a card type."; return false;}
if(cardnumber == ""){cardnumberMsg.innerHTML = "You must enter a card number."; return false;}
if(cardsec == ""){cardsecMsg.innerHTML = "You must enter a security code."; return false;}
if(cardexpdate == ""){cardexpdateMsg.innerHTML = "You must enter an expiration date."; return false;}
}
</script>
</head>
<body>
<?php include('includes/header.inc'); ?>
<?php include('includes/nav.inc'); ?>
<div id="wrapper">
<?php include('includes/aside.inc'); ?>
<section>
<h2>My Cart</h2>
<table width="100%">
<tr>
<th>Catalog ID</th>
<th>Item Name</th>
<th>Price</th>
<th>Item Text</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['WSC'];
if ($cart) {
$i = 1;
$ordercost;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td align="left">';
echo $row['itemid'];
echo '</td>';
echo '<td align="left">';
echo $row['itemname'];
echo '</td>';
echo '<td align="left">';
echo $row['price'];
$ordercost+=$row['price'];
$downcost = $ordercost / 10;
echo '</td>';
echo '<td align="left">';
echo '<p><input type="text" id= "itemtext" name="itemtext"></p>';
echo '</td>';
echo '<td align="left">';
echo 'Remove From Cart';
echo '</td>';
echo '</tr>';
}
$i++;
}
}
?>
</table><br />
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="submit" name="clear" value="Empty Shopping Cart">
</form>
<?php if(isset($inserted)) {echo $inserted;} else{ ?>
<form method="post" action="<?php echo $SERVER['PHP_SELF'] ?>" name="form1" onSubmit="return validateForm()">
<p>Total Price: <?php echo $ordercost;?> <input type="hidden" id="ordercost" name="ordercost" value="<?php echo $ordercost;?>"> </p>
<p>Down Cost: <?php echo number_format((float)$downcost, 2, '.', '');?> <input type="hidden" id="downcost" name="downcost" value="<?php echo number_format((float)$downcost, 2, '.', '');?>"> </p>
<p><label>Order Type:</label><br> <input type="text" id="ordertype" name="ordertype">
<?php if(isset($ordertypeMsg)) {echo $ordertypeMsg;} ?>
<br /><span id="ordertypeMsg" style="color:red"></span>
</p>
<p><label>Card Type:</label><br> <input type="text" id="cardtype" name="cardtype">
<?php if(isset($cardtypeMsg)) {echo $cardtypeMsg;} ?>
<br /><span id="cardtypeMsg" style="color:red"></span>
</p>
<p><label>Card Number:</label><br> <input type="text" id="cardnumber" name="cardnumber">
<?php if(isset($cardnumberMsg)) {echo $cardnumberMsg;} ?>
<br /><span id="cardnumberMsg" style="color:red"></span>
</p>
<p><label>Card Security Code:</label><br> <input type="text" id="cardsec" name="cardsec">
<?php if(isset($cardsecMsg)) {echo $cardsecMsg;} ?>
<br /><span id="cardsecMsg" style="color:red"></span>
</p>
<p><label>Card Expiration Date:</label><br> <input type="text" id="cardexpdate" name="cardexpdate">
<?php if(isset($cardexpdateMsg)) {echo $cardexpdateMsg;} ?>
<br /><span id="cardexpdateMsg" style="color:red"></span>
</p>
<p><input type="submit" name="PlaceOrder" value="Place Order"></p>
</form><?php }?>
</section>
</div>
<?php include('includes/footer.inc'); ?>
</body>
</html>
Update: This is your answer: change '$itemtext[itemnumber]' into '$itemtext'
This is going wrong because of the way you use quotes. (not the answer but you might want to think about it ;-) )
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
You should not use '$email' but -for example- ...VALUES ('".$email."',...
Learn more about this here: What is the difference between single-quoted and double-quoted strings in PHP?
On another note, your code is not safe. Please use: http://php.net/manual/en/function.mysql-real-escape-string.php
Example:
...VALUES ('".mysql_real_escape_string($email)."',...

Last record in database is being used rather than the record desired

I have an approval/denial user system that I created and I am running into an issue with it.
I first have to approve or deny the user. If that user is approved, their name is placed into a different section of the page called 'Approved Users'. Within this area I change the user's permission/group level. However, if I have more than one user in the approved user section, if I try to update a user, it updates the last record displayed no matter which user I try to change.
For example, if I had this and tried to update Rick's record, Bob's would be updated. Bob's record would be the last one in my database.
-Bob
-Tony
-Rick
Whenever I approve the record, the correct user's record gets changed. It is only when I try to change the group/permission part, it does not work right.
Starting here it works..
$con = mysqli_connect("localhost", "", "", "");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
$pending_email = $row['email'];
?>
<form action="" method="POST" id="status">
<input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id'/>
<?php
if ($pending_firstname == true) {
echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" .
"Username - ". $pending_username . "</br></br>"
//echo print_r($_POST);
?>
<button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button>
<button class="deny" type="submit" form="status" name="deny" value="<?=$pending_id;?>">Deny</button>
</form><br><br><br>
<?php
;} else {
echo "There are no Pending Requests at this time.";
}
}
}
}
?>
<hr><br>
End of Pending users and up to this point it works and uses the correct user that was clicked. Now at this point when I try to update the user's info it updated the first user displayed...
<h2>Approved User Requests</h2><br>
<div id="success" style="color: red;"></div><br>
<?php
$con2 = mysqli_connect("localhost", "", "", "");
$run2 = mysqli_query($con2,"SELECT * FROM user_requests ORDER BY id DESC");
$runUsers2 = mysqli_query($con2,"SELECT * FROM users ORDER BY id DESC");
$numrows2 = mysqli_num_rows($run2);
if( $numrows2 ) {
while($row2 = mysqli_fetch_assoc($run2)){
if($row2['status'] == "Approved"){
//var_dump ($row2);
$approved_id = $row2['user_id'];
$approved_firstname = $row2['firstname'];
$approved_lastname = $row2['lastname'];
$approved_username = $row2['username'];
$approved_email = $row2['email'];
if ($approved_firstname == true) {
echo "Name - ". $approved_firstname . " " . $approved_lastname . "</br>" .
"Username - ". $approved_username . "</br></br>"
?>
<div class="change_group_button">
<a class="change_group" href="javascript:void(0)">Change User Permission</a>
</div><br>
<div id="light" class="change_group_popup">
<a class="close" href="javascript:void(0)">Close</a>
<div class="group_success" style="color: red;"></div><br>
<form id="update_group" action="" method="POST" accept-charset="utf-8">
<div class="field">
<label for="group">Group</label>
<input type="hidden" value="<?php echo $approved_id; ?>" id="approved_id" name="id" />
<input type="hidden" value="<?php echo $approved_firstname; ?>" id="approved_firstname" name="firstname" />
<input type="hidden" value="<?php echo $approved_lastname; ?>" id="approved_lastname" name="lastname" />
<input type="hidden" value="<?php echo $approved_username; ?>" id="approved_username" name="username" />
<input type="hidden" value="<?php echo $approved_email; ?>" id="approved_email" name="email" />
<select id='group_id' name='group' required>
<option value=''><?php echo htmlentities($group); ?></option>
<option value="1">Bench</option>
<option value="2">Spectator</option>
<option value="3">Team Member</option>
<option value="4">Commissioner</option>
</select>
</div>
<input type="submit" value="submit" name="group">
</form>
AJAX that I use to update the info..
//AJAX call for Approving the status
$(document).ready(function () {
$('.approve').click(function () {
$.ajax({
url: 'userRequest_approve.php',
type: 'POST',
data: {
id: $(this).val(), //id
status: 'Approved' //status
},
success: function (data) {
//do something with the data that got returned
$("#success").fadeIn();
$("#success").show();
$('#success').html('User Status Changed!');
$('#success').delay(5000).fadeOut(400);
},
//type: 'POST'
});
return false;
});
});
//AJAX call for updating the group
$(document).ready(function () {
$('#update_group').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: 'user_group_update.php',
type: 'POST',
data: {
id: $("#approved_id").val(), //id
firstname: $("#approved_firstname").val(), //firstname
lastname: $("#approved_lastname").val(), //lastname
username: $("#approved_username").val(), //username
email: $("#approved_email").val(), //email
// update_group: $("#group_id").val() //group level
update_group: $(this).find( "#group_id option:selected" ).val()
},
success: function (data) {
//do something with the data that got returned
$(".group_success").fadeIn();
$(".group_success").show();
$('.group_success').html('User Permission Level Changed!');
$('.group_success').delay(5000).fadeOut(400);
alert(data);
},
error: function(jqXHR, textStatus,errorThrown )
{
// alert on an http error
alert( textStatus + errorThrown );
}
});
return false;
});
});
I believe the entire issue has to do with the id, but I don't get what is wrong with the id I am getting. Does anyone see anything I am doing incorrectly that is causing this?
In the first part of your code, I found a few syntax errors. Corrected to:
<?php
$con = mysqli_connect("localhost", "", "", "");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
$pending_email = $row['email'];
echo "<form action='' method='POST' id='status'>\r\n";
echo "<input type='hidden' name='id' value='$pending_id' id='pending_id' />\r\n";
if ($pending_firstname == true) {
echo "Name - $pending_firstname $pending_lastname</br>\r\n";
echo "Username - $pending_username</br></br>\r\n";
echo "<button class='approve' type='submit' form='status' name='approve' value='$pending_id'>Approve</button>\r\n";
echo "<button class='deny' type='submit' form='status' name='deny' value='$pending_id'>Deny</button>\r\n";
echo "</form><br><br><br>\r\n";
} else {
echo "There are no Pending Requests at this time.";
}
}
}
}
?>
Second, am concerned about your double query. I would advise running the query, iterate over the result, and then run the second query. Should also free the results after each query just to be safe. If this is in the same page, I would also not create a new connection.
If you could post any error or results form your Console, could expand upon my answer.

INSERT a row per array object

I am in the process of creating a document association tool whereby users can associate documents to a ticket from a pre-existing list of documents.
Thanks to the help of Alberto Ponte I was able to construct the initial radio box system (originally checkbox, changed for obvious reasons) from this question: Separate out array based on array data
Now that I have the radio buttons presenting correctly I am trying to get the data inserted into a MySQL with a row for each document. Following on from this I want to have it look up the table for each object and see if there is an existing entry and update that rather than inset a duplicate entry.
Apologies in advance for the soon to be depreciated code and I will be correcting the code going forward, however that is a much bigger task than I currently have time for.
Also apologies if the code is considered messy. I'm not fantastic at PHP and not too hot on best practices. Any quick pointers are always welcome.
Display code:
<?php
include "../includes/auth.php";
include "../includes/header.php";
## Security ########################################################
if ($company_id != 1 OR $gid < 7) {
echo' <div class="pageheader">
<div class="holder">
<br /><h1>Access Denied <small> Your attempt has been logged</small></h1>
</div>
</div>
';
exit();
}
// GET Values ###################################################
$jat_id = intval($_GET['id']);
$div_id = intval($_GET['div_id']);
## Page Start ########################################################
echo '
<div class="pageheader">
<div class="holder">
<br /><h1>Clovemead Job Management Platform<small> Welcome...</small></h1>
</div>
</div>
<div class="well5" style="width:1000px !important;">
<h3>Create Document Association</h3>
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>
<form method="post" action="create-doc-assoc-exec.php">
<input type="hidden" value="'.$doc_id.'" name="doc_id">
<input type="hidden" value="'.$jat_id.'" name="jat_id">
<input type="hidden" value="'.$div_id.'" name="div_id">';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result400 = mysql_query($order4);
$_results = mysql_fetch_array($result400);
if (!$_results) {
echo '
<td><input type="radio" name="req0" value="2"></td>
<td><input type="radio" name="req0" value="1"></td>
<td><input type="radio" name="req0" value="0" checked ></td>';
} else {
foreach ($_results as $result400) {
$requirement = $_results['requirement'];
}
$name = "req".$doc_id;
echo '
<input type="hidden" value ="'.$name.'" name="name">
<td><input type="radio" name="'.$name.'" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>
<input type="submit" name="submit value" value="Create Document Association" class="btn success Large"></form>';
$order2 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$dbname = $row2['division_dbname'];
$order3 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type = $row3['type'];
$type2 = strtolower($type);
echo '
<input type="button" value="Back" onclick="window.location='./view-'.$type2.'.php?id='.$jat_id.''" class="btn primary Large">
';
}}
echo '
</div>';
include "../includes/footer.php";
?>
Execute Code:
<?php
include "../includes/dbconnect.php";
$name = $_POST['name'];
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$doc_id = intval($_POST['doc_id']);
$jat_id = intval($_POST['jat_id']);
$div_id = intval($_POST['div_id']);
$req = intval($_POST[$name]);
$req_blank = intval($_POST['req0']);
if ($req_blank == 0) {
$requirement = 0;
} elseif ($req_blank == 1) {
$requirement = 1;
} elseif ($req_blank == 2) {
$requirement = 2;
} elseif ($req == 0) {
$requirement = 0;
} elseif ($req == 1) {
$requirement = 1;
} elseif ($req == 2) {
$requirement = 2;
}
foreach ($doc_id as $doc_id2) {
$order = "INSERT INTO document_assoc (jat_id, dept_id, doc_id, requirement) VALUES ('$jat_id', '$div_id', '$doc_id2', '$requirement')";
$result = mysql_query($order);
$order1 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result1 = mysql_query($order1);
while ($row1 = mysql_fetch_array($result1)) {
$dbname = $row1['division_dbname'];
$order2 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$type = $row2['type'];
$type2 = strtolower($type);
if($result){
header("location:view-$type2.php?id=$jat_id&creation=success");
} else {
header("location:view-$type2.php?id=$jat_id&creation=failed");
}
}}
}
?>
A few reference points:
$doc_id is the ID of each document which is to be passed over as an array for use in a (i believe) foreach insert
$jat_id is the ticket id documents are being associated to
$div_id is the department the ticket is associated
And the radio boxes are to decider the requirement of each document. To be passed over inline with $doc_id
What I have tried:
After a fair bit of searching - finding nothing - rechecking my terminology and searching again I managed to find the suggestion of using base64_encode(serialize()) on the arrays but I could not get this to work.

Categories