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 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.
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
I have an update page where I check the title of the employee whether he is a doctor or a nurse. If the employee is a doctor/nurse an HTML form will be shown, if not a doctor/nurse, patient information will only be displayed and cannot be edited. But my code somehow skips the part where I wanted to display the form even if I am logged in as a doctor/nurse. Can you please help me with this....
<?php
$a=$_SESSION['employeeID'];
$title="SELECT title FROM employee WHERE employeeID = '$a'";
if($title == 'nurse' OR $title == 'doctor')
{
echo '<form method="post" id="customForm" action="add_assessment.php">
<table>
<input type="hidden" name="res_id" value="' . $_GET['res_id'] . '" />
<tr>
<td><label for="name"><font style="color:white">Symptoms</font><font style="color:gray"></font></label>
<input id="name" name="symptoms" type="text" /></td>
<td><label for="name"><font style="color:white">Respiratory Rate</font></label>
<input id="name" name="respiratoryRate" type="text" /></td>
<td><label for="name"><font style="color:white">Temperature</font> <font style="color:gray"></font></label>
<input id="name" name="temperature" type="text" /></td>
</tr>
<tr>
<td><label for="name"><font style="color:white">Blood Pressure</font></label>
<input id="name" input name="bloodPressure" type="text" class="input2"/></td>
<td><label for="name"><font style="color:white">Pulse Rate</font></label>
<input id="name" input name="pulseRate" type="text" /></td>
</tr>
<tr>
<td><label for="name"><font style="color:white">Chief Complaint</font></label>
<input id="name" input name="complaint" type="text" class="input2"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input id="send" name="send" type="submit" value="Submit" /></td>
</tr>
</table>
</form>';
}
else
{
$host="localhost";
$username="root";
$password=""; // password
$db_name="rhu"; // Database name
$tbl_name="assessment"; // Table name
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$id = $_GET['res_id'];
$sql = mysql_query("SELECT * FROM assessment WHERE patientID='$id'");
while($row = mysql_fetch_array($sql))
{
echo "<p>ID: ".$id."</p>";
echo "<p>Assessment ID: ".$row['assessmentID']."</p>";
echo "<p>Symptoms: ".$row['symptoms']."</p>";
echo "<p>Respiratory Rate: ".$row['respiratoryRate']."</p>";
echo "<p>Temperature: ".$row['temperature']."</p>";
echo "<p>Blood Pressure: ".$row['bloodPressure']."</p>";
echo "<p>Pulse Rate: ".$row['pulseRate']."</p>";
echo "<p>Complaints: ".$row['complaint']."</p>";
echo "<p>Date: ".$row['date']."</p>";
echo "<br>";
}
}
?>
In its current state, you are simply assigning a string to the variable $title. You are literally saying that $title is the string "SELECT title FROM employee WHERE employeeID = '$a'"; therefore it is skipping the if($title == 'nurse' OR $title == 'doctor').
You are also not executing a MySQL query, try this first
$a=$_SESSION['employeeID'];
$sql = mysql_query("SELECT title FROM employee WHERE employeeID = '"$a"'");
while($row = mysql_fetch_array($sql)){
$title = $row['title'];
if($title == 'nurse' OR $title == 'doctor')
{
echo....
You should also note that mysql_* is deprecated and will be phased out of PHP as a solution in the future. To future-proof your code, consider using mysqli or PDO transactions.
You can try like this--
$sql = mysql_query("SELECT title FROM employee WHERE employeeID = '$a'");
while($row = mysql_fetch_array($sql)){
$title = $row['title'];
if($title == 'nurse' OR $title == 'doctor')
{
...continue you coding