Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to change information in database with php.

Status
Not open for further replies.

C0FFEE123

Programmer
Sep 1, 2008
44
NL
Hi,

I am currently working with a database.
I already have the insert part only now i want to make a edit part.
How i want to do it?
I want to show a screen with all the information in textfields.

Example:

Name: Test
Price: 123
Link: test.html

Name: Test2
Price: 321
Link: test2.html

+----+
|Edit|
+----+

Only how to do it, i have no idea.
Thanks

-------------------------------------
I am a progammer.... no realy.
 
a few thoughts:

1. your sig: really is spelled with two ls. is the mispelling intentional?
2. phpmyadmin does what you want. but it may be giving too much authority to your users.
3. you're looking for a CRUD system (create, retrieve, update, delete). Try out my code for this:
 
Are you looking to actually display the info on the screen and not allow editing until EDIT button is clicked or is button used to submit the changes?

Not sure based on your given info ...

I normally display a grid with the rows from my db and provide means to edit data by clicking on (a) the row itself or (b) an icon placed within the row.

Try using a class
Code:
<?PHP
//
// SIMPLE CLASS AND A COUPLE OF RELEVANT FUNCTIONS
//
function OpenDB($db) {
if ($db == NULL or $db == '') $db = 'dbname';
//connect to MySQL
mysql_connect('dbhost', 'dbuser', 'dbpassword');
mysql_select_db('dbname');
}

function getQuery($sql) {
	return mysql_query($sql);
}
function getCount($query) {
	if ($query) { return mysql_num_rows($query); } else { return 0; }
}

class aRow {
  var $rows='';
  function listRows() {
    $sql='SELECT * FROM yourtable WHERE 1;';
	OpenDB('dbname'); $query=getQuery($sql);
	$string = '
	<table border="0" cellpadding="0" cellspacing="0" width="100%" class="datagrid">
	  <tr class="tblhdr">
	    <th>COL 01</th>
		<th>COL 02</th>
		<th>COL 03</th>
	  </tr>';
	if (getCount($query) > 0) {
	while ($row=mysql_fetch_assoc($query)) {
		$string .= '
		<tr class="gridrow" onclick="editRow('.$row['id'].');">
		  <td>'.$row['col01'].'</td>
		  <td>'.$row['col02'].'</td>
		  <td>'.$row['col03'].'</td>
		</tr>';
	}
	}
	$string .= '</table>';
	$this->rows=$string;
  }
  function editRow($id) {
    $sql = 'SELECT * FROM yourtable WHERE id = '.$id.' LIMIT 1;';
	OpenDB(''); $query=getQuery($sql);
	$row=mysql_fetch_assoc($query);
	if ($row) {
		$string = '
		<form name="editRow" method="post">
		 COL 01&nbsp;<input name="col01" id="col01ID" type="text" /><br />
		 COL 02&nbsp;<input name="col02" id="col02ID" type="text" /><br />
		 COL 03&nbsp;<input name="col03" id="col03ID" type="text" /><br />
		 <input name="editRow" type="submit" value="Save Changes" />
<input name="id" type="hidden" value="'.$id.'" />
		</form>';
		$this->eRow=$string;
	} else { $this->eRow="<p>What's up doc?</p>"; }
  }
  function wrtRow($id) {
    $sql = 'UPDATE yourtable SET 
	`col01`   =  "'.$_POST['col01'].'",
	`col02`   =  "'.$_POST['col02'].'",
	`col03`   =  "'.$_POST['col03'].'"
	WHERE id = '.$id;
	$query=getQuery($sql);
	if($query) { return(1); } else { return(0); }
  }
}
?>

which in turn is called by
Code:
<?PHP

$myRows = new aRow;
if ($_POST['editRow'] == '') {
	if strtoupper($_REQUEST['action']) == 'EDIT') {
		$string = $myRows->editRow($_GET['id']);
	} else {
		$string = $myRows->listRows();
	}
} else {
	$wrtrow=$myRows->wrtRow($_POST['id']);
	$string=$myRows->listRows();
}
?>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
	editRow(id) {
	  window.location('myPHP.php?action=edit;id='+id);
	}
</script>
<style type="text/css">
	.datagrid {
	
	}
	.gridrow {
	  background-color: #CCC;
	}
</style>

</head>
<body>
<?PHP
  echo $string;
?>
</body>
</html>

NOTE: I did not get a chance to test this code, I just put it together in hope I can point you in the right direction.

Plenty of room for improvement but I hope this gives you an idea on one way to address your needs.

Good luck!



--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
A couple of corrections for my posting above:

(1) Function listRows()
Change $this->rows=$string; with return ($string);

(2) Function editRows()
Change $this->eRow=$string; with return ($string);
Change $this->eRow="<p>What's up doc?</p>"; with
return ("<p>What's up doc?</p>");

