PHP Form array has empty values when inserting into MySQL table - php

I'm having an issue inserting php form array values into a MySQL table. Right now the form itself pulls worker information from another table to populate the fields and their values. Right now there are only three workers that would populate those fields, however as more workers get added, there could be as many as 40. When I add just the first worker from the form, all the information inserts normally. However, when I add more than one, the title and employeeId fields are blank and I can't figure out why. Any help would be greatly appreciated.
Here is the form:
<form method = 'POST' action = 'addworkers.php'>
<?php
$sql2 = "select * from workers where companyId = 1";
$result2 = mysqli_query($conn,$sql2);
$numRows = mysqli_num_rows($result2);
$check = 0;
while($row2 = $result2->fetch_assoc()) {
$employeeId = $row2["id"];
$name = $row2["name"];
echo '<input type="checkbox" name="employeeId[]" value="' . $employeeId . '">';
echo "$name\n";
echo '<input type = "hidden" value="' . $companyId . '" name = "companyId[]"/>';
echo '<input type = "hidden" value="' . $jobNumber . '" name = "jobNumber[]"/>';
echo 'Site Title : <input type = "text" name = "title[]"/><br/>';
}
?>
<input type="hidden" name="count" value="<?php echo "$numRows"; ?>"/>
<input type = 'submit' value = 'SEND'/>
</form>
Then the addworkers.php code
require_once("dbConfig.php");
session_start();
$timestamp = date("Y-m-d");
if (isset($_SESSION['loginname'])) {
$companyId = isset($_POST['companyId']) ? $_POST['companyId'] : "" ;
$jobNumber = isset($_POST['jobNumber']) ? $_POST['jobNumber'] : "" ;
$employeeId = isset($_POST['employeeId']) ? $_POST['employeeId'] : "" ;
$title = isset($_POST['title']) ? $_POST['title'] : "" ;
foreach($title as $key=>$value){
if (!empty($value)) {
$query = "insert into `Jobs` (id, companyId, jobId, employeeId, siteTitle, dateAdded) values (NULL,'$companyId[$key]', '$jobNumber[$key]','$employeeId[$key]','$value','$timestamp')";
$result = mysqli_query($conn,$query);
}
}
} else {
echo "Error";
}
I changed the echo "Error" line but the output was clear.
It must be a problem with how the array is counted but I'm not sure how to fix it. in the form, if I check the boxes next to each row, all the information is entered into the table properly. If I only check the second and/or third line, it doesn't include the Site Title and the employeeId is reversed.
Here is the output of the form:
<form method = 'POST' action = 'insertworkers.php'>
<input type="checkbox" name="employeeId[]" value="1">Mike
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="checkbox" name="employeeId[]" value="2">Steve
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="checkbox" name="employeeId[]" value="3">Roger
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="hidden" name="count" value="3"/>
<input type = 'submit' value = 'SEND'/>
</form>
I also changed the foreach loop to a for loop since the array depth should be the same as all fields will be mandatory
require_once("dbConfig.php");
session_start();
$counter = "".$_POST["count"]."";
$timestamp = date("Y-m-d");
if ( isset( $_SESSION['loginname'] ) ) {
$companyId = isset($_POST['companyId']) ? $_POST['companyId'] : "" ;
$jobNumber = isset($_POST['jobNumber']) ? $_POST['jobNumber'] : "" ;
$employeeId = isset($_POST['employeeId']) ? $_POST['employeeId'] : "" ;
$title = isset($_POST['title']) ? $_POST['title'] : "" ;
for($i=0, $count = count($employeeId);$i<$count;$i++){
if (!empty($employeeId)) {
$query = "insert into `customerJobs` (id, companyId, jobId, employeeId, siteTitle, dateAdded) values (NULL,'$companyId', '$jobNumber','$employeeId[$i]','$title[$i]','$timestamp')";
$result = mysqli_query($conn,$query);
}
}
} else {
echo "Error";
}

Related

Display user selection in dropdown list

