Hi all, Am coding a little experiment at the moment.. and something has totally stumped me.. Ok i have a mysql database.. with the table members which contains, yeh you guessed it couple of members or users Inside a php/html page all im doing is echoing a table to return the current users here is the code: <?php include('db_connect.php'); $sql = "SELECT * FROM `members` LIMIT 0, 15"; $result = mysql_query($sql) or die(mysql_error()); echo "<center><table border='1' padding='10' cellpadding='10' class='recordstable'> <tr> <th>ID</th> <th>Username</th> <th>Password</th> <th>Delete</th> </tr>"; while ($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['username'] . "</td>"; echo "<td>" . $row['password'] . "</td>"; echo "<td><a href=\"delete_user.php?id=$row[id]\">Delete</a></td>"; echo "</tr>"; } echo "</table></center>"; ?> PHP: So as you can see.. im connecting to database, returning a table with the current members in and displaying it nicely on page.. this works perfectly My next item as you can see is im creating a simple link to "delete_users.php" this should trigger a delete on the record i have selected my code for this is: <?php include('db_connect.php'); $sql="DELETE FROM members WHERE ID='$id'"; $query = mysql_query($sql); if ($query) { header("location:test.php"); } else { echo 'error' . mysql_error(); } ?> PHP: Now when i click that.. it obviously carrys the code out "fine" because the page is then redirected to test.php, however it doesn't delete the record... What have i done wrong? thanks in advanced.. its probs something really stupid and obvious but i just cant see it and its frustrating as always with code!
You haven't defined $id anywhere. Echo out the $sql variable, and you'll see that the DELETE statement probably will show WHERE ID='' - hence nothing will be deleted. That being said - the HTML in this experiment is atrocious, and horribly outdated.
...also you have an uppercase ID in your delete query: $sql="DELETE FROM members WHERE ID='$id'"; Code (markup): But in your select query it is lowercase: echo "<td>" . $row['id'] . "</td>"; Code (markup): shouldn't it be lowercase in the delete query? but as @PoPSiCLe says that code is very outdated
intrigued.. what would be a better way? the code works and returns a nice table,.. looking into the id now Matt
As for the HTML.... <center> and settings options for the <table> in the tag is deprecated, and should not be used. Use CSS to style and format the content. You should also (although it's technically not needed) use <thead> around the row of <th> and <tbody> around the content of the table. Something like this: <table class="recordstable"> <thead> <tr> <th>ID</th> <th>Username</th> <th>Password</th> <th>Delete</th> </tr> </thead> <tbody> <tr> <content goes here> </tr> </tbody> </table> Code (markup): and then, in the CSS-file you'll have something akin to this: .recordstable { border: 1px solid #000; padding: 10px; } .recordstable td, .recordstable th { padding: 10px; } Code (markup):
As PoPSiCLe pointed out much more politely than I ever could, your markup has it's head wedged up 1997's backside.... the bizarroland indenting surely isn't helping matters either... much less still using the mysql_ functions we've been told for EIGHT YEARS to stop using, hence the giant red warning boxes in the manual to that end. You're missing a half dozen important attributes like scope, tags like thead and tbody, and are using attributes that have no business on a page after 1998 like cellpadding and border. Also a decent example of what's wrong with using double quotes for strings in PHP. (which usually results in crappy output and pointless escapes) Likewise since you should be using PDO or mysqli instead of mysql_ you should be using prepared queries so you know $id is set right... and as others mentioned, just where are you even setting a value for $id?!? To clean up the first snippet: <?php include('dbConnect.php'); /* assumes this creates a PDO object named $db */ $statement = $db->exec('SELECT * FROM members LIMIT 0, 15'); echo ' <table class="recordsTable"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Username</th> <th scope="col">Password</th> <th scope="col">Delete</th> </tr> </thead><tbody>'; while ($row = $db->fetch()) echo ' <tr> <th scope="row">', $row['id'], '</th> <td>', $row['username'], '</td> <td>', $row['password'], '</td> <td><a href="delete_user.php?id=', $row[id], '">Delete</a></td> </tr>'; echo ' </tbody> </table>'; ?> Code (markup): Dragging it kicking and screaming into semantic markup -- Everything else belonging in your CSS... As to the second snippet: <?php include('dbConnect.php'); /* assumes this creates a PDO object named $db */ $stmt = $db->prepare(' DELETE FROM members WHERE id = :id '); /* where exactly are you SETTING $id ?!? is that GET, POST? */ if ( $stmt->execute(array(':id' => $id)) && ($db->errorCode == 0) ) { if ($stmt->rowCount() > 0) { echo 'Deleted ',$stmt->rowCount(),' rows'; } else { echo 'Invalid user ID or user not found'; } } else echo 'PDO Error ', $db->errorCode, ': ',$db->errorInfo[2]; ?> Code (markup): I would also advise against playing stupid header redirect tricks since that's just a waste of a handshake. You want to call test.php, use include or require.
you need to add this at the start of your delete page: $id = $id ? $id : ''; or $id = $_REQUEST["id"]; depending on your version of PHP and whats supported
Hi all thanks for your reply s.. new code to me hence small project to learn this.. errm i have tested the above code and i get "Call to undefined method PDO::fetch()" error.. any ideas why? it writes the table headers but data is not returned and that error appears? im using: $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password'); Code (markup): as my PDO? in database connect.. is this the correct method?
I 've never used PDO, this is what i use: $server = 'localhost'; $admin = 'xxxxxx'; $adminpass = 'xxxxxx'; $db = 'xxxxx'; $sqlsession=mysql_connect("$server","$admin","$adminpass"); mysql_select_db("$db"); which i guess is the old method.
that was my original method but this PDO connection is more secure.. read up ^^ apparently.. Id rather learn a new more improved way and im thankfully for both the above users for the information above almost there.. it appears connected.. just not fetching?
Try this: dbConnect.php <?php define ('DB_HOST', 'localhost'); define ('DB_NAME', 'dbname'); define ('DB_USER', 'username'); define ('DB_PASS', 'password'); try { $db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS); $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db-> exec("set names utf8"); } catch(PDOException $e) { echo $e->getMessage(); } ?> Code (markup): <?php include('dbconnect.php'); /* assumes this creates a PDO object named $db */ $stmt = $db->prepare('SELECT * FROM members LIMIT 0, 15'); echo ' <table class="recordsTable"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Username</th> <th scope="col">Password</th> <th scope="col">Delete</th> </tr> </thead><tbody>'; if ($stmt->execute(array())) { while ($row = $stmt->fetch()) { echo ' <tr> <th scope="row">', $row['id'], '</th> <td>', $row['username'], '</td> <td>', $row['password'], '</td> <td><a href="delete_user.php?id=', $row['id'], '">Delete</a></td> </tr>';}} echo ' </tbody> </table>'; ?> Code (markup):
perrrrrrfecct mate working! this is all very new code to me.. thanks so much for all the info learning a lot
@malky66 -- I would highly advise AGAINST sticking the connection info in DEFINE, since that opens a MASSIVE security hole since the connection info is then "always available" to ANY code... No matter what the re-re's at turdpress might tell you. It's like the OTHER reason not to use mysql_ functions being the connection is global in scope -- which is why putting $db global in scope is rubbish too. With PDO or mysqli you can at least keep the connection object local and only pass it to where it's needed. See my explanation here: http://techtalkin.com/Thread-Securing-your-PHP-taking-it-further-than-most
looks like we are all learning from this.. all good this end im experimental css styling with it at the moment.. seems to style the first row differently.. but its obviously poor css styling on my front! I have awarded best answer to @deathshadow on the grounds he has given me the most info.. (the original code tidy up post) However i am massively grateful to everyone else who has helped with this, @malky66 this is the second or 3rd time you have helped me out on the forum technical knowledge wise and its good to see we still have some good members around here! thanks everyone really learned something from this..
That's the thing with php and programming in general, no matter how much you think you know, there's always something new to learn..and it's why we always need people like @deathshadow, his knowledge is invaluable.
... and I've been programming for close to three decades now, and I'm STILL learning. I put an hour aside every night before bed to read php.net as the MASSIVE function library built into PHP most always means "yeah, there's a function for that" -- and letting PHP's functions do the work instead of brute force coding is ALWAYS faster in an interpreted language. But as I've said for ages, there's always something new to learn. The day you think you know all there is to know, is the day the rest of the world leaves you behind. Probably why I'm so annoyed with developers who never manage to extract their heads from 1997's backside. (or try to bring back the worst of 1990's practices with asshattery like HTML 5)... but as the old saying goes, those who fail to learn history...
based on the code above.. what's the easiest way to implement pagination? any tips.. sorry to be such a newbie with this code..
Look up OFFSET and LIMIT (you can specify an offset in LIMIT) for MySQL and use URL parameters to specify which page (take a look in Google for MySQL PHP pagination as there are plenty of examples).