I am trying to run a php upload which checks to see if a serial number already exists then if it doesnt submits data.
so :
Submit form --> PHP Checks DB for Duplicate Serial number --> If Serial number Does not Exist then post data // If Does Exist ignore input
However what ever i try doesnt seem to work. The following is my code but no matter what i do it submits the data even though the serial number already exists.
Form:
<form id="form1" action="senddata.php" name="form1" method="post">
<table class="table2" cellpadding="0" cellspacing="0">
<tr><td colspan="3"><input type="button" onClick="update()" value="Get Details"></td></tr>
<tr>
<td><label for="description">Description:</label></td>
<td><input tabindex="0" required type="text" name="description" id="description"></td>
</tr>
<tr>
<td><label for="nameofcomputer">Computer Code:</label></td>
<td><input tabindex="1" required type="text" name="nameofcomputer" id="nameofcomputer"></td>
</tr>
<tr>
<td><label for="make">Make:</label></td>
<td><input tabindex="2" required type="text" name="make" id="make"></td>
</tr>
<tr>
<td><label for="model">Model:</label></td>
<td><input tabindex="3" required type="text" name="model" id="model"></td>
</tr>
<tr>
<td><label for="serial">Serial Number:</label></td>
<td><input tabindex="4" required type="text" name="serial" id="serial"></td>
</tr>
<tr>
<td><label for="inputname">Your Name: </label></td>
<td><input tabindex="5" required id="inputname" name="inputname">
</td>
</tr>
</table>
<input required type="submit" name="submit" id="submit" value="Submit">
</form>
PHP
$desc=$_POST['description'];
$code=strtoupper($_POST['nameofcomputer']);
$make=$_POST['make'];
$model=$_POST['model'];
$serial=strtoupper($_POST['serial']);
$user=$_POST['inputname'];
$type='1';
$org='-1';
$control = "8670";
$now = new DateTime(null, new DateTimeZone('Europe/London'));
$date = $now->format('Y-m-d H:i:s');
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$dupe = sqlsrv_query($conn, "SELECT * FROM Asset WHERE Serial_Number = '$serial'");
$num_rows = sqlsrv_num_rows($dupe);
if ($num_rows == 0) {
$tsql = "INSERT INTO Asset (Name, Asset_Type_ID, Ref_Code, Owner_Organisation_ID, Make, Model, Serial_Number, Current_Location, Start_Date)
VALUES ('$desc', '$type', '$code', '$org', '$make', '$model', '$serial', '$user', '$date')";
sqlsrv_query( $conn, $tsql);
echo "Asset Uploaded";
} else {
echo 'Error! Already on our database!';
}
Any help to get this working is appreciated.
I replaced
$dupe = sqlsrv_query($conn, "SELECT Serial_Number FROM Asset WHERE Serial_Number = '$serial'");
with
$dupe = sqlsrv_query($conn, "SELECT Serial_Number FROM Asset WHERE Serial_Number = '$serial'", array(), array("Scrollable"=>"buffered"));
and it worked perfectly.
Thanks to those who helped me figure out where the code was going wrong.
Related
I set up an HTML with a form that would send the information over to a PHP page. Then the PHP would run through it and send it to my DB. I set it the database up in cPanel. I have another part to the code that searches for the item and that works. I just don't get why the query statement in this isn't pulling the information.
The error that I get is "An error has occurred. The item was not added." which I have set up after the query line. I can't seem to figure out why.
Here is the code:
html:
<form action="insert_product.php" method="post">
<table border="0">
<tr>
<td>ShoeName</td>
<td><input type="text" name="ShoeName" maxlength="13" size="13"></td>
</tr>
<tr>
<td>Price</td>
<td> <input type="text" name="Price" maxlength="7" size="7"></td>
</tr>
<tr>
<td>ProductID</td>
<td> <input type="text" name="ProductID" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Size</td>
<td><input type="text" name="Size" maxlength="7" size="7"></td>
</tr>
<tr>
<td>ShoeType</td>
<td><input type="text" name="ShoeType" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Brand</td>
<td><input type="text" name="Brand" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Color</td>
<td><input type="text" name="Color" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Rating</td>
<td><input type="text" name="Rating" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" name="Description" maxlength="40" size="40"></td>
</tr>
<tr>
<td>ImageName</td>
<td><input type="text" name="ImageName" maxlength="7" size="7"></td>
</tr>
<tr>
<td>StockAmount</td>
<td><input type="text" name="StockAmount" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
php:
<?php
// create short variable names
$ShoeName=$_POST['ShoeName'];
$Price=$_POST['Price'];
$ProductID=$_POST['ProductID'];
$Size=$_POST['Size'];
$ShoeType=$_POST['ShoeType'];
$Brand=$_POST['Brand'];
$Color=$_POST['Color'];
$Rating=$_POST['Rating'];
$Description=$_POST['Description'];
$ImageName=$_POST['ImageName'];
$StockAmount=$_POST['StockAmount'];
if (!$ShoeName || !$Price || !$ProductID || !$Size || !$ShoeType || !$Brand || !$Color || !$Rating || !$Description || !$ImageName || !$StockAmount) {
echo "You have not entered all the required details.<br />"
."Please go back and try again.";
exit;
}
if (!get_magic_quotes_gpc()) {
$ShoeName = addslashes($ShoeName);
$Price = doubleval($Price);
$ProductID = addslashes($ProductID);
$Size = addslashes($Size);
$ShoeType = addslashes($ShoeType);
$Brand = addslashes($Brand);
$Color = addslashes($Color);
$Rating = doubleval($Rating);
$Description = addslashes($Description);
$ImageName = addslashes($ImageName);
$StockAmount = doubleval($StockAmount);
}
# $db = new mysqli('localhost', 'admin', '(pass)', 'KicksUnlimited');
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "INSERT INTO product".'(ShoeName, Price, ProductID, Size, ShoeType, Brand, Color, Rating, Description, ImageName, StockAmount)'."values
('".$ShoeName."', '".$Price."', '".$ProductID."', '".$Size."', '".$ShoeType."', '".$Brand."', '".$Color."', '".$Rating."', '".$Description."', '".$ImageName."', '".$StockAmount."')";
$result = $db->query($query);
if ($result) {
echo $db->affected_rows." shoe inserted into database.";
} else {
echo "An error has occurred. The item was not added.";
}
$db->close();
?>
Test:
type query in cpanel with values not variable.
Use print $ShoeName=$_POST['ShoeName']; in front of every $_POST[] and on the end print exit; It is to control that value coming from Form.
Comment all between variables $_POST[] and INSERT INTO .....
Control quote. It is mess of quote, double, single, it does not need. And control if it is need quote around every values.
Sorry, I have not time to do all that for to find for sure error.
Do it yourself because it is the best way of learning.
I am currently making a system for a client database management. There are four tables in mySQL for this system, which are; admin, staff, client, and project. The project table has one foreign key from the client table, which is the clientid.
Now, I have made forms for all these tables so that the user can input the data into them. Weirdly, the only form that can be updated successfully is the staff one. Both the client and project forms cannot be updated at all. It returns as successful, but the data are not altered.
Below is the staff update code.
<?php
include 'database.php';
$staffid = $_GET['staffid'];
$sql = "SELECT * FROM staff WHERE staffid='$staffid'";
$result = mysqli_query($conn,$sql);
while ($row=mysqli_fetch_array($result)){
$staffname = $row['staffname'];
$staffemail = $row['staffemail'];
$staffphone = $row['staffphone'];
}
if(isset($_POST['submit'])){
$staffname = $_POST['staffname'];
$staffemail = $_POST['staffemail'];
$staffphone = $_POST['staffphone'];
$sql = "UPDATE staff SET
staffname='$staffname',staffemail='$staffemail',staffphone='$staffphone' WHERE staffid='$staffid'";
$result = mysqli_query($conn,$sql);
if($result){
echo "<table><td><tr><h4>Record has been updated successfully!<br></tr></td></h4></table>";
}
else {
echo "<h4>Record has <b>NOT</b> been updated successfully<br></h4>";
}
}
?>
<form action="" method="post">
<table class ="table1">
<tr>
<td>Staff Name:</td> <td><input type="text" name="staffname" size="50" value="<?php echo $staffname;?>"></td>
</tr>
<tr>
<td>Staff Email:</td> <td><input type="text" name="staffemail" size="50" value="<?php echo $staffemail;?>"></td>
</tr>
<tr>
<td>Staff Phone No:</td> <td><input type="text" name="staffphone" size="50" value="<?php echo $staffphone;?>"></td>
</tr>
<td><input type="submit" value="Update" name="submit"> <input type="button" value="View" name="view" onclick='location.href="viewstaff.php"'></td>
</table>
</form>
Okay now is the update code for the client table.
<?php
include 'database.php';
$clientid = $_GET['clientid'];
$sql = "SELECT * FROM client WHERE clientid='$clientid'";
$result = mysqli_query($conn,$sql) or die ("Error in query: $query. ".mysqli_error());
while ($row=mysqli_fetch_array($result)){
$clientid = $row['clientid'];
$clientname = $row['clientname'];
$clientno = $row['clientno'];
$clientemail = $row['clientemail'];
$clientadd = $row['clientadd'];
}
if(isset($_POST['submit'])){
$clientid = $row['clientid'];
$clientname = $row['clientname'];
$clientno = $row['clientno'];
$clientemail = $row['clientemail'];
$clientadd = $row['clientadd'];
$sql = "UPDATE client SET clientid='$clientid',clientname='$clientname',clientno='$clientno',clientemail='$clientemail',clientadd='$clientadd' WHERE clientid='$clientid'";
$result = mysqli_query($conn,$sql) or die ("Error in query: $query. ".mysqli_error());
if($result){
echo "<table><td><tr><h4>Record has been updated successfully!<br></tr></td></h4></table>";
}
else {
echo "<h4>Record has <b>NOT</b> been updated successfully<br></h4>";
}
}
?>
<form action="" method="post">
<table class ="table1">
<tr>
<td>Client ID:</td> <td><input type="text" name="clientid" size="50" value="<?php echo $clientid;?>"></td>
</tr>
<tr>
<td>Client Name:</td> <td><input type="text" name="clientname" size="50" value="<?php echo $clientname;?>"></td>
</tr>
<tr>
<td>Client Phone No.:</td> <td><input type="text" name="clientno" size="50" value="<?php echo $clientno;?>"></td>
</tr>
<tr>
<td>Client Email:</td> <td><input type="text" name="clientemail" size="50" value="<?php echo $clientemail;?>"></td>
</tr>
<tr>
<td>Client Address:</td> <td><input type="text" name="clientadd" size="50" value="<?php echo $clientadd;?>"></td>
</tr>
<td><input type="submit" value="Update" name="submit"> <input type="button" value="View" name="view" onclick='location.href="viewclient.php"'></td>
</table>
</form>
Maybe I'm stupid or what but I've been trying to figure out the problem for 3 hours and I'm this close to crying lol. Been reading all the threads here about updating form but still, no answer. Hope that anyone here could help me. Thank you.
The code you use for the client table update uses this code:
if(isset($_POST['submit'])){
$clientid = $row['clientid']; // $row should be $_POST
$clientname = $row['clientname']; // $row should be $_POST
$clientno = $row['clientno']; // $row should be $_POST
$clientemail = $row['clientemail']; // $row should be $_POST
$clientadd = $row['clientadd']; // $row should be $_POST
But those $rows should be $_POST, else the updated data will be the same as the previous data (since $row is the result from the query SELECT * FROM client WHERE clientid='$clientid'). You do it correctly in the staff table update code:
if(isset($_POST['submit'])){
$staffname = $_POST['staffname'];
$staffemail = $_POST['staffemail'];
$staffphone = $_POST['staffphone'];
Please note that your your script is at risk of SQL Injection Attack. Have a look at what happened to Little Bobby Tables. Even if you are escaping inputs, its not safe!. Use prepared parameterized statements instead.
I am HR and new for Developing. I started doing program for HR management using PHP and Mysql. I want to add the names of atleast 5 employees in a single row of a column. I use bootstrap to get multiple values in a single field. But when I try to insert the values, only the last value is inserted.
<td>Distribute</td><td><input type="text" class="form-control" name="distribute[]"></td>
HTML Code:
<tr><td>Distribute</td><td><input type="text" class="form-control" name="distribute[]"></td></tr>
PHP to insert into mysql
$civil_id= $_POST['civil_id'];
$name= $_POST['name'];
$card_type = $_POST['card_type'];
$count = $_POST['count'];
$amt=$card_type * $count;
$avail_bal=$_POST['balance']- $amt;
$issue_year= $_POST['issue_year'];
$issue_month= $_POST['issue_month'];
$issue_date= $_POST['issue_date'];
$distribute= $_POST['distribute'];
$sql ="insert into group_phone
(civil_id,
name,
card_type,
count,
amt,
avail_bal,issue_year,issue_month,issue_date,distribute)values('$civil_id',
'$name',
'$card_type',
'$count',
'$amt',
'$avail_bal','$issue_year','$issue_month','$issue_date','$distribute')";
HTML
<script>
$(document).ready(function() {
$(".select2_single").select2({
placeholder: "Select Vehicle Plate Number",
allowClear: true
});
$(".select2_group").select2({});
$(".select2_multiple").select2({
maximumSelectionLength: 10,
placeholder: "With Max Selection limit 10",
allowClear: true
});
});
</script>
<form class="form-horizontal form-label-left" action="new_rechargecard.php" method="POST" ">
<table id="datatable" class="table table-striped table-bordered">
<tbody>
<tr>
<td width='100'>Employee Name: </td><td><input type="text" class="form-control" placeholder="0" name="name" value="<?php echo "$name";?>" ></td>
</tr>
<tr>
<td>Available Balance</td><td><input type="text" class="form-control" placeholder="0" name="balance" value=<?php echo $balance;?> > </td></tr>
<tr><td>Civil id</td><td><input type="text" class="form-control" placeholder="Civil ID Required" name="civil_id" value=<?php echo $pass_name;?> > </td></tr>
<!--<tr><td>Name</td><td><input type="text" class="form-control" name="name" value="<?php echo $name;?>" > </td></tr>-->
<tr><td width='250'>Card Type (1 KD or 2.5 KD or 5 KD)</td><td><input type="text" class="form-control" name="card_type"></td></tr>
<tr><td width='200'>Card Count</td><td><input type="text" class="form-control" name="count"></td></tr>
<tr><td>Issue Year</td><td><input type="text" class="form-control" name="issue_year" value="<?php echo date('Y'); ?>"></td></tr>
<tr><td>For the Month of</td><td><input type="text" class="form-control" name="issue_month" value="<?php echo date('M'); ?>"></td></tr>
<tr><td>Issue date</td><td><input type="text" class="form-control" name="issue_date"></td></tr>
<tr><td>Distribute</td><td><select name="distribute" class="select2_multiple form-control" tabindex="-1" multiple="multiple">
<option></option>
<option>Richard Marcus</option>
<option>Rowlant S Peter</option>
<option>David.K.Rumpell</option>
<option>John Mathew</option>
</select>
</td></tr>
<tr><td></td><td><input type="submit" class="btn btn-round btn-danger" value="Update" name="submit"></td></tr>
</tbody>
</table>
</form>
Change your code like this
<?php
/* First create mysql connection */
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "userlist";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
/* End */
$civil_id= $_POST['civil_id'];
$name= $_POST['name'];
$card_type = $_POST['card_type'];
$count = $_POST['count'];
$amt=$card_type * $count;
$avail_bal=$_POST['balance']- $amt;
$issue_year= $_POST['issue_year'];
$issue_month= $_POST['issue_month'];
$issue_date= $_POST['issue_date'];
$distribute= $_POST['distribute'];
$sql ="insert into group_phone
(civil_id,
name,
card_type,
count,
amt,
avail_bal,issue_year,issue_month,issue_date,distribute)values('".$civil_id."',
'".$name."',
'".$card_type."',
'".$count."',
'".$amt."',
'".$avail_bal."','".$issue_year."','".$issue_month."','".$issue_date."','".$distribute."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
MySQL table structure
-- Table structure for table userlist
CREATE TABLE IF NOT EXISTS `userlist` (
`civil_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`card_type` varchar(100) NOT NULL,
`count` int(11) NOT NULL,
`amt` int(11) NOT NULL,
`avail_bal` int(11) NOT NULL,
`issue_year` int(11) NOT NULL,
`issue_month` varchar(50) NOT NULL,
`issue_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`distribute` varchar(200) NOT NULL,
PRIMARY KEY (`civil_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Working Query (MySQL)
INSERT INTO `userlist` (`civil_id`, `name`, `card_type`, `count`, `amt`, `avail_bal`, `issue_year`, `issue_month`, `issue_date`, `distribute`) VALUES
(1, 'aman,suresh,mohan', 'POST', 10, 500, 50, 2016, 'March', '2017-02-01 06:46:16', 'Airtel,Idea,Vodafone');
Not sure if you have solved this, but you just need to do an arrayed distribute name in the form then use a built-in function to turn the array to string, some popular functions are serialize() or json_encode(). I prefer the latter because JavaScript can use it, but in terms of best practice, it is generally frowned upon to store an array into a database like this. I have found it is useful for one-time instances where targeted searching is not required now or in the future. I would use it very sparingly. In this instance you may want to create a separate table that stores the names separately and join them when you go to select them later.
Also, for my example, I have used PDO instead of mysqli_ but the principles are the same. Look into bind_param. Finally, I would look at creating some useful classes that will help clean up the script. The ones I have below are some basic examples.
/classes/User.php
# I would think about containing your script in a class, this is just
# a bare-bones example
class User
{
public function __construct(PDO $db)
{
$this->db = $db;
}
protected function getAmount($a, $b)
{
return $a*$b;
}
protected function getBalance($a,$b)
{
return $a-$b;
}
public function addUser($array)
{
$bind = array(
$_POST['civil_id'],
$_POST['name'],
$_POST['card_type'],
$_POST['count'],
$amt = $this->getAmount($_POST['card_type'],$_POST['count']),
$this->getBalance($_POST['balance'],$amt),
$_POST['issue_year'],
$_POST['issue_month'],
$_POST['issue_date'],
json_encode($_POST['distribute'])
);
$sql ="INSERT INTO group_phone
(civil_id,name,card_type,count,amt,avail_bal,issue_year,issue_month,issue_date,distribute)
values
(?,?,?,?,?,?,?,?,?,?)";
$query = $this->db->prepare($sql);
$query->execute($bind);
}
}
/classes/Database.php
# This would need to be filled out and made to work with yours
# This is demonstration purposes only
class Database
{
private static $con;
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
self::$con = new PDO("mysql:host=localhost;dbname=databasename;","username","password");
return self::$con;
}
}
/new_rechargecard.php
define('DS', DIRECTORY_SEPARATOR);
define('ROOT_DIR', __DIR__);
define('CLASSES', ROOT_DIR.DS.'classes');
# Create a class autoloader
spl_autoload_register(function($class){
$inc = CLASSES.DS.trim(str_replace('\\',DS,$class),DS).'.php';
if(file_exists($inc))
include_once($inc);
});
# Create db
$con = (new Database())->connect();
# Check for update
if(isset($_POST['action']) && $_POST['action'] == 'update_user') {
# Create user instance
$User = new User($con);
# Add into database
$User->addUser($_POST);
}
?>
Form HTML:
<form class="form-horizontal form-label-left" action="new_rechargecard.php" method="POST">
<input type="hidden" name="action" value="update_user" />
<table id="datatable" class="table table-striped table-bordered">
<tbody>
<tr>
<td width='100'>Employee Name: </td>
<td><input type="text" class="form-control" placeholder="0" name="name" value="<?php echo $name ?>" ></td>
</tr>
<tr>
<td>Available Balance</td>
<td><input type="text" class="form-control" placeholder="0" name="balance" value=<?php echo $balance ?> ></td>
</tr>
<tr>
<td>Civil id</td>
<td><input type="text" class="form-control" placeholder="Civil ID Required" name="civil_id" value=<?php echo $pass_name;?> ></td>
</tr>
<tr>
<td width='250'>Card Type (1 KD or 2.5 KD or 5 KD)</td>
<td><input type="text" class="form-control" name="card_type"></td>
</tr>
<tr>
<td width='200'>Card Count</td>
<td><input type="text" class="form-control" name="count"></td>
</tr>
<tr>
<td>Issue Year</td>
<td><input type="text" class="form-control" name="issue_year" value="<?php echo date('Y'); ?>"></td>
</tr>
<tr>
<td>For the Month of</td>
<td><input type="text" class="form-control" name="issue_month" value="<?php echo date('M'); ?>"></td>
</tr>
<tr>
<td>Issue date</td>
<td><input type="text" class="form-control" name="issue_date"></td>
</tr>
<tr>
<td>Distribute</td>
<td><select name="distribute[]" class="select2_multiple form-control" tabindex="-1" multiple="multiple">
<option></option>
<option>Richard Marcus</option>
<option>Rowlant S Peter</option>
<option>David.K.Rumpell</option>
<option>John Mathew</option>
</select></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="btn btn-round btn-danger" value="Update"></td>
</tr>
</tbody>
</table>
</form>
I have a classrooms in schools and when I click on a certain classroom, I want to add students into it but my actual code is doing something stupid. It adds a student but i can see the student in all classrooms, not just in the one that i added him into. So when Im in classroom number 1, I see a form in there, I can add a student there, ... see how it works here:
here is the code: http://www.xxxx.xx/projekt/
here is my code in file trieda.php
<table align="center"><tr><td>
<form action="vlozit2.php" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="hidden" name="id_triedy" value="<?= $trieda['id_triedy'] ?>" />
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
</td></tr></table>
<?php
$result = mysqli_query($prip,"SELECT * FROM student ORDER BY meno");
while($student = mysqli_fetch_array($result))
{
echo "<br /><table cellspacing='1' cellpadding='1' class='tabulka1' align='center'><tr>";
echo "<td width='200'><a href='student.php?id_triedy=".$trieda['id_triedy']."".id_student=".$student['id_student']."'>".$student['meno']." ".$student['priezvisko']."</a></td>";
?>
<td width='300px' align='right' bgcolor="#fbfbfb">Zmazať</td>
</tr></table>
<?php
}
?>
here is vlozit2.php (a code that works for the form to add a student)
if(isset($_POST['submit']))
{
//meno a priezvisko
$student = $_POST['meno'];
$student = $_POST['priezvisko'];
$trieda = $_POST['id_triedy'];
//connect to the database
include 'config.php';
//insert results from the form input
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES('$_POST[meno]', '$_POST[priezvisko]', '$_POST[id_triedy]')";
$add = "<table align='center'>
<tr>
<td> Študent bol úspešne pridaný do triedy. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
$not_add = "<table align='center'>
<tr>
<td> Študent s týmto menom a priezviskom už je v tejto triede. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
if (mysqli_query($prip, $sql)) {
echo $add;
}else{
echo $not_add;
}
mysqli_close($prip);
}
?>
Try to replace your part of code with these snipets:
1) in trieda.php
<form action="vlozit2.php?id_triedy=<?php echo $_GET["id_triedy"];?>" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
2) in vlozit2.php
$student = $_POST['meno'];
$priezvisko = $_POST['priezvisko'];
$id_trieda = $_GET['id_triedy'];
and
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES( '{$student}', '{$priezvisko}', {$id_trieda} )";
Hopefully you store your id_trieda as INT type.
In your vlozit2.php file is nothing about inserting of class id. So put
<input type="hidden" name="classId" value="<?= $trieda['id'] ?>" />
to your form and in vlozit2.php get this value from $_POST['classId'] and insert it with other students data or anywhere you want to have it.
as you see in this code i made a table by selecting models from table in my database..
however i posted the return of the select query to be like the primary column for this table and put it into the while loop so it keeps generating rows till the models which came with the select query be finished
now i got a a problem when i'm trying to get this models in a $_Post[''] supergloble it keeps send me only the last value it gets from the loop
my question is how to get each and every value from the this loop to use it in a single insert query in my DB?
and sorry for the bad English :S !!
<form class="form-signin" action="<?php $_SERVER['PHP_SELF'];?>" method="Post">
<?php
$models = mysql_query("SELECT `Model_Name` FROM `models` WHERE `Brand` = 20");
while($row = mysql_fetch_array($models))
{
echo '
<tr>
<td><input type="text" name="mode[]" value="'.$row['Model_Name'].'"></td>
<td><input type="text" name="sellout[]" value=""></td>
<td><input type="text" name="shelfshare[]" value=""></td>
<td><input type="text" name="price[]" value=""></td>
<td><input type="text" name="Shortage[]" value=""></td>
<td><input type="text" name="Inventory[]" value=""></td>
</tr>
';
}
?>
</form>
the inserting script
$date = date("Y-m-d");
foreach($_POST['mode'] as $key => $mode){
$sellout = $_POST['sellout'][$key];
$shelfshare = $_POST['shelfshare'][$key];
$price = $_POST['price'][$key];
$shortage = $_POST['shortage'][$key];
$inventory = $_POST['inventory'][$key];
mysql_query("INSERT INTO `smartdailyreport`(`SFO_Code`, `Model`, `Sell_Out`, `Shelf_Share`, `Price`, `Shortage`, `Inventory`, `Date`) VALUES ('".mysql_real_escape_string($_SESSION['idd'])."','".mysql_real_escape_string($mode)."','".mysql_real_escape_string($sellout)."','".mysql_real_escape_string($shelfshare)."','".mysql_real_escape_string($price)."','".mysql_real_escape_string($shortage)."','".mysql_real_escape_string($inventory)."','".mysql_real_escape_string($date)."')") or die(mysql_error());
}
Make the name of those inputs an array :
<tr>
<td><div class="col3" align="center"><input type="text" name="mode[]" class="form-control" value="'.$row['Model_Name'].'"></div></td>
<td><div class="col3" align="center"><input type="text" name="sellout[]" class="form-control" value=""></div></td>
<td><div class="col3" align="center"><input type="text" name="shelfshare[]" class="form-control" value=""></div></td>
<td><div class="col3" align="center"><input type="text" name="price[]" class="form-control" value=""></div></td>
<td><div class="col3" align="center"><input type="text" name="Shortage[]" class="form-control" value=""></div></td>
<td><div class="col3" align="center"><input type="text" name="Inventory[]" class="form-control" value=""></div></td>
</tr>
Then when you process the form:
foreach($_POST['mode'] as $key=>$mode){
$thisIsOne = $_POST['mode'][$key];
$alsoThisOne = $_POST['sellout'][$key];
etc...
}
I'll put my comments into an answer for you...
You've got $POST as your $mode value, fix that up. (or remove it, $mode is already defined from the foreach)
Put your query inside your foreach loop, otherwise you just overwrite those variables each time you iterate, then insert the last one at the end
Put mysql_error into the die callback of mysql_query to show you an error if there is one (if you want to)
$date = date("Y-m-d");
foreach($_POST['mode'] as $key => $mode){
$sellout = $_POST['sellout'][$key];
$shelfshare = $_POST['shelfshare'][$key];
$price = $_POST['price'][$key];
$shortage = $_POST['shortage'][$key];
$inventory = $_POST['inventory'][$key];
mysql_query("INSERT INTO `smartdailyreport`(`SFO_Code`, `Model`, `Sell_Out`, `Shelf_Share`, `Price`, `Shortage`, `Inventory`, `Date`) VALUES ('".mysql_real_escape_string($_SESSION['idd'])."','".mysql_real_escape_string($mode)."','".mysql_real_escape_string($sellout)."','".mysql_real_escape_string($shelfshare)."','".mysql_real_escape_string($price)."','".mysql_real_escape_string($shortage)."','".mysql_real_escape_string($inventory)."','".mysql_real_escape_string($date)."')") or die(mysql_error());
}
Lastly, use mysqli_* instead of mysql as mysql has been deprecated for some time now. And also, use mysqli_real_escape_string or similar to escape your POST variables and save you from SQL Injection