chris93 Posted November 8, 2016 Share Posted November 8, 2016 <b></b>i have written a code that connects to a database using Xampp in php... but it does not sort the database at all. <?php //Step1 $db = mysqli_connect('localhost','root','123','first_db') or die('Error connecting to MySQL server.'); ?> <html> <head> </head> <body> <h1>PHP connect to MySQL</h1> <?php $sql ="INSERT INTO users (id,name,password) VALUES ('7','chris','444')"; mysqli_query($db,$sql); $sql = "SELECT * FROM users ORDER BY id 'ASC'"; $query = mysqli_query($db, $sql); //Step2 $query = "SELECT * FROM users"; mysqli_query($db, $query) or die('Error querying database.'); //Step3 $result = mysqli_query($db, $query); //$row = mysqli_fetch_array($result); while ($row = mysqli_fetch_array($result)) { echo $row[0] . ' ' . $row[1] . ': '. $row[2] .'<br />'; } //Step 4 mysqli_close($db); ?> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/302493-how-to-sort-database-by-column-in-php/ Share on other sites More sharing options...
benanamen Posted November 8, 2016 Share Posted November 8, 2016 (edited) Why are you querying the users table twice. You are just overwriting the first query. You need to ORDER BY on the column you want sorted by. You don't need to manually close the DB connection. It will close automatically when the script finishes running. Also, select specific column names, not SELECT * and use the column name results, not row[0]. Who the heck is going to know what you're dealing with when reading the script? Edited November 8, 2016 by benanamen Quote Link to comment https://forums.phpfreaks.com/topic/302493-how-to-sort-database-by-column-in-php/#findComment-1539109 Share on other sites More sharing options...
Barand Posted November 8, 2016 Share Posted November 8, 2016 And remove the quotes from 'ASC'. (As the default is ASC you don't really need it.) SELECT * FROM users ORDER BY id Quote Link to comment https://forums.phpfreaks.com/topic/302493-how-to-sort-database-by-column-in-php/#findComment-1539110 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.