1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Anyone see whats wrong with this?

Discussion in 'PHP' started by Fiverscripts, Oct 1, 2013.

  1. #1
    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!
     
    Solved! View solution.
    Fiverscripts, Oct 1, 2013 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    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.
     
    PoPSiCLe, Oct 1, 2013 IP
    Fiverscripts likes this.
  3. malky66

    malky66 Acclaimed Member

    Messages:
    3,996
    Likes Received:
    2,248
    Best Answers:
    88
    Trophy Points:
    515
    #3
    ...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
     
    malky66, Oct 1, 2013 IP
    Fiverscripts likes this.
  4. Fiverscripts

    Fiverscripts Moderator Staff

    Messages:
    1,839
    Likes Received:
    42
    Best Answers:
    1
    Trophy Points:
    370
    #4
    intrigued.. what would be a better way? the code works and returns a nice table,..

    looking into the id now

    Matt
     
    Fiverscripts, Oct 1, 2013 IP
  5. malky66

    malky66 Acclaimed Member

    Messages:
    3,996
    Likes Received:
    2,248
    Best Answers:
    88
    Trophy Points:
    515
    #5
    mysql functions are now deprecated, you should look at mysqli or PDO, it's much more secure
     
    malky66, Oct 1, 2013 IP
    ryan_uk and Arick unirow like this.
  6. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #6
    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):
     
    PoPSiCLe, Oct 1, 2013 IP
    Fiverscripts likes this.
  7. #7
    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.
     
    deathshadow, Oct 1, 2013 IP
  8. pmf123

    pmf123 Notable Member

    Messages:
    1,447
    Likes Received:
    75
    Best Answers:
    0
    Trophy Points:
    215
    #8
    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
     
    pmf123, Oct 2, 2013 IP
  9. Fiverscripts

    Fiverscripts Moderator Staff

    Messages:
    1,839
    Likes Received:
    42
    Best Answers:
    1
    Trophy Points:
    370
    #9
    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?
     
    Fiverscripts, Oct 4, 2013 IP
  10. pmf123

    pmf123 Notable Member

    Messages:
    1,447
    Likes Received:
    75
    Best Answers:
    0
    Trophy Points:
    215
    #10
    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.
     
    pmf123, Oct 4, 2013 IP
  11. Fiverscripts

    Fiverscripts Moderator Staff

    Messages:
    1,839
    Likes Received:
    42
    Best Answers:
    1
    Trophy Points:
    370
    #11
    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?
     
    Fiverscripts, Oct 4, 2013 IP
  12. malky66

    malky66 Acclaimed Member

    Messages:
    3,996
    Likes Received:
    2,248
    Best Answers:
    88
    Trophy Points:
    515
    #12
    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):
     
    malky66, Oct 4, 2013 IP
    ryan_uk and Fiverscripts like this.
  13. Fiverscripts

    Fiverscripts Moderator Staff

    Messages:
    1,839
    Likes Received:
    42
    Best Answers:
    1
    Trophy Points:
    370
    #13

    perrrrrrfecct mate working! :) this is all very new code to me.. thanks so much for all the info :) learning a lot
     
    Fiverscripts, Oct 4, 2013 IP
  14. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #14
    @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
     
    deathshadow, Oct 5, 2013 IP
    ryan_uk, Fiverscripts and malky66 like this.
  15. malky66

    malky66 Acclaimed Member

    Messages:
    3,996
    Likes Received:
    2,248
    Best Answers:
    88
    Trophy Points:
    515
    #15
    Nice one @deathshadow, another lesson learnt:)
     
    malky66, Oct 5, 2013 IP
  16. Fiverscripts

    Fiverscripts Moderator Staff

    Messages:
    1,839
    Likes Received:
    42
    Best Answers:
    1
    Trophy Points:
    370
    #16
    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..
     
    Fiverscripts, Oct 5, 2013 IP
  17. malky66

    malky66 Acclaimed Member

    Messages:
    3,996
    Likes Received:
    2,248
    Best Answers:
    88
    Trophy Points:
    515
    #17
    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.
     
    malky66, Oct 5, 2013 IP
  18. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #18
    ... 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...
     
    Last edited: Oct 6, 2013
    deathshadow, Oct 6, 2013 IP
    Arick unirow and ryan_uk like this.
  19. Fiverscripts

    Fiverscripts Moderator Staff

    Messages:
    1,839
    Likes Received:
    42
    Best Answers:
    1
    Trophy Points:
    370
    #19
    based on the code above.. what's the easiest way to implement pagination? any tips.. sorry to be such a newbie with this code..
     
    Fiverscripts, Oct 8, 2013 IP
  20. ryan_uk

    ryan_uk Illustrious Member

    Messages:
    3,983
    Likes Received:
    1,022
    Best Answers:
    33
    Trophy Points:
    465
    #20
    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).
     
    ryan_uk, Oct 8, 2013 IP