Wednesday, May 6, 2015

How to update multiple data in php

This is simple trick which provides solution for your question for this you have to use array concept .


file name as you wish

connect to database with respected connection string

Table structure:

mysql> CREATE TABLE tab(
id int NOT NULL AUTO_INCREMENT,
name varchar(255) null,
mobile bigint null,
email varchar(255) null
);

HTML FORM

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
ini_set("display_errors",0);

mysql_connect("localhost","root","");
mysql_select_db("test") or die("Unable to select database");

$sql = "SELECT * FROM tab where valid=0 ORDER BY id";

$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());

$i = 0;

echo '<table width="50%">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>Name</td>';
echo '<td>Address</td>';
echo '</tr>';

echo "<form name='form_update' method='post' action='dharamart.php'>\n";
$dada=array();
while ($students = mysql_fetch_array($result)) {
$email=$students['email'];
if (strpos($email, '@') !== false){
$mail="";
}
else{
$mail="background-color:red;";
}

$mobile=$students['mobile'];
if(strlen($mobile)==10){
$dada[]=$mobile;
$array_count=array_count_values($dada);
foreach($dada as $val){
$count=$array_count[$val];
if($count>1){
$tel="background-color:yellow;";
}
else{
$tel="";
}
}
}
else{
$tel="background-color:red;";
}
echo '<tr>';
echo "<td>{$students['id']}<input type='hidden' name='id[$i]' value='{$students['id']}' /></td>";
echo "<td>{$students['name']}</td>";
echo "<td><input type='text' size='40' style='{$mail}' name='address[$i]' value='{$students['email']}' /></td>";
echo "<td><input type='text' size='40' style='{$tel}' name='mobile[$i]' value='{$students['mobile']}' /></td>";
echo "<td><input type='checkbox' name='ass[$i]'></td>";
echo '</tr>';
++$i;
}
echo '<tr>';
echo "<td><input type='submit' name='submit' value='submit' /></td>";
echo '</tr>';
echo "</form>";
echo '</table>';
?>



BACK CODE


file name must be:   dharamart.php

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
ini_set("display_errors",0);

mysql_connect("localhost","root","");
mysql_select_db("test") or die("Unable to select database");
 if(isset($_POST['submit'])){
$size = count($_POST['address']);

$i = 0;
while ($i < $size) {
$address= $_POST['address'][$i];
$mobile= $_POST['mobile'][$i];
$id = $_POST['id'][$i];

$query = "UPDATE tab SET email = '$address',mobile='$mobile' WHERE id = '$id' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
echo "$address<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
 header("Location: multi1.php");
 }
?>






No comments:

Post a Comment

Dharamart.blogspot.in