After the user select the CD, I'm trying to display a user's selection with editing so I'm displaying it in either textbox or dropdown list. As in the picture I can get Publisher to display in a textbox but for the dropdownlist it's showing as blank. I have try to $CDPub within the option value but it doesn't work.
<form method="get" action="UpdateCD.php">
<div align="center">
<div>Title <input type = "text" name = "CDTitle" value = "<?php echo $CDTitle; ?>" /></div></br>
<div>Year <input type = "text" name = "CDYear" value = "<?php echo $CDYear; ?>" /></div></br>
<div>Price <input type = "text" name = "CDPrice" value = "<?php echo $CDPrice; ?>" /></div></br>
<div>Category <input type = "text" name = "CDCat" value = "<?php echo $CDCat; ?>" /></div></br>
<div>Publisher <input type = "text" name = "CDPub" value = "<?php echo $CDPub; ?>" /></div></br>
Publisher
<select name="CDPub">
<option value= " ">
<?php
include 'database_conn.php'; //make db connection
if (! ( is_object($conn ) && ( get_class( $conn ) == 'mysqli' ))) {
die("DB connection failure.");
}
$rsCDpub = mysqli_query($conn, "SELECT nmc_publisher.pubName FROM nmc_publisher");
if ( !$rsCDpub ) {
die("No result from DB query."); //probably invalid SQL, table error
}
if ( $rsCDpub->num_rows < 1 ) {
die("No rows returned from DB query."); //query runs but nothing is found in DB to match
}
while($Catpubresult = mysqli_fetch_array($rsCDpub)){
echo "<option value='".$Catpubresult[0]."'>".$Catpubresult[0]."</option>";
//echo "<option value='".$Catpubresult[0]."'>".$Catpubresult[0]."</option>";
}
?></br></br>
<div><input type="submit" value="Update"></div>
</form>
You can do something like this:
// your code
while($Catpubresult = mysqli_fetch_array($rsCDpub)){
$option = "<option value='{$Catpubresult[0]}'";
if($Catpubresult[0] == $CDPub){
$option .= " selected='selected'";
}
$option .= ">{$Catpubresult[0]}</option>";
echo $option;
//echo "<option value='".$Catpubresult[0]."'>".$Catpubresult[0]."</option>";
}
// your code

how to use the current value of a select option inside input field

I'm using phpmyadmin in Xampp, where I have made two tables;
Table 1: Category with its attributes as cat_id and cat_name (where cat_id is a Primary Key)
Table 2: Item with its attributes as item_id, item_name, item_price ... cat_id (where item_id is a Primary Key and cat_id is a Foreign Key)
I have also made the correct relationship in phpmyadmin.
The problem is to use the value i.e. cat_id of the selected cat_name in a select tag inside php.
ps. Im aware of being a subject to SQL Injection.
PHP
<?php
require ('config.php');
if(isset($_POST['check']))
{
if(isset($_POST['button']))
{
$catname = $_POST['cat'];
$que1 = "SELECT * FROM category WHERE cat_name = '$catname'";
$res1 = mysql_query($que1);
$row = mysql_fetch_array($res1);
$cat_db = $row['cat_name'];
if($catname == $cat_db || $catname == "")
{
echo "Catergory: $catname already exits. Failed to be inserted.";
}
else
{
$que = "INSERT INTO category (cat_name) VALUES('$catname')";
$res = mysql_query($que);
echo "Catergory: $catname inserted successfully.";
}
die();
}
if(isset($_POST['item_name']))
{
$i_id = $_POST['item_id'];
$i_name = $_POST['item_name'];
$i_quan = $_POST['item_quantity'];
$i_size = $_POST['item_size'];
$i_price = $_POST['item_price'];
$cat_id = $_POST['cat_id'];
$que = "INSERT INTO item(item_name, item_quantity, item_size, item_price, cat_id) VALUES('$i_name','$i_quan','$i_size','$i_price', '$cat_id')";
$run = mysql_query($que);
if(!$run)
echo "Item Details failed to Update.";
}
}
?>
HTML
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "login.css">
</head>
<body>
<form action = "" method = "POST">
<p><label class = "field">Add Category:</label></p>
<input type = "text" name = "cat" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+" title = "Please enter your Category Name">
<button type= "submit" onclick = "location.href = '';" id = "savebutton" name = "button">Add Now</button>
<p><label class = "field">Add Item:</label></p>
<select name="cate">
<?php
$que1 = "SELECT * FROM category";
$res1 = mysql_query($que1);
while($row = mysql_fetch_array($res1))
{
$cat_id_db = $row['cat_id']; //use array over here
$cat_db = $row['cat_name']; //use array over here
?>
<option value="<?php echo $cat_id_db; ?>" ><?php echo $cat_db;?></option>
<?php } ?>
</select>
<?php
$que1 = "SELECT * FROM category WHERE cat_name = '$cat_db'"; //yahan masla hai bhai, how do i set '$cat_db' into a static variable?
$res1 = mysql_query($que1);
$row = mysql_fetch_array($res1);
$cat_db_id = $row['cat_id'];
?>
<p><label class = "field">Category ID:</label></p>
<input type = "text" name = "cat_id" value = "<?php echo $cat_id_db; ?>" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+"> <!-- this is the PROBLEM how do i use the value of a selected option ONLY? -->
<p><label class = "field">Item ID:</label></p>
<input type = "text" name = "item_id" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+"title = "Please enter your Item ID">
<p><label class = "field">Item Name:</label></p>
<input type = "text" name = "item_name" class = "textbox-300" pattern = "[a-zA-Z ]+"title = "Please enter your Item Name">
<p><label class = "field">Item Quantity:</label></p>
<input type = "text" name = "item_quantity" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+"title = "Please enter your Item Quantity">
<p><label class = "field">Item Size:</label></p>
<input type = "text" name = "item_size" class = "textbox-300" pattern = "[a-zA-Z0-9\.\, ]+"title = "Please enter your Item Size">
<p><label class = "field">Item Price:</label></p>
<input type = "text" name = "item_price" class = "textbox-300" pattern = "[a-zA-Z0-9\.\, ]+"title = "Please enter your Item Price">
<input type = "hidden" name = "check">
<input type = "submit" class = "button" name = "sub" value = "Save">
</form>
</body>
</html>
You will have the id of selected sub cat. so write a query to fetch the cat_id.
select * from sub_category where item_id = "posted id" and you will get the main category id.
Thanks to a member here i found the answer so im posting it here, in case anyone comes here looking for the same thing.
<select name="cate" onchange="changeInput(this.value);">
<?php //your php code here ?>
</select>
<p><label class = "field">Category ID:</label></p>
<input type = "text" name = "cat_id" id="cat_id" value = "change select to see me change" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+" title = "Please enter your Item Price">
</form>
<script>
var changeInput = function (val){
var input = document.getElementById("cat_id");
input.value = val;
}
</script>

