Jump to content

how to sort database by column in php


chris93

Recommended Posts

<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>
 

 

Link to comment
Share on other sites

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 by benanamen
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.