Wednesday, 31 July 2013

Implode and Explode the data from database in php

Implode means return a string from the elements of an array that means it converts an array into the srting.Explode split a string by string,it change a string into an array. 

      For example consider a simple driving form,


<form name="aform" method="post" action="conn.php" onsubmit="return validation();">
<table border="0px" cellpadding="10" cellspacing="0" id="tbl">
<tr><td align="center" colspan="2">Sample Driving Form</td></tr>
<tr>
     <td>Vehicle</td>
     <td><input type="checkbox" name="vehicle[]" value="bus" />bus
     <input type="checkbox" name="vehicle[]" value="car" />car
     <input type="checkbox" name="vehicle[]" value="bike" />bike</td>
</tr>
<tr><td colspan="2" align="center"><input type="submit" name="submit" value="submit" /></td></tr>
</table>
</form>

Lets see the output

Sample Driving Form
Vehicle bus car bike



Implode the datas using database :


Connect the database :


<?php
       $conn=mysql_connect("127.0.0.1","root","") or die(mysql_error());
       $select_db=mysql_select_db("arrayconcept_db",$conn) or die(mysql_error());
?>

Insert into the database :


<?php
if(isset($_POST['submit']))
{
print_r($_POST);
$vehicle=$_POST['vehicle'];

$r=implode(",",$vehicle);
$insert=mysql_query("insert into arrayconcept_tbl(vehicle) value ('$r')") or die(mysql_error());
}
?>

After implode into the databse the output will be 


Explode the datas from the database :



<?php
$select_tbl=mysql_query("select * from arrayconcept_tbl",$conn);
while($fetch=mysql_fetch_object($select_tbl))
{
$r=$fetch->vehicle;

$i=explode(",",$r);

echo $i[0]."</br>";
}
?>

Finally after explode from the database,the output will be the