Page 1 of 1

All in one page

Posted: Sun Jul 10, 2011 2:08 am
by Sagar_999
Hey I have this script which can update and delete the records in same page... I want to add another function for insert record...
Please help me...

<?php

$link=mysql_connect("localhost","root","");

mysql_select_db("stud",$link);

if(isset($_POST['save']))
{
$nm=$_POST['nm'];
$id=$_POST['id'];

$uq="update stud
set nm='$nm'
where id=".$id;

mysql_query($uq,$link);

header("location:index.php");
}
else if(isset($_GET['id'])){
$dq="delete from stud
where id=".$_GET['id'];

mysql_query($dq,$link);

header("location:index.php");
}

/* if(isset($_GET['insert'])){
echo'<table>
<tr>
<td><input type="text" value="ins">';
$ins="insert into stud(nm) values() " */
?>
<html>
<body>
<table border="0" width="50%" align="center">
<tr align="center" bgcolor="gray" style="color:white;">
<th>No</th>
<th>Name</th>
<th>Delete</th>
</tr>

<?php

$sq="select * from stud";
$sres=mysql_query($sq,$link);
$count=1;
while($row=mysql_fetch_assoc($sres)){
echo '<form action="index.php" method="post">';
echo '<tr align="center" bgcolor="#f1f1f1">
<td>'.$count.'
<td>';
if(isset($_POST['edit']) and $_POST['id']==$row['id'])
{
echo '<input type="text" value="'.$row['nm'].'" name="nm">';
}
else
{
echo $row['nm'];
}
echo '<input type="hidden" name="id" value='.$row['id'].'>';

if(isset($_POST['edit']) and $_POST['id']==$row['id'])
{
echo '<td><input type="submit" value="Save" name="save">';
}
else
{
echo '<td><input type="submit" value="Edit" name="edit">';
}
echo '<a href="index.php?id='.$row['id'].'">X</a></tr>';

echo '</form>';
$count++;
}
echo '<td><input type="submit" value="insert" name="Insert">';

?>
</table>
</body>
</html>

Re: All in one page

Posted: Sun Jul 10, 2011 4:41 am
by social_experiment
It would be easier if you create a function and then call that when the insert option is selected.

Code: Select all

<?php
 function insertIntoDb($value)
 {
  if ($value != '')
  {
   $query = "INSERT INTO stud (nm) VALUES ('". mysql_real_escape_string($value) . "')";
   $sql = mysql_query($query);
  }
 }
 
 //
 if (isset($_GET['insert']))
 {
  insertIntoDb($_POST['ins']);
  # rest of the code
 }
?>
This would be executed if the $_GET['insert'] is set. It's missing some checks (which should always be done on any input received) but this is just an idea of what you can do. Btw, you should also check the value of $_GET['insert'] because the following will also trigger the function : page.php?insert=

An alternative to your idea is to have a url like this : page.php?action=delete or page.php?action=save so it will be easier (and safer) to control what action has been selected by the user.

Hint: the php code button will help whoever is reading your code. :)

Re: All in one page

Posted: Sun Jul 10, 2011 11:59 pm
by Sagar_999
Thanks Dear for your kind reply..