Was thinking one thing and ended up doing another - Sorry!



--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
Having noticed my errors, I decided to give the scripts a quick and sure enough there were a couple of problems.

Here are the scripts again
Code:
//simpleclass.php
<?PHP
function OpenDB($db) {
if ($db == NULL or $db == '') $db = 'dbname';
//connect to MySQL
mysql_connect('dbhose', 'dbuser', 'dbpassword');
mysql_select_db('dbname');
}

function getQuery($sql) {
	return mysql_query($sql);
}
function getCount($query) {
	if ($query) { return mysql_num_rows($query); } else { return 0; }
}

class aRow {
  var $rows='';
  function listRows() {
    $sql='SELECT * FROM yourtable WHERE 1;';
	OpenDB('dbname'); $query=getQuery($sql);
	$string = '
	<table border="1" cellpadding="0" cellspacing="0" width="100%" class="datagrid">
	  <tr class="tblhdr">
	    <th>COL 01</th>
		<th>COL 02</th>
		<th>COL 03</th>
	  </tr>';
	if (getCount($query) > 0) {
	while ($row=mysql_fetch_assoc($query)) {
		$string .= '
		<tr class="gridrow" id="row'.$row['id'].'" onclick="editRow('.$row['id'].');" onmouseover="chgColor('.$row['FileID'].',1);" onmouseout="chgColor('.$row['id'].',0);">
		  <td>'.$row['col01'].'</td>
		  <td>'.$row['col02'].'</td>
		  <td>'.$row['col03'].'</td>
		</tr>';
	}
	}
	$string .= '</table>';
	return($string);
  }
  function editRow($id) {
    $sql = 'SELECT * FROM yourtable WHERE id = '.$id.' LIMIT 1;';
	OpenDB(''); $query=getQuery($sql);
	$row=mysql_fetch_assoc($query);
	if ($row) {
		$string = '
		<form name="editRow" method="post">
		 COL 01&nbsp;<input name="col01" id="col01ID" type="text" value="'.$row['col01'].'" /><br />
		 COL 02&nbsp;<input name="col02" id="col02ID" type="text" value="'.$row['col02'].'" /><br />
		 COL 03&nbsp;<input name="col03" id="col03ID" type="text" value="'.$row['col03'].'" /><br />
		 <input name="editRow" type="submit" value="Save Changes" />
		 <input name="id" type="hidden" value="'.$id.'" />
		</form>';
		return($string);
	} else { return("<p>What's up doc?</p>"); }
  }
  function wrtRow($id) {
    $sql = 'UPDATE yourtable SET 
	`col01`   =  "'.$_POST['col01'].'",
	`col02`   =  "'.$_POST['col02'].'",
	`col03`   =  "'.$_POST['col03'].'"
	WHERE id = '.$id;
	$query=getQuery($sql);
	echo $sql;
	if($query) { return(1); } else { return(0); }
  }
}
?>

and the show and play script
Code:
// simplephp.php
<?PHP

include("simpleclass.php");

$myRows = new aRow;
if ($_POST['editRow'] == '') {
	if (strtoupper($_REQUEST['action']) == 'EDIT') {
		$string = $myRows->editRow($_GET['id']);
	} else {
		$string = $myRows->listRows();
	}
} else {
	$wrtrow=$myRows->wrtRow($_POST['id']);
	if ($wrtrow) { $string=$myRows->listRows(); } else { $string='<p style="color: red;">Sorry, I had problems saving your changes!!!</p>'.$myRows->listRows(); }
}
?>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
	function editRow(id) {
	  var url = 'simplephp.php?action=edit&id='+id;
	  window.location=url;
	}
	function chgColor(n,num){
		var row='row'+n;
		if (num > 0) { document.getElementById(row).style.background='gold'; } else { document.getElementById(row).style.background=''; }
	}
</script>
<style type="text/css">
	.datagrid {
	
	}
	.gridrow {
	  background-color: #FFF;
	}
	.tblhdr {
	  background-color: #CCC;
	}
</style>

</head>
<body>
<?PHP
  echo $string;
?>
</body>
</html>

I ran it through using one of my tables and I was able:
1) to successfully display my rows on a grid
2) have row background color change as mouse hovers over
3) open a page with form to edit record
4) submit and process changes
5) display grid again with changed information


Of course this is not exactly production material but my aim is to simply give you an idea of how one could do what you are looking for.


--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
Do you think it might be better to get a php/mysql book and learn how to do it ?
 
Books are always good but they do not always provide answers or real world scenarios.

I have several books and I constantly come here with questions and more often than not, this medium is a greater value.

--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
there have been many threads about how best to help users. and there's no right answer.

I tend to provide coded solutions because:

1. that's what i'd want
2. that to me is the easiest way of explaining something
3. i think it is unduly condescending to tell someone to go look something up when you know the answer yourself. it's your choice whether to spend your time helping someone. that's not to say that i like being taken advantage of: and there are some threads that really annoy me.
4. i think learning a coding language is similar to learning a spoken language. text books take you only so far but the only way to learn properly is to immerse yourself in the language, listen to the radio, read novels, go to the movies, sit in bars etc. in the coding world that means pretty much getting your hands dirty in other people's code.
 
Well said ingresman. I feel that providing full code solutions encourages lazy thinking and poor work practices and discourages learning and personal development. This is supposed to be a forum for interaction between computer professionals, not a code library or a help desk. There are plenty of code libraries around, and it will be a pity if this forum slides down to join them.

___________________________________________________________
If you want the best response to a question, please check out FAQ222-2244 first.
'If we're supposed to work in Hex, why have we only got A fingers?'
Drive a Steam Roller
Steam Engine Prints
 
there you go! two opposing views in two posts! sounds like healthy ' interaction between computer professionals'

as i said, this topic has been done to death. we all do what we think is best and want to do. live and let live. the red flag is the steam valve (hope you appreciate the metaphor, john!)
 
I agree with you jpadie - I do what I do for several reasons and they are all volunteered

1) Pay back to the help I have received
2) Good will and willingness to help others
3) I believe that by helping, I learn ...
4) Every now and then I go, Hmm, how can I do that?

In a personal gain: I hope to be published technical book writer in the future, this is good experience (say, this is my "community organizer" position).

If I have nothing to offer, I simply do nothing and when that is the case, I often feel bad ... Why? Not sure, I just do.



--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
Thanks for the help guys :p
Testing your code now ^^

-------------------------------------
I am a progammer.... no realy.
 
@jpadie - [smile] - Like the analogy!

___________________________________________________________
If you want the best response to a question, please check out FAQ222-2244 first.
'If we're supposed to work in Hex, why have we only got A fingers?'
Drive a Steam Roller
Steam Engine Prints
 
The crux is whether the OP understands what's going on in the code or do they just copy/paste and are happy it works. Unfortunately the latter is often the more likely scenario (not saying it is in this case).

That's where the difference is and not in whether we post fully coded solutions.

I prefer coded solutions but at the very least I think a coded solution should be accompanied by a narrative explanation consisting of:

1. A clear definition of the problem (unless OP is very specific with their question)
2. The steps needed to solve the problem
3. What the code is doing

Without that narrative the code is only of partial help or may only apply to a very specific set of circumstances. This is when you start to see the same people asking very similar questions because the code they got last time doesn't quite do what they now need to do.

Anyway, it's a problem that will never go away. So I live with it :)

--
Tek-Tips Forums is Member Supported. Click Here to donate

<honk>*:O)</honk>

Tyres: Mine's a pint of the black stuff.
Mike: You can't drink a pint of Bovril.


 
true enough, Foamcow. it's best practice to my mind to comment code whether you're developing for yourself or for others.
 
I think we all have our philosophies arounf how much help we give. My own is give a man and fish and he'll eat for the day, teach him how to fish and he'll eat for life.
Quite often I have a look at previous posts from the OP and if they tend to be of the same level e.g. basic quiestions about syntax I refer to the manual. If the majority are helpfull replies I just asume this particular problem is something that is really foxing for what ever reason.
 
ingresman said:
My own is give a man and fish and he'll eat for the day, teach him how to fish and he'll eat for life

this is oft - quoted. And i think we'd all agree with the philosophy. The question begs, and here's where are collective philosophies are free to differ, as to what is the best way to teach someone to fish. I'm of the immersive, code review school. Each to their own.
 
I have been doing this for about a year now. I read a book and reference a couple others every now and then. For the most part, I credit most of what I know this this forum and people like jpadie that have consistently provided valuable help.

I regularly spend hours online reading articles and sample code. I keep a great number of links I go back to. Google is also a frequent stop. This works for me.

These are my rules before I post a question:
1) Think if I've done similar work elsewhere
2) Consult one of my books
3) Search tek-tips (if no results - post question)
4) php.net
5) google

As you can see, even after I post a question, I continue searching for an answer - I have found that this approach has helped me a lot and often find multiple ways to solve my problem.

jpadie has provided me with code (like the chat) which I put apart and back together so that I can learn. I am no expert but I think I've come a long way from my 1st post.

I am grateful for this forum and its members and hope things continue as they are.




--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
Thank you for you help guys, it worked! :)
And you are the first one to noticed that i've missspelled really jpadie, only mispelled is with 2 SS so misspelled. ^^

-------------------------------------
I am a progammer.... no realy.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top