How preserve my inputs values each time that I refresh my page?

I want to enter a name and a mark. As the mark entered is less or equal to 100, the names and marks entered is to be stored in an associative array when I click the submit button and it should request me to enter another name and marks. But if I enter a mark greater than 100 discarding the name entered, when I click the submit button, the php script should display me all the names and marks previously entered. Here what I have done but I am not getting the desired results. Please help. My code:
<?php
if(isset($_POST['lname']) && isset($_POST['marks'])){
$name = $_POST['lname'];
$marks = $_POST['marks'];
$lists = array($name => $marks);
foreach($lists as $name => $marks){
echo $name . '<br>';
echo $marks;
}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method = "POST">
Name:<br>
<input type = "text" name = "lname"><br><br>
Marks:<br>
<input type = "text" name = "marks"><br><br>
<input type = "submit" value = "Submit">
</form>
You can use session to achieve what you want, see this code:
<?php
session_start();
if(isset($_POST['lname']) && isset($_POST['marks'])){
if($_POST['marks'] > 100) {
$_SESSION['info'][] = array($_POST['lname'] => $_POST['marks']);
}
}
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
foreach($_SESSION['info'][$i] as $name => $marks){
echo '<p>' . $name . '<br>';
echo $marks . '</p>';
}
}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method = "POST">
Name:<br>
<input type = "text" name = "lname"><br><br>
Marks:<br>
<input type = "text" name = "marks"><br><br>
<input type = "submit" value = "Submit">
</form>
You should read some docs about session:
http://php.net/manual/en/intro.session.php
You are posting name and your server side is looking for lname

Cant update values in mysql database php

