Insert into | on duplicate key update to add new row - php

I'm trying to update a table, with the ability of adding new rows.
The script is updating the values, but not inserting new rows. When I add a row, it updates the first one.
This is my table:
TABLE `tbl_orderdetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) DEFAULT NULL,
`product_name` varchar(255) DEFAULT NULL,
`quantity` varchar(255) DEFAULT NULL,
`price` varchar(255) DEFAULT NULL,
`discount` int(11) DEFAULT NULL,
`amount` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
And this is my update code:
<?php
if (isset($_POST['update'])) {
$size = count($_POST['quantity']);
$size = count($_POST['product_name']);
$size = count($_POST['price']);
$size = count($_POST['discount']);
$size = count($_POST['amount']);
$i = 0;
while ($i<$size) {
$quantity= $_POST['quantity'][$i];
$product_name= $_POST['product_name'][$i];
$price= $_POST['price'][$i];
$discount= $_POST['discount'][$i];
$amount= $_POST['amount'][$i];
$id= $_POST['id'][$i];
$order_id= $_POST['order_id'][$i];
$query = ("INSERT INTO tbl_orderdetail (id, order_id, quantity, product_name, price, discount, amount )
VALUES ('$id', '$order_id', '$quantity', '$product_name', '$price', '$discount', '$amount' )
ON DUPLICATE KEY UPDATE quantity = '$quantity', product_name = '$product_name', price = '$price', discount = '$discount', amount = '$amount'");
mysql_query($query) or die(mysql_error());
++$i;
}
header("Location: $PHP_SELF");
mysql_close();
}
?>
Here's my form:
<form method="post" action="">
<div class="box-body">
<table class="table table-bordered table-hover">
<?php
$sql = "SELECT * FROM tbl_orderdetail WHERE order_id=$id";
$result = mysql_query($sql);
$count=mysql_num_rows($result);
?>
<thead>
<th>No</th>
<th>Qtde</th>
<th>Descrição</th>
<th>Unitário</th>
<th>Desc.(%)</th>
<th>Valor</th>
<th><input type="button" value="+" id="add" class="btn btn-primary"></th>
</thead>
<tbody id="orderdetail" class="detail">
<?php
while ($rows = mysql_fetch_array($result)){
?>
<tr>
<input type="hidden" name="id[]" value="<?php echo $rows['id']; ?>" >
<td width="2%" class="no">1</td>
<td width="10%"><input type="text" id="quantity" class="form-control quantity" name="quantity[]" value="<?php echo $rows['quantity']; ?>"></td>
<td width="60%"><input type="text" id="product_name" class="form-control product_name" name="product_name[]" value="<?php echo $rows['product_name']; ?>"></td>
<td width="8%"><input type="text" id="price" class="form-control price" name="price[]" value="<?php echo $rows['price']; ?>"></td>
<td width="4%"><input type="text" id="discount" class="form-control discount" name="discount[]" value="<?php echo $rows['discount']; ?>"></td>
<td width="10%"><input type="text" id="amount" class="form-control amount" name="amount[]" value="<?php echo $rows['amount']; ?>"></td>
<td width="6%"><a href="#" class="remove">Excluir</td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<th></th>
<th></th>
<th></th>
<th></th>
<th style="text-align:center;" >Total R$</th>
<th style="text-align:center;" class="total">0</th>
</tfoot>
</table>
<input type="submit" class="btn btn-primary" name="update" id="update" value="Salvar">
</form>

First: DO NOT use php's mysql library, use mysqli or PDO instead
Second: Your code is vulnerable to sql injection - best fix would be to use prepared statement (I'd advice again to look into PDO). Never ever trust anything that might be coming from a user (i.e all the POST, GET stuff).
Third: for development always display all errors, warnings, notices etc (You might have seen at least the deprecated warning for the mysql library - if working with php >= 5.5 - and the careless use of $_POST values)
Fourth: I'm sorry to say that your code makes not much of a sense to me:
1.)
$size = count($_POST['quantity']);
$size = count($_POST['product_name']);
// ... etc ...
$size = count($_POST['amount']);
Here you are only taking the size of amount into account. so all the lines with $size = before the last one are senseless.
2.) In the while loop we find lines similar to those:
$id= $_POST['id'][$i];
and $i is incremented until it's the size of $_POST['amount']. What if the size of $_POST['id'] is not the same as the $_POST['amount']?
3.) You are using auto_increment for the primary key but inserting the id manually. I'd remove the auto_increment here.
So if I'd guess I would try echoing $query and check if either the while-loop is not running as often as it should or if the id values are somehow strange.
== Edit ==
I just saw your html output right now. As J.Han pointed out: your script does exactly what it was said that it should do:
You are reading all the results from the database and after editing and submitting it the new values should overwrite the old ones.
If you want to use that script with insert you have to set the id to one that is not yet in your database (i.e. set a value of zero in html and catch that in the php part to generate a valid new id)

Related

How to add multiple values in a single row of a column using php into mysql

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>

Auto increment employee ID

I just want to add an employee and after that, the employee ID will also increment. Also that textbox must be disabled
Also here's my code. All I want is to auto increment my employee ID when I add a new employee. I hope everyone will help me. Thank you in advance. :)
<center>
<form class="contact_form" action="#" method="post">
<h2>Register New Employee</h2>
<br/>
<table>
<tr>
<td><label for="emp">Emp ID:</label></td>
<td><input type="text" name="emp" placeholder="Emp ID" required /></td>
</tr>
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" name="fname" placeholder="First Name" required />
<input type="text" name="lname" placeholder="Last Name" required /></td>
</tr>
<tr>
<td><label for="address">Address:</label></td>
<td><input type="text" name="address" placeholder="Full Address" required /></td>
</tr>
<tr>
<td><label for="contact">Contact:</label></td>
<td><input type="text" name="contact" placeholder="Contact Number" required /></td>
</tr>
<tr>
<td><label for="type">Type:</label></td>
<td><select name="type" id="type">
<option>Type of Employee</option>
<option>Contractual</option>
<option>Regular</option>
</select>
</td>
</tr>
<tr>
<td><label for="salary">Salary:</label></td>
<td><input type="text" name="salary" placeholder="Emp Salary" required /></td>
</tr>
</table>
<br/>
<button class="submit" name="submit" type="submit" onclick="message()">Submit</button>
<button class="reset" name="reset" type="reset">Clear</button>
</form>
<?php
if (isset($_POST['submit'])) {
include 'alqdb.php';
$emp=$_POST['emp'];
$fname= $_POST['fname'];
$lname=$_POST['lname'];
$address=$_POST['address'];
$contact=$_POST['contact'];
$type=$_POST['type'];
$salary=$_POST['salary'];
mysqli_query($con, "INSERT INTO employee (EmpID,EmpFName,EmpLName,EmpAddress,ContactNumber,TypeofEmployee,Salary)
VALUES ('$emp','$fname','$lname','$address','$contact','$type','$salary')");
}
?>
</center>
</body>
<script language="javascript">
function message() {
alert("Successfully added!");
}
</script>
If you want to have an EmpID like EMP001
this code will work:
public function autoincemp()
{
global $value2;
$query = "SELECT empid from tbemployee order by empid desc LIMIT 1";
$stmt = $this->db->prepare($query);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$value2 = $row['empid'];
$value2 = substr($value2, 3, 5);
$value2 = (int) $value2 + 1;
$value2 = "EMP" . sprintf('%04s', $value2);
$value = $value2;
return $value;
} else {
$value2 = "EMP0001";
$value = $value2;
return $value;
}
}
You could modify your database to include AUTO_INCREMENT in EmpID.
You can disable input by doing <input type="text" name="emp" placeholder="Emp ID" required disabled />
Place AUTO_INCREMENT attribute to emp_id column in your DB. Remove that EMP ID field from your UI.
The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows. Means, AUTO_INCREMENT automatically insert new incremented id for that field on each INSERT query
Reference
You can hide Emp ID code and change input type="text" to input type="hidden" and remove required in your form.
Now just use AUTO_INCREMENT for EmpId in your table.
It's late but you can do this,
$id = 1; //Your last record Id + 1
str_pad($id, 3, "0", STR_PAD_LEFT);
Hope this helps someone.
Reference
REATE TABLE dbo.tblUsers
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblUsers without specifying values for ID or UserID:
INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

PHP - 1 form, 2 tables - Can't insert data into table 1

I'm trying to make an invoice system that adds rows, from a tutorial and data is correctly inserted into tbl_orderdetail, but I can't make it work to insert data to tbl_order.
These are the 2 MYSQL tables:
CREATE TABLE IF NOT EXISTS `tbl_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`re_name` varchar(255) DEFAULT NULL,
`location` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `tbl_orderdetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) DEFAULT NULL,
`product_name` varchar(255) DEFAULT NULL,
`quantity` varchar(255) DEFAULT NULL,
`price` varchar(255) DEFAULT NULL,
`discount` int(11) DEFAULT NULL,
`amount` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=73 ;
And this is my connection code:
<?php
$cn = mysql_connect('localhost','root','');
if($cn)
{
mysql_select_db('mydb',$cn);
}
if(isset($_POST['submit']))
$re_name = $_POST['re_name'];
$location = $_POST['location'];
{
mysql_query ("INSERT INTO tbl_order(re_name,location) VALUES('{$_POST['re_name']}','{$_POST['location']}')");
$id = mysql_insert_id();
for($i = 0 ;$i < count($_POST['productname']);$i++)
{
mysql_query("INSERT INTO tbl_orderdetail
SET order_id = '{$id}',
product_name = '{$_POST['productname'][$i]}',
quantity = '{$_POST['quantity'][$i]}',
price = '{$_POST['price'][$i]}',
discount = '{$_POST['discount'][$i]}',
amount = '{$_POST['amount'][$i]}'
");
}
}
?>
What is wrong in my code?
Here is the form that submits the values:
<form action="" method="post">
<div class="box-body">
<div class="form-group">
ReceptName
<input type="text" name="re_name" id="re_name" class="form-control">
</div>
<div class="form-group">
Location
<input type="text" name="location" id="location" class="form-control">
</div>
<input type="submit" class="btn btn-primary" name="submit" id="submit" value="Save Record">
</div>
<table class="table table-bordered table-hover">
<thead>
<th>No</th>
<th>ProductName</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount</th>
<th>Amount</th>
<th><input type="button" value="+" id="add" class="btn btn-primary"></th>
</thead>
<tbody class="detail">
<tr>
<td class="no">1</td>
<td><input type="text" class="form-control productname" name="productname[]"></td>
<td><input type="text" class="form-control quantity" name="quantity[]"></td>
<td><input type="text" class="form-control price" name="price[]"></td>
<td><input type="text" class="form-control discount" name="discount[]"></td>
<td><input type="text" class="form-control amount" name="amount[]"></td>
<td><a href="#" class="remove">Delete</td>
</tr>
</tbody>
<tfoot>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th style="text-align:center;" class="total">0</th>
</tfoot>
</table>
</div>
</div><!-- /.box -->
</form>
</div><!--/.col (left) -->
Thank you all for helping me.
I dropped tbl_order and created a new one called 'orcamen'.
Here's the php code that worked:
if(isset($_POST['submit']))
{
$razao = $_POST["razao"];
$local = $_POST["local"];
$condicao = $_POST["condicao"];
$estado = $_POST["estado"];
$material = $_POST["material"];
$obs = $_POST["obs"];
mysql_query
("INSERT INTO orcamen ( id , razao , local , condicao , estado , material , obs )
VALUES ( NULL , '$razao', '$local', '$condicao', '$estado', $material', '$obs')");
$id = mysql_insert_id();
for($i = 0 ;$i < count($_POST['productname']);$i++)
{
mysql_query("INSERT INTO tbl_orderdetail
SET order_id = '{$id}',
product_name = '{$_POST['productname'][$i]}',
quantity = '{$_POST['quantity'][$i]}',
price = '{$_POST['price'][$i]}',
discount = '{$_POST['discount'][$i]}',
amount = '{$_POST['amount'][$i]}'
");
}
}

Update a row value in SQL database after submit based on selected checkbox(es)

I have this table:
In my SQL, I have this column named 'Status' with two values only: Inactive and Active which is set to be Inactive by default.
My question is, how can I update in my database the 'Status' column to "Active" if the specific row is checked after clicking the "Submit" button? Even if there's more than 1 row that is checked. What SQL query should I use (or if combined with PHP)?
I am using PHP by the way. I've researched and can't seem to get the right answer.
Thank you in advance for all the help/advice/suggestion.
UPDATE:
I have modified #Vikas Umrao's answer and made a few changes. The Status row successfully updates whenever the table row is checked. However, the row that was previously updated stays in the array and does not reset. I'll explain it further, but before that, below are my working code with database:
SQL (set up your own connection, mine is named database.php)
CREATE TABLE IF NOT EXISTS `table_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`department` varchar(255) NOT NULL,
`status` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
INSERT INTO `table_test` (`id`, `name`, `department`, `status`) VALUES
(1, 'Misha', 'Accounting', 'Inactive'),
(2, 'Justin', 'IT', 'Inactive'),
(3, 'Chris', 'HR', 'Inactive');
And this is my whole index.php as some script based on Vikas'
<?php
include('database.php');
$query = "SELECT * FROM table_test";
$result = mysql_query($query);
if($result === false) {
die(mysql_error());
}
echo "<form method='post' action='#'>
<h2>Table Content</h2>
<table>
<thead>
<tr style='background-color: rgb(102, 222, 93);'>
<td>Name</td>
<td>Department</td>
<td>Status</td>
<td></td>
</tr>
</thead>
<tbody>";
while($row = mysql_fetch_array($result)){
$row_id = $row['id'];
$name = $row['name'];
$department = $row['department'];
$status = $row['status'];
echo "<tr><td>" . $name . "</td><td>" . $department . "</td><td>" . $status . "</td><td><input type='checkbox' name='id[]' value='" . $row_id . "'/></td></tr>";
}
echo "</tbody></table><input type='submit' value='submit'></form>"; //end form
/***** Update Status *****/
/*print_r($_POST);*/
if(gettype($_POST['id'])=="array"){
foreach($_POST['id'] as $val){
$id_c = $val;
$query2 = "UPDATE table_test SET status = 'Inactive' where id='".$id_c."'";
$result2 = mysql_query($query2);
if($result2 === false) {
die(mysql_error());
}
echo "Status " .$id_c. " is updated. <br>";
}
}
mysql_close();
?>
UPDATE QUESTION:
When I check a row and then click submit, the status value in database changes. I echoed the result of which IDs are updated. However, even after refreshing the page, the data row updated values were still there.
So let's say I change the Update query to active instead of inactive, if I refresh the page and the previously updated rows were Misha and Chris', then their status will be active even if I don't want them to:
$query2 = "UPDATE table_test SET status = 'Active' where id='".$id_c."'";
So everytime I refresh the page, it will continuously update the row even if it's not checked. How can I clear the php array values? I've seen this the unset and instantiate but can't seem to apply it here. How should I do that?
Below is a sample screenshot of the result:
Thank you!
=======================
FINAL:
I was able to fix it on my own. Thanks everyone!
Your form should be like this . value of <input name="id[]" value="1" type="checkbox" checked=""> will be the primary id of table.
<form method="post">
<table id="status-table">
<thead>
<tr style="background-color: rgb(102, 222, 93);">
<td>Name</td>
<td>Department</td>
<td>Status</td>
<td><input type="checkbox"></td>
</tr>
</thead>
<tbody>
<tr>
<td>Misha</td>
<td>Accounting</td>
<td>Inactive</td>
<td><input name="id[]" value="1" type="checkbox" checked=""></td>
</tr>
<tr>
<td>Justin</td>
<td>IT</td>
<td>Active</td>
<td><input name="id[]" value="2" type="checkbox"></td>
</tr>
<tr>
<td>Chris</td>
<td>HR</td>
<td>Inactive</td>
<td><input name="id[]" value="3" type="checkbox" checked=""></td>
</tr>
</tbody>
</table>
<input type="submit" value="submit">
</form>
and your php code will be like this:
<?php
//print_r($_POST);
if(gettype($_POST['id'])=="array"){
foreach($_POST['id'] as $val){
$id_c=$val;
$query="update table set status='Active' where id='".$id_c."'";
}
}
?>

how to add images to mysql database when a user submit their images

I want to add multiple images into mysql database using a form. Whenever a user submits that form then it captures all data and stores that into mysql database. (it is right way, but i need)
My database table is looking like this.
CREATE TABLE `Owner_detail` (
`id` int(10) NOT NULL auto_increment,
`fullname` varchar(30) NOT NULL,
`List1` varchar(20) NOT NULL,
`List2` varchar(20) NOT NULL,
`List3` varchar(20) NOT NULL,
`area` varchar(30) NOT NULL,
`ownermobile` varchar(20) NOT NULL,
`email` varchar(20) NOT NULL,
`image_one` blob NOT NULL,
`image_two` blob NOT NULL,
`image_three` blob NOT NULL,
`otherdetail` varchar(300) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=49 ;
My html form is looking like this.
<table width="60%"><form action="process.php" method="post" enctype="multipart/form-data" name="tripleplay" onsubmit="MM_validateForm('fullname','','R','area','','R','ownermobile','','RisNum','email','','RisEmail','otherdetail','','R');return document.MM_returnValue">
<tr>
<td width="44%">Full Name : </td>
<td width="56%"><input size="25" type="text" name="fullname" id="fullname" /></td>
</tr>
<tr>
<td valign="top">Rental Type:</td>
<td>
<select name='List1' id="List1" onchange="fillSelect(this.value,this.form['List2'])">
<option selected>Make a Selection</option>
</select>
<br /><br />
<select name='List2' id="List2" onchange="fillSelect(this.value,this.form['List3'])">
<option selected>Make a Selection</option>
</select><br /><br />
<select name='List3' id="List3" onchange="getValue(this.value, this.form['List2'].value,
this.form['List1'].value)">
<option selected>Make a Selection</option>
</select>
</td>
</tr>
<tr>
<td>Area : </td>
<td><input size="25" type="text" name="area" id="area" />
sq.ft.</td>
</tr>
<tr>
<td>Owner Mobile / Landline</td>
<td><input size="25" type="text" name="ownermobile" id="ownermobile" /></td>
</tr>
<tr>
<td><p>E-mail</p></td>
<td><input size="25" type="text" name="email" id="email" /></td>
</tr>
<tr>
<td valign="top">Pictures of Property</td>
<td>
<input type="file" name="image_one" id="image_one" />
<input type="file" name="image_two" id="image_two" />
<input type="file" name="image_three" id="image_three" />
</td>
</tr>
<tr>
<td valign="top">Other details you would like to share about your property:</td>
<td><textarea size="25" name="otherdetail" id="otherdetail" cols="45" rows="5"> </textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" id="submit" value="Submit" /></td>
</tr>
</form>
</table>
and my processing form in php is looking like this
<?
if( $_POST )
{
$con = mysql_connect("","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("vkrental", $con);
$users_fullname = $_POST['fullname'];
$users_area = $_POST['area'];
$users_List1 = $_POST['List1'];
$users_List2 = $_POST['List2'];
$users_List3 = $_POST['List3'];
$users_ownermobile = $_POST['ownermobile'];
$users_email = $_POST['email'];
$users_image_one = $_POST['image_one'];
$users_image_two = $_POST['image_two'];
$users_image_three = $_POST['image_three'];
$users_otherdetail = $_POST['otherdetail'];
$users_fullname = htmlspecialchars($users_fullname);
$users_area = htmlspecialchars($users_area);
$users_List1 = htmlspecialchars($users_List1);
$users_List2 = htmlspecialchars($users_List2);
$users_List3 = htmlspecialchars($users_List3);
$users_ownermobile = htmlspecialchars($users_ownermobile);
$users_email = htmlspecialchars($users_email);
$users_image_one = htmlspecialchars($users_image_one);
$users_image_two = htmlspecialchars($users_image_two);
$users_image_three = htmlspecialchars($users_image_three);
$users_otherdetail = htmlspecialchars($users_otherdetail);
$query = "
INSERT INTO `vkrental`.`Owner_detail` (
`fullname` ,
`area` ,
`List1` ,
`List2` ,
`List3` ,
`ownermobile` ,
`email` ,
`image_one` ,
`image_two` ,
`image_three` ,
`otherdetail`
)
VALUES ( '$users_fullname',
'$users_area', '$users_List1','$users_List2','$users_List3', '$users_ownermobile', '$users_email', '$users_image_one','$users_image_two','$users_image_three', '$users_otherdetail'
);";
mysql_query($query);
echo "<h2>Success.</h2>";
mysql_close($con);
}
?>
My Problem is when ever I am inserting images from mysql database it stores successfully.
but when i am doing that from my html form it is not storing images. it is storing only data(text).
I don't know what is the actual error in my forms.
I wonder what using htmlspecialchars() for binary data would do.
$users_image_one = htmlspecialchars($users_image_one);
$users_image_two = htmlspecialchars($users_image_two);
[Edit:]
htmlspecialchars() is used to preserve special characters of text data. However, if you use it for binary data, it would mess up everything.
Troubleshoot them yourself:
You can try to find out the problem by first just uploading only the images.
Also have a look at this link : File upload using POST method
Does not sound like there is an error . . . .
You don't store the actual images in your database, but rather just their name, or a reference to the images
e.g. product_one.jpg
Then when you want to display it you would do something like
<img src=" <?php $echo \images\$users_image_one ?> ">

Categories