I am trying to update a record on my admin mysql table. But still no changes when i try this method.. I can't see the problem wth this code..
Info.php
<?php
$query = "SELECT * from admin where username = '{$_SESSION['login_user']}'";
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result))
{
echo '<input type="text" class="form-control" name="user_id" disabled value='.$row['user_id'].'>';
echo '<input type="text" class = "form-control" name = "lastname" value='.$row['lname'].'>';
echo '<input type="text" class = "form-control" name = "firstname" value='.$row['fname'].'>';
echo '<input type="text" class = "form-control" name = "middlename" value='.$row['mname'].'>';
echo '<input type="text" class = "form-control" name = "address" value='.$row['address'].'>';
echo '<input type="text" class = "form-control" name = "contact" value='.$row['contact'].'>';
echo '<input type="text" class = "form-control" name = "email_add" value='.$row['email_add'].'>';
echo '<input type="text" class = "form-control" name = "username" value='.$row['username'].'>';
echo '<input type="password" class = "form-control" name = "password" value='.$row['password'].'>';
echo '<input type="password" class = "form-control" name = "confirmPassword" value='.$row['conf_pass'].'>';
}?>
<button type="submit" class="btn btn-primary" name="update">Submit</button>
update.php ---- I don't know what's the problem with it.
<?php
include('pgconnect.php');
if(isset($_GET['update'])){
$acctid = $_GET['user_id'];
$lname = $_GET['lastname'];
$fname = $_GET['firstname'];
$mname = $_GET['middlename'];
$address = $_GET['address'];
$contact = $_GET['contact'];
$email = $_GET['email_add'];
$user = mysql_real_escape_string($_GET['username']); # use whatever escaping function your db requires this is very important.
$pass = mysql_real_escape_string($_GET['password']);
$confpass = mysql_real_escape_string($_GET['confirmPassword']);
$sql = "UPDATE admin SET lname='$lname', fname='$fname', mname ='$mname', address='$address' contact = $contact, email_add = '$email', username ='$user',password = '$pass', conf_pass = '$confpass' where user_id = '$acctid'";
$result = mysqli_query($conn,$sql);
echo "$sql";
if($result){
echo"Succesully Updated!";
}
else
{
echo"Cannot be Updated!";
}
mysqli_close($conn);
}?>
To understand the mechanism behind forms:
index.html:
<form action="update.php?param=234" method="post">
<input type="text" name="firstfield" />
<button name="update">Submit</button>
</form>
update.php:
<?php
echo $_GET['param']; //should output 234
echo $_POST['firstfield']; //should output whatever you put in your textfield
var_dump($_POST['update']); //should return something
as you noticed, the parameter after ? in your action is passed as GET value and all the other values are POST values.

SQL Update Query not updating records

I have a list of games that when clicked lead to a form that allows users to edit records before updating them.
Here is the Edit Games page;
<?php
$gameID = isset($_GET['gameID']) ? $_GET['gameID'] : '';
$gameYear = isset($_GET['gameYear']) ? $_GET['gameYear'] : '';
$gamePrice = isset($_GET['gamePrice']) ? $_GET['gamePrice'] : '';
$gameName = isset($_GET['gameName']) ? $_GET['gameName'] : '';
$sql = "SELECT * FROM game WHERE gameName = $gameName";
$queryresult = mysqli_query($conn, $sql)
or die (mysqli_error($conn));
$row = mysqli_fetch_assoc($queryresult);
$gameID = $row['gameID'];
$gameYear = $row['gameYear'];
$gamePrice = $row['gamePrice'];
$gameName = $row['gameName'];
?>
<div id="form">
<form action="updateGame.php" id="Update" method="get">
<label> Game ID
<input id="text" name="id" value = "<?php echo $gameID; ?>" />
</label>
<label> Year
<input type = "text" name = "year" value = "<?php echo $gameYear; ?>" />
</label>
<label> Price
<input type = "text" name = "price" value = "<?php echo $gamePrice; ?>" />
</label>
<label> Name
<input type = "text" name = "name" value = "<?php echo $gameName; ?>" />
</label>
<input type = "submit" value = "Update">
Here is the update page that runs when the submit button is clicked;
<?php
$gameID = isset($_GET['gameID']) ? $_GET['gameID'] : '';
$gameYear = isset($_GET['gameYear']) ? $_GET['gameYear'] : '';
$gamePrice = isset($_GET['gamePrice']) ? $_GET['gamePrice'] : '';
$gameName = isset($_GET['gameName']) ? $_GET['gameName'] : '';
$sql = "UPDATE game SET gameYear = '$gameYear', gamePrice = '$gamePrice', gameName = '$gameName' WHERE gameID = '$gameID'";
mysqli_query($conn, $sql)
or die (mysqli_error($conn));
mysqli_close($conn);
echo "Updated";
?>
The edit games page works and I can edit the records, when I press the submit button it comes up with the echo statement saying the record was updated, however, no changes happen and I'm not sure why.
Your form uses name="id", not name="gameID", so your $_GET['gameID'] variable is not set on any of your requests, but $_GET['id'] is. Update your form or your GET page, so that the names match.
You've forgot to append the variables in your query. I should be like this:
$sql = "UPDATE game SET gameYear = '".$gameYear."', gamePrice = '".$gamePrice."', gameName = '".$gameName."' WHERE gameID = '".$gameID."'";